@crawlee/playwright 4.0.0-beta.15 → 4.0.0-beta.151

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 +14 -14
  2. package/index.d.ts +2 -2
  3. package/index.js +1 -1
  4. package/internals/adaptive-playwright-crawler.d.ts +116 -63
  5. package/internals/adaptive-playwright-crawler.js +320 -266
  6. package/internals/enqueue-links/click-elements.d.ts +36 -64
  7. package/internals/enqueue-links/click-elements.js +65 -67
  8. package/internals/playwright-browser-pool.d.ts +71 -0
  9. package/internals/playwright-browser-pool.js +61 -0
  10. package/internals/playwright-crawler.d.ts +180 -125
  11. package/internals/playwright-crawler.js +68 -63
  12. package/internals/playwright-launcher.d.ts +32 -18
  13. package/internals/playwright-launcher.js +23 -17
  14. package/internals/utils/playwright-utils.d.ts +54 -41
  15. package/internals/utils/playwright-utils.js +110 -121
  16. package/internals/utils/rendering-type-prediction.d.ts +25 -11
  17. package/internals/utils/rendering-type-prediction.js +81 -27
  18. package/package.json +14 -18
  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,24 +1,25 @@
1
- import type { BrowserCrawlerOptions, BrowserCrawlingContext, BrowserHook, GetUserDataFromRequest, RequestHandler, RouterRoutes } from '@crawlee/browser';
2
- import { BrowserCrawler, Configuration } from '@crawlee/browser';
3
- import type { PlaywrightController, PlaywrightPlugin } from '@crawlee/browser-pool';
1
+ import type { BrowserCrawlerOptions, BrowserCrawlingContext, BrowserHook, ContextPipeline, CrawlingContext, GetUserDataFromRequest, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '@crawlee/browser';
2
+ import { BrowserCrawler } from '@crawlee/browser';
4
3
  import type { Dictionary } from '@crawlee/types';
5
4
  // @ts-ignore optional peer dependency or compatibility with es2022
6
5
  import type { LaunchOptions, Page, Response } from 'playwright';
6
+ import { z } from 'zod';
7
7
  import type { PlaywrightLaunchContext } from './playwright-launcher.js';
8
- import type { DirectNavigationOptions, PlaywrightContextUtils } from './utils/playwright-utils.js';
9
- export interface PlaywrightCrawlingContext<UserData extends Dictionary = Dictionary> extends BrowserCrawlingContext<Page, Response, PlaywrightController, UserData>, PlaywrightContextUtils {
8
+ import type { DirectNavigationOptions, HandleCloudflareChallengeOptions, PlaywrightContextUtils } from './utils/playwright-utils.js';
9
+ export type PlaywrightGotoOptions = NonNullable<Parameters<Page['goto']>[1]>;
10
+ export interface PlaywrightCrawlingContext<UserData extends Dictionary = any> extends BrowserCrawlingContext<Page, Response, UserData, PlaywrightGotoOptions>, PlaywrightContextUtils {
10
11
  }
11
- // @ts-ignore optional peer dependency or compatibility with es2022
12
- export interface PlaywrightHook extends BrowserHook<PlaywrightCrawlingContext, PlaywrightGotoOptions> {
13
- }
14
- export type PlaywrightGotoOptions = Parameters<Page['goto']>[1];
15
- export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension> extends BrowserCrawlerOptions<Page, Response, PlaywrightController, PlaywrightCrawlingContext, ContextExtension, ExtendedContext, {
16
- browserPlugins: [PlaywrightPlugin];
17
- }> {
12
+ export type PlaywrightHook<UserData extends Dictionary = any> = BrowserHook<PlaywrightCrawlingContext<UserData>>;
13
+ export interface PlaywrightCrawlerOptions<ContextExtension = Dictionary<never>, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<PlaywrightCrawlingContext['request']>>, StatisticStateExtension extends object = {}> extends BrowserCrawlerOptions<Page, Response, PlaywrightCrawlingContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
18
14
  /**
19
15
  * The same options as used by {@link launchPlaywright}.
20
16
  */
21
17
  launchContext?: PlaywrightLaunchContext;
18
+ /**
19
+ * Whether to run browser in headless mode. Defaults to `true`.
20
+ * Can be also set via {@link Configuration}.
21
+ */
22
+ headless?: boolean;
22
23
  /**
23
24
  * Function that is called to process each request.
24
25
  *
@@ -26,8 +27,6 @@ export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext
26
27
  * - `request` is an instance of the {@link Request} object with details about the URL to open, HTTP method etc.
27
28
  * - `page` is an instance of the `Playwright`
28
29
  * [`Page`](https://playwright.dev/docs/api/class-page)
29
- * - `browserController` is an instance of the
30
- * [`BrowserController`](https://github.com/apify/browser-pool#browsercontroller),
31
30
  * - `response` is an instance of the `Playwright`
32
31
  * [`Response`](https://playwright.dev/docs/api/class-response),
33
32
  * which is the main resource response as returned by `page.goto(request.url)`.
@@ -43,28 +42,28 @@ export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext
43
42
  * The exceptions are logged to the request using the
44
43
  * {@link Request.pushErrorMessage} function.
45
44
  */
46
- requestHandler?: RequestHandler<ExtendedContext>;
45
+ requestHandler?: RouterHandler<ExtendedContext, Routes> | RequestHandler<ExtendedContext>;
47
46
  /**
48
47
  * Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies
49
- * or browser properties before navigation. The function accepts two parameters, `crawlingContext` and `gotoOptions`,
50
- * which are passed to the `page.goto()` function the crawler calls to navigate.
48
+ * or browser properties before navigation. The function receives the `crawlingContext`; the options object
49
+ * forwarded to `page.goto()` is available as `crawlingContext.gotoOptions` and can be mutated in place.
50
+ * A hook may optionally return a partial object whose properties are merged into the crawling context
51
+ * (e.g. to override context members for subsequent hooks and pipeline stages).
51
52
  * Example:
52
53
  * ```
53
54
  * preNavigationHooks: [
54
- * async (crawlingContext, gotoOptions) => {
55
- * const { page } = crawlingContext;
55
+ * async ({ page, gotoOptions }) => {
56
56
  * await page.evaluate((attr) => { window.foo = attr; }, 'bar');
57
+ * gotoOptions.timeout = 60_000;
57
58
  * },
58
59
  * ]
59
60
  * ```
60
- *
61
- * Modyfing `pageOptions` is supported only in Playwright incognito.
62
- * See {@link PrePageCreateHook}
63
61
  */
64
- preNavigationHooks?: PlaywrightHook[];
62
+ preNavigationHooks?: BrowserHook<PlaywrightCrawlingContext<GetUserDataFromRequest<ExtendedContext['request']>>, ContextExtension>[];
65
63
  /**
66
64
  * Async functions that are sequentially evaluated after the navigation. Good for checking if the navigation was successful.
67
- * The function accepts `crawlingContext` as the only parameter.
65
+ * The function accepts `crawlingContext` as the only parameter. A hook may optionally return a partial object
66
+ * whose properties are merged into the crawling context (e.g. to override `response` after solving a challenge).
68
67
  * Example:
69
68
  * ```
70
69
  * postNavigationHooks: [
@@ -77,7 +76,7 @@ export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext
77
76
  * ]
78
77
  * ```
79
78
  */
80
- postNavigationHooks?: PlaywrightHook[];
79
+ postNavigationHooks?: BrowserHook<PlaywrightCrawlingContext<GetUserDataFromRequest<ExtendedContext['request']>>, ContextExtension>[];
81
80
  }
82
81
  /**
83
82
  * Provides a simple framework for parallel crawling of web pages
@@ -90,24 +89,26 @@ export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext
90
89
  * If the target website doesn't need JavaScript, consider using {@link CheerioCrawler},
91
90
  * which downloads the pages using raw HTTP requests and is about 10x faster.
92
91
  *
93
- * The source URLs are represented using {@link Request} objects that are fed from
94
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link PlaywrightCrawlerOptions.requestList}
95
- * or {@link PlaywrightCrawlerOptions.requestQueue} constructor options, respectively.
92
+ * The source URLs are represented using {@link Request} objects that are fed from the
93
+ * {@link IRequestManager|request manager} provided via the {@link PlaywrightCrawlerOptions.requestManager|`requestManager`}
94
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
95
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
96
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
97
+ * result as `requestManager`.
96
98
  *
97
- * If both {@link PlaywrightCrawlerOptions.requestList} and {@link PlaywrightCrawlerOptions.requestQueue} are used,
98
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
99
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
99
+ * > The {@link PlaywrightCrawlerOptions.requestList|`requestList`} and {@link PlaywrightCrawlerOptions.requestQueue|`requestQueue`}
100
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
100
101
  *
101
102
  * The crawler finishes when there are no more {@link Request} objects to crawl.
102
103
  *
103
104
  * `PlaywrightCrawler` opens a new Chrome page (i.e. tab) for each {@link Request} object to crawl
104
105
  * and then calls the function provided by user as the {@link PlaywrightCrawlerOptions.requestHandler} option.
105
106
  *
106
- * New pages are only opened when there is enough free CPU and memory available,
107
- * using the functionality provided by the {@link AutoscaledPool} class.
108
- * All {@link AutoscaledPool} configuration options can be passed to the {@link PlaywrightCrawlerOptions.autoscaledPoolOptions}
109
- * parameter of the `PlaywrightCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
110
- * {@link AutoscaledPoolOptions} are available directly in the `PlaywrightCrawler` constructor.
107
+ * New pages are only opened when there is enough free CPU and memory available, as judged by the crawler's
108
+ * {@link ConcurrencySystem}.
109
+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
110
+ * `PlaywrightCrawler` constructor, or, for finer control, by injecting a pre-configured
111
+ * {@link ConcurrencySystem|`concurrencySystem`}.
111
112
  *
112
113
  * Note that the pool of Playwright instances is internally managed by the [BrowserPool](https://github.com/apify/browser-pool) class.
113
114
  *
@@ -142,99 +143,153 @@ export interface PlaywrightCrawlerOptions<ContextExtension = {}, ExtendedContext
142
143
  * ```
143
144
  * @category Crawlers
144
145
  */
145
- export declare class PlaywrightCrawler<ContextExtension = {}, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension> extends BrowserCrawler<Page, Response, PlaywrightController, {
146
- browserPlugins: [PlaywrightPlugin];
147
- }, LaunchOptions, PlaywrightCrawlingContext, ContextExtension, ExtendedContext> {
148
- readonly config: Configuration;
146
+ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<PlaywrightCrawlingContext['request']>>, StatisticStateExtension extends object = {}> extends BrowserCrawler<Page, Response, LaunchOptions, PlaywrightCrawlingContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
147
+ /**
148
+ * @internal
149
+ */
149
150
  protected static optionsShape: {
150
- // @ts-ignore optional peer dependency or compatibility with es2022
151
- browserPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
152
- // @ts-ignore optional peer dependency or compatibility with es2022
153
- launcher: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
154
- // @ts-ignore optional peer dependency or compatibility with es2022
155
- ignoreIframes: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
156
- // @ts-ignore optional peer dependency or compatibility with es2022
157
- ignoreShadowRoots: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
158
- // @ts-ignore optional peer dependency or compatibility with es2022
159
- navigationTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
160
- // @ts-ignore optional peer dependency or compatibility with es2022
161
- preNavigationHooks: import("ow").ArrayPredicate<unknown> & import("ow").BasePredicate<unknown[] | undefined>;
162
- // @ts-ignore optional peer dependency or compatibility with es2022
163
- postNavigationHooks: import("ow").ArrayPredicate<unknown> & import("ow").BasePredicate<unknown[] | undefined>;
164
- // @ts-ignore optional peer dependency or compatibility with es2022
165
- launchContext: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
166
- // @ts-ignore optional peer dependency or compatibility with es2022
167
- headless: import("ow").AnyPredicate<string | boolean>;
168
- // @ts-ignore optional peer dependency or compatibility with es2022
169
- sessionPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
170
- // @ts-ignore optional peer dependency or compatibility with es2022
171
- persistCookiesPerSession: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
172
- // @ts-ignore optional peer dependency or compatibility with es2022
173
- useSessionPool: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
174
- // @ts-ignore optional peer dependency or compatibility with es2022
175
- proxyConfiguration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
176
- // @ts-ignore optional peer dependency or compatibility with es2022
177
- contextPipelineBuilder: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
178
- // @ts-ignore optional peer dependency or compatibility with es2022
179
- extendContext: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
180
- // @ts-ignore optional peer dependency or compatibility with es2022
181
- requestList: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
182
- // @ts-ignore optional peer dependency or compatibility with es2022
183
- requestQueue: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
184
- // @ts-ignore optional peer dependency or compatibility with es2022
185
- requestHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
186
- // @ts-ignore optional peer dependency or compatibility with es2022
187
- requestHandlerTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
188
- // @ts-ignore optional peer dependency or compatibility with es2022
189
- errorHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
190
- // @ts-ignore optional peer dependency or compatibility with es2022
191
- failedRequestHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
192
- // @ts-ignore optional peer dependency or compatibility with es2022
193
- maxRequestRetries: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
194
- // @ts-ignore optional peer dependency or compatibility with es2022
195
- sameDomainDelaySecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
196
- // @ts-ignore optional peer dependency or compatibility with es2022
197
- maxSessionRotations: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
198
- // @ts-ignore optional peer dependency or compatibility with es2022
199
- maxRequestsPerCrawl: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
200
- // @ts-ignore optional peer dependency or compatibility with es2022
201
- maxCrawlDepth: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
202
- // @ts-ignore optional peer dependency or compatibility with es2022
203
- autoscaledPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
204
- // @ts-ignore optional peer dependency or compatibility with es2022
205
- statusMessageLoggingInterval: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
206
- // @ts-ignore optional peer dependency or compatibility with es2022
207
- statusMessageCallback: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
208
- // @ts-ignore optional peer dependency or compatibility with es2022
209
- retryOnBlocked: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
210
- // @ts-ignore optional peer dependency or compatibility with es2022
211
- respectRobotsTxtFile: import("ow").AnyPredicate<boolean | object>;
212
- // @ts-ignore optional peer dependency or compatibility with es2022
213
- onSkippedRequest: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
214
- // @ts-ignore optional peer dependency or compatibility with es2022
215
- httpClient: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
216
- // @ts-ignore optional peer dependency or compatibility with es2022
217
- minConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
218
- // @ts-ignore optional peer dependency or compatibility with es2022
219
- maxConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
220
- // @ts-ignore optional peer dependency or compatibility with es2022
221
- maxRequestsPerMinute: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
222
- // @ts-ignore optional peer dependency or compatibility with es2022
223
- keepAlive: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
224
- // @ts-ignore optional peer dependency or compatibility with es2022
225
- log: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
226
- // @ts-ignore optional peer dependency or compatibility with es2022
227
- experiments: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
228
- // @ts-ignore optional peer dependency or compatibility with es2022
229
- statisticsOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
151
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
152
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
153
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
154
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
155
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
156
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
157
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
158
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
159
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
160
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
161
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
162
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
163
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
164
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
165
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
166
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
167
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
168
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
169
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
170
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
171
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
172
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
173
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
174
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
175
+ requestQueue: z.ZodOptional<z.ZodEnum<{
176
+ deferred: "deferred";
177
+ writeThrough: "writeThrough";
178
+ }>>;
179
+ }, z.core.$strict>]>>;
180
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
181
+ // @ts-ignore optional peer dependency or compatibility with es2022
182
+ httpClient: z.ZodOptional<z.ZodCustom<import("@crawlee/http-client").BaseHttpClient, import("@crawlee/http-client").BaseHttpClient>>;
183
+ // @ts-ignore optional peer dependency or compatibility with es2022
184
+ configuration: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").Configuration, import("@crawlee/browser").Configuration>>;
185
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
186
+ // @ts-ignore optional peer dependency or compatibility with es2022
187
+ eventManager: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").EventManager, import("@crawlee/browser").EventManager>>;
188
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
189
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
190
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
191
+ initialConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
192
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
193
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
194
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
195
+ id: z.ZodOptional<z.ZodString>;
196
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
197
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
198
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
199
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
200
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
201
+ browserPoolBuilder: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
202
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
203
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
204
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
205
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
206
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
207
+ headless: z.ZodOptional<z.ZodBoolean>;
208
+ launcher: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
230
209
  };
210
+ /** @internal */
211
+ protected static optionsSchema: z.ZodObject<{
212
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
213
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
214
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
215
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
216
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
217
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
218
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
219
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
220
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
221
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
222
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
223
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
224
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
225
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
226
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
227
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
228
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
229
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
230
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
231
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
232
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
233
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
234
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
235
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
236
+ requestQueue: z.ZodOptional<z.ZodEnum<{
237
+ deferred: "deferred";
238
+ writeThrough: "writeThrough";
239
+ }>>;
240
+ }, z.core.$strict>]>>;
241
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
242
+ // @ts-ignore optional peer dependency or compatibility with es2022
243
+ httpClient: z.ZodOptional<z.ZodCustom<import("@crawlee/http-client").BaseHttpClient, import("@crawlee/http-client").BaseHttpClient>>;
244
+ // @ts-ignore optional peer dependency or compatibility with es2022
245
+ configuration: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").Configuration, import("@crawlee/browser").Configuration>>;
246
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
247
+ // @ts-ignore optional peer dependency or compatibility with es2022
248
+ eventManager: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").EventManager, import("@crawlee/browser").EventManager>>;
249
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
250
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
251
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
252
+ initialConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
253
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
254
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
255
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
256
+ id: z.ZodOptional<z.ZodString>;
257
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
258
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
259
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
260
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
261
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
262
+ browserPoolBuilder: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
263
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
264
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
265
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
266
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
267
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
268
+ headless: z.ZodOptional<z.ZodBoolean>;
269
+ launcher: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
270
+ }, z.core.$strict>;
231
271
  /**
232
272
  * All `PlaywrightCrawler` parameters are passed via an options object.
233
273
  */
234
- constructor(options?: PlaywrightCrawlerOptions<ExtendedContext>, config?: Configuration);
235
- protected _navigationHandler(crawlingContext: PlaywrightCrawlingContext, gotoOptions: DirectNavigationOptions): Promise<Response | null>;
274
+ constructor(options?: PlaywrightCrawlerOptions<ContextExtension, ExtendedContext, Routes, StatisticStateExtension>);
275
+ protected buildContextPipeline(): ContextPipeline<CrawlingContext, PlaywrightCrawlingContext>;
276
+ protected navigationHandler(crawlingContext: PlaywrightCrawlingContext, gotoOptions: DirectNavigationOptions): Promise<Response | null>;
236
277
  private enhanceContext;
237
278
  }
279
+ /**
280
+ * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
281
+ * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
282
+ *
283
+ * **Example usage**
284
+ * ```ts
285
+ * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
286
+ *
287
+ * const crawler = new PlaywrightCrawler({
288
+ * postNavigationHooks: [handleCloudflareChallengeHook()],
289
+ * });
290
+ * ```
291
+ */
292
+ export declare function handleCloudflareChallengeHook(options?: HandleCloudflareChallengeOptions): PlaywrightHook;
238
293
  /**
239
294
  * Creates new {@link Router} instance that works based on request labels.
240
295
  * This instance can then serve as a `requestHandler` of your {@link PlaywrightCrawler}.
@@ -259,6 +314,6 @@ export declare class PlaywrightCrawler<ContextExtension = {}, ExtendedContext ex
259
314
  * await crawler.run();
260
315
  * ```
261
316
  */
262
- // @ts-ignore optional peer dependency or compatibility with es2022
263
- export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): import("@crawlee/browser").RouterHandler<Context>;
264
- //# sourceMappingURL=playwright-crawler.d.ts.map
317
+ export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
318
+ export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
319
+ export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;
@@ -1,6 +1,7 @@
1
- import { BrowserCrawler, Configuration, RequestState, Router } from '@crawlee/browser';
2
- import ow from 'ow';
3
- import { PlaywrightLauncher } from './playwright-launcher.js';
1
+ import { assertBrowserPoolNotConfigured, BrowserCrawler, RequestState, Router, serviceLocator } from '@crawlee/browser';
2
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
3
+ import { z } from 'zod';
4
+ import { playwrightBrowserPool, remotePlaywrightBrowserPool } from './playwright-browser-pool.js';
4
5
  import { gotoExtended, playwrightUtils } from './utils/playwright-utils.js';
5
6
  /**
6
7
  * Provides a simple framework for parallel crawling of web pages
@@ -13,24 +14,26 @@ import { gotoExtended, playwrightUtils } from './utils/playwright-utils.js';
13
14
  * If the target website doesn't need JavaScript, consider using {@link CheerioCrawler},
14
15
  * which downloads the pages using raw HTTP requests and is about 10x faster.
15
16
  *
16
- * The source URLs are represented using {@link Request} objects that are fed from
17
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link PlaywrightCrawlerOptions.requestList}
18
- * or {@link PlaywrightCrawlerOptions.requestQueue} constructor options, respectively.
17
+ * The source URLs are represented using {@link Request} objects that are fed from the
18
+ * {@link IRequestManager|request manager} provided via the {@link PlaywrightCrawlerOptions.requestManager|`requestManager`}
19
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
20
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
21
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
22
+ * result as `requestManager`.
19
23
  *
20
- * If both {@link PlaywrightCrawlerOptions.requestList} and {@link PlaywrightCrawlerOptions.requestQueue} are used,
21
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
22
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
24
+ * > The {@link PlaywrightCrawlerOptions.requestList|`requestList`} and {@link PlaywrightCrawlerOptions.requestQueue|`requestQueue`}
25
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
23
26
  *
24
27
  * The crawler finishes when there are no more {@link Request} objects to crawl.
25
28
  *
26
29
  * `PlaywrightCrawler` opens a new Chrome page (i.e. tab) for each {@link Request} object to crawl
27
30
  * and then calls the function provided by user as the {@link PlaywrightCrawlerOptions.requestHandler} option.
28
31
  *
29
- * New pages are only opened when there is enough free CPU and memory available,
30
- * using the functionality provided by the {@link AutoscaledPool} class.
31
- * All {@link AutoscaledPool} configuration options can be passed to the {@link PlaywrightCrawlerOptions.autoscaledPoolOptions}
32
- * parameter of the `PlaywrightCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
33
- * {@link AutoscaledPoolOptions} are available directly in the `PlaywrightCrawler` constructor.
32
+ * New pages are only opened when there is enough free CPU and memory available, as judged by the crawler's
33
+ * {@link ConcurrencySystem}.
34
+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
35
+ * `PlaywrightCrawler` constructor, or, for finer control, by injecting a pre-configured
36
+ * {@link ConcurrencySystem|`concurrencySystem`}.
34
37
  *
35
38
  * Note that the pool of Playwright instances is internally managed by the [BrowserPool](https://github.com/apify/browser-pool) class.
36
39
  *
@@ -66,47 +69,47 @@ import { gotoExtended, playwrightUtils } from './utils/playwright-utils.js';
66
69
  * @category Crawlers
67
70
  */
68
71
  export class PlaywrightCrawler extends BrowserCrawler {
69
- config;
72
+ /**
73
+ * @internal
74
+ */
70
75
  static optionsShape = {
71
76
  ...BrowserCrawler.optionsShape,
72
- browserPoolOptions: ow.optional.object,
73
- launcher: ow.optional.object,
74
- ignoreIframes: ow.optional.boolean,
75
- ignoreShadowRoots: ow.optional.boolean,
77
+ headless: z.boolean().optional(),
78
+ launcher: schemas.anyObject.optional(),
76
79
  };
80
+ /** @internal */
81
+ static optionsSchema = z.strictObject(PlaywrightCrawler.optionsShape);
77
82
  /**
78
83
  * All `PlaywrightCrawler` parameters are passed via an options object.
79
84
  */
80
- constructor(options = {}, config = Configuration.getGlobalConfig()) {
81
- ow(options, 'PlaywrightCrawlerOptions', ow.object.exactShape(PlaywrightCrawler.optionsShape));
82
- const { launchContext = {}, headless, ...browserCrawlerOptions } = options;
83
- const browserPoolOptions = {
84
- ...options.browserPoolOptions,
85
- };
85
+ constructor(options = {}) {
86
+ const parsedOptions = parseArgument(options, PlaywrightCrawler.optionsSchema, 'PlaywrightCrawlerOptions');
87
+ const { launchContext, headless, configuration, contextPipelineBuilder, ...browserCrawlerOptions } = parsedOptions;
86
88
  if (launchContext.proxyUrl) {
87
89
  throw new Error('PlaywrightCrawlerOptions.launchContext.proxyUrl is not allowed in PlaywrightCrawler.' +
88
90
  'Use PlaywrightCrawlerOptions.proxyConfiguration');
89
91
  }
90
- // `browserPlugins` is working when it's not overridden by `launchContext`,
91
- // which for crawlers it is always overridden. Hence the error to use the other option.
92
- if (browserPoolOptions.browserPlugins) {
93
- throw new Error('browserPoolOptions.browserPlugins is disallowed. Use launchContext.launcher instead.');
94
- }
95
- if (headless != null) {
96
- launchContext.launchOptions ??= {};
97
- launchContext.launchOptions.headless = headless;
92
+ if (options.browserPool) {
93
+ // The raw options, not the parsed ones: `launchContext` has a default, so by now it is always set.
94
+ assertBrowserPoolNotConfigured(new.target.name, {
95
+ launchContext: options.launchContext,
96
+ headless: options.headless,
97
+ });
98
98
  }
99
- const playwrightLauncher = new PlaywrightLauncher(launchContext, config);
100
- browserPoolOptions.browserPlugins = [playwrightLauncher.createBrowserPlugin()];
101
99
  super({
102
100
  ...browserCrawlerOptions,
103
101
  launchContext,
104
- browserPoolOptions,
105
- contextPipelineBuilder: () => this.buildContextPipeline().compose({ action: this.enhanceContext.bind(this) }),
106
- }, config);
107
- this.config = config;
102
+ configuration,
103
+ browserPoolBuilder: (remoteBrowser) => remoteBrowser
104
+ ? remotePlaywrightBrowserPool({ ...remoteBrowser, launchContext, headless, configuration })
105
+ : playwrightBrowserPool({ launchContext, headless, configuration }),
106
+ contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
107
+ });
108
108
  }
109
- async _navigationHandler(crawlingContext, gotoOptions) {
109
+ buildContextPipeline() {
110
+ return super.buildContextPipeline().compose({ action: this.enhanceContext.bind(this) });
111
+ }
112
+ async navigationHandler(crawlingContext, gotoOptions) {
110
113
  return gotoExtended(crawlingContext.page, crawlingContext.request, gotoOptions);
111
114
  }
112
115
  async enhanceContext(context) {
@@ -114,6 +117,8 @@ export class PlaywrightCrawler extends BrowserCrawler {
114
117
  const locator = context.page.locator(selector).first();
115
118
  await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
116
119
  };
120
+ const downloads = [];
121
+ context.page.on('download', (download) => downloads.push(download));
117
122
  return {
118
123
  injectFile: async (filePath, options) => playwrightUtils.injectFile(context.page, filePath, options),
119
124
  injectJQuery: async () => {
@@ -133,45 +138,45 @@ export class PlaywrightCrawler extends BrowserCrawler {
133
138
  return playwrightUtils.parseWithCheerio(context.page, this.ignoreShadowRoots, this.ignoreIframes);
134
139
  },
135
140
  infiniteScroll: async (options) => playwrightUtils.infiniteScroll(context.page, options),
136
- saveSnapshot: async (options) => playwrightUtils.saveSnapshot(context.page, { ...options, config: this.config }),
141
+ listDownloads: async () => downloads,
142
+ saveSnapshot: async (options) => playwrightUtils.saveSnapshot(context.page, {
143
+ ...options,
144
+ configuration: serviceLocator.getConfiguration(),
145
+ }),
137
146
  enqueueLinksByClickingElements: async (options) => playwrightUtils.enqueueLinksByClickingElements({
138
147
  ...options,
139
148
  page: context.page,
140
- requestQueue: this.requestQueue,
149
+ requestManager: this.requestManager,
141
150
  }),
142
151
  compileScript: (scriptString, ctx) => playwrightUtils.compileScript(scriptString, ctx),
143
- closeCookieModals: async () => playwrightUtils.closeCookieModals(context.page),
144
152
  handleCloudflareChallenge: async (options) => {
145
- return playwrightUtils.handleCloudflareChallenge(context.page, context.request.url, context.session, options);
153
+ return playwrightUtils.handleCloudflareChallenge(context.page, context.request.url, options);
146
154
  },
147
155
  };
148
156
  }
149
157
  }
150
158
  /**
151
- * Creates new {@link Router} instance that works based on request labels.
152
- * This instance can then serve as a `requestHandler` of your {@link PlaywrightCrawler}.
153
- * Defaults to the {@link PlaywrightCrawlingContext}.
154
- *
155
- * > Serves as a shortcut for using `Router.create<PlaywrightCrawlingContext>()`.
159
+ * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
160
+ * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
156
161
  *
162
+ * **Example usage**
157
163
  * ```ts
158
- * import { PlaywrightCrawler, createPlaywrightRouter } from 'crawlee';
159
- *
160
- * const router = createPlaywrightRouter();
161
- * router.addHandler('label-a', async (ctx) => {
162
- * ctx.log.info('...');
163
- * });
164
- * router.addDefaultHandler(async (ctx) => {
165
- * ctx.log.info('...');
166
- * });
164
+ * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
167
165
  *
168
166
  * const crawler = new PlaywrightCrawler({
169
- * requestHandler: router,
167
+ * postNavigationHooks: [handleCloudflareChallengeHook()],
170
168
  * });
171
- * await crawler.run();
172
169
  * ```
173
170
  */
174
- export function createPlaywrightRouter(routes) {
175
- return Router.create(routes);
171
+ export function handleCloudflareChallengeHook(options) {
172
+ return async (context) => {
173
+ const response = await context.handleCloudflareChallenge(options);
174
+ if (response !== undefined) {
175
+ return { response };
176
+ }
177
+ return undefined;
178
+ };
179
+ }
180
+ export function createPlaywrightRouter(routesOrSchemas) {
181
+ return Router.create(routesOrSchemas);
176
182
  }
177
- //# sourceMappingURL=playwright-crawler.js.map