@crawlee/playwright 4.0.0-beta.13 → 4.0.0-beta.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +17 -13
  2. package/index.d.ts +2 -2
  3. package/index.js +1 -1
  4. package/internals/adaptive-playwright-crawler.d.ts +128 -59
  5. package/internals/adaptive-playwright-crawler.js +317 -230
  6. package/internals/enqueue-links/click-elements.d.ts +37 -55
  7. package/internals/enqueue-links/click-elements.js +63 -55
  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 +193 -124
  11. package/internals/playwright-crawler.js +63 -62
  12. package/internals/playwright-launcher.d.ts +28 -18
  13. package/internals/playwright-launcher.js +19 -18
  14. package/internals/utils/playwright-utils.d.ts +61 -24
  15. package/internals/utils/playwright-utils.js +145 -95
  16. package/internals/utils/rendering-type-prediction.d.ts +28 -13
  17. package/internals/utils/rendering-type-prediction.js +87 -29
  18. package/package.json +18 -14
  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
  33. package/tsconfig.build.tsbuildinfo +0 -1
@@ -3,6 +3,7 @@ import { BrowserLauncher, Configuration } from '@crawlee/browser';
3
3
  import { PlaywrightPlugin } from '@crawlee/browser-pool';
4
4
  // @ts-ignore optional peer dependency or compatibility with es2022
5
5
  import type { Browser, BrowserType, LaunchOptions } from 'playwright';
6
+ import { z } from 'zod';
6
7
  /**
7
8
  * Apify extends the launch options of Playwright.
8
9
  * You can use any of the Playwright compatible
@@ -70,31 +71,41 @@ export interface PlaywrightLaunchContext extends BrowserLaunchContext<LaunchOpti
70
71
  * @ignore
71
72
  */
72
73
  export declare class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin> {
73
- readonly config: Configuration;
74
+ readonly configuration: Configuration;
74
75
  protected static optionsShape: {
75
76
  // @ts-ignore optional peer dependency or compatibility with es2022
76
- launcher: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
77
+ launcher: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
77
78
  // @ts-ignore optional peer dependency or compatibility with es2022
78
- launchContextOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
79
+ launchContextOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
80
+ proxyUrl: z.ZodOptional<z.ZodURL>;
81
+ useChrome: z.ZodOptional<z.ZodBoolean>;
82
+ useIncognitoPages: z.ZodOptional<z.ZodBoolean>;
83
+ browserPerProxy: z.ZodOptional<z.ZodBoolean>;
84
+ ignoreProxyCertificate: z.ZodOptional<z.ZodBoolean>;
85
+ userDataDir: z.ZodOptional<z.ZodString>;
79
86
  // @ts-ignore optional peer dependency or compatibility with es2022
80
- proxyUrl: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
81
- // @ts-ignore optional peer dependency or compatibility with es2022
82
- useChrome: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
83
- // @ts-ignore optional peer dependency or compatibility with es2022
84
- useIncognitoPages: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
85
- // @ts-ignore optional peer dependency or compatibility with es2022
86
- browserPerProxy: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
87
+ launchOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
88
+ userAgent: z.ZodOptional<z.ZodString>;
89
+ };
90
+ protected static optionsSchema: z.ZodObject<{
87
91
  // @ts-ignore optional peer dependency or compatibility with es2022
88
- userDataDir: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
92
+ launcher: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
89
93
  // @ts-ignore optional peer dependency or compatibility with es2022
90
- launchOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
94
+ launchContextOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
95
+ proxyUrl: z.ZodOptional<z.ZodURL>;
96
+ useChrome: z.ZodOptional<z.ZodBoolean>;
97
+ useIncognitoPages: z.ZodOptional<z.ZodBoolean>;
98
+ browserPerProxy: z.ZodOptional<z.ZodBoolean>;
99
+ ignoreProxyCertificate: z.ZodOptional<z.ZodBoolean>;
100
+ userDataDir: z.ZodOptional<z.ZodString>;
91
101
  // @ts-ignore optional peer dependency or compatibility with es2022
92
- userAgent: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
93
- };
102
+ launchOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
103
+ userAgent: z.ZodOptional<z.ZodString>;
104
+ }, z.core.$strict>;
94
105
  /**
95
106
  * All `PlaywrightLauncher` parameters are passed via this launchContext object.
96
107
  */
97
- constructor(launchContext?: PlaywrightLaunchContext, config?: Configuration);
108
+ constructor(launchContext?: PlaywrightLaunchContext, configuration?: Configuration);
98
109
  }
99
110
  /**
100
111
  * Launches headless browsers using Playwright pre-configured to work within the Apify platform.
@@ -125,9 +136,8 @@ export declare class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin
125
136
  * Optional settings passed to `browserType.launch()`. In addition to
126
137
  * [Playwright's options](https://playwright.dev/docs/api/class-browsertype?_highlight=launch#browsertypelaunchoptions)
127
138
  * the object may contain our own {@link PlaywrightLaunchContext} that enable additional features.
128
- * @param [config]
139
+ * @param [configuration]
129
140
  * @returns
130
141
  * Promise that resolves to Playwright's `Browser` instance.
131
142
  */
132
- export declare function launchPlaywright(launchContext?: PlaywrightLaunchContext, config?: Configuration): Promise<Browser>;
133
- //# sourceMappingURL=playwright-launcher.d.ts.map
143
+ export declare function launchPlaywright(launchContext?: PlaywrightLaunchContext, configuration?: Configuration): Promise<Browser>;
@@ -1,33 +1,35 @@
1
- import { BrowserLauncher, Configuration } from '@crawlee/browser';
1
+ import { BrowserLauncher, Configuration, parseArgument, schemas } from '@crawlee/browser';
2
2
  import { PlaywrightPlugin } from '@crawlee/browser-pool';
3
- import ow from 'ow';
3
+ import { z } from 'zod';
4
4
  /**
5
5
  * `PlaywrightLauncher` is based on the `BrowserLauncher`. It launches `playwright` browser instance.
6
6
  * @ignore
7
7
  */
8
8
  export class PlaywrightLauncher extends BrowserLauncher {
9
- config;
9
+ configuration;
10
10
  static optionsShape = {
11
11
  ...BrowserLauncher.optionsShape,
12
- launcher: ow.optional.object,
13
- launchContextOptions: ow.optional.object,
12
+ // Passthrough schemas — the launcher module object must keep its prototype through parsing.
13
+ launcher: schemas.anyObject.optional(),
14
+ launchContextOptions: schemas.anyObject.optional(),
14
15
  };
16
+ static optionsSchema = z.strictObject(PlaywrightLauncher.optionsShape);
15
17
  /**
16
18
  * All `PlaywrightLauncher` parameters are passed via this launchContext object.
17
19
  */
18
- constructor(launchContext = {}, config = Configuration.getGlobalConfig()) {
19
- ow(launchContext, 'PlaywrightLauncherOptions', ow.object.exactShape(PlaywrightLauncher.optionsShape));
20
- const { launcher = BrowserLauncher.requireLauncherOrThrow('playwright', 'apify/actor-node-playwright-*').chromium, } = launchContext;
21
- const { launchOptions = {}, ...rest } = launchContext;
20
+ constructor(launchContext = {}, configuration = Configuration.getGlobalConfiguration()) {
21
+ const parsedContext = parseArgument(launchContext, PlaywrightLauncher.optionsSchema, 'PlaywrightLaunchContext');
22
+ const { launcher = BrowserLauncher.requireLauncherOrThrow('playwright', 'apify/actor-node-playwright-*').chromium, } = parsedContext;
23
+ const { launchOptions = {}, ...rest } = parsedContext;
22
24
  super({
23
25
  ...rest,
24
26
  launchOptions: {
25
27
  ...launchOptions,
26
- executablePath: getDefaultExecutablePath(launchContext, config),
28
+ executablePath: getDefaultExecutablePath(parsedContext, configuration),
27
29
  },
28
30
  launcher,
29
- }, config);
30
- this.config = config;
31
+ }, configuration);
32
+ this.configuration = configuration;
31
33
  this.Plugin = PlaywrightPlugin;
32
34
  }
33
35
  }
@@ -36,8 +38,8 @@ export class PlaywrightLauncher extends BrowserLauncher {
36
38
  * @returns default path to browser.
37
39
  * @ignore
38
40
  */
39
- function getDefaultExecutablePath(launchContext, config) {
40
- const pathFromPlaywrightImage = config.get('defaultBrowserPath');
41
+ function getDefaultExecutablePath(launchContext, configuration) {
42
+ const pathFromPlaywrightImage = configuration.defaultBrowserPath;
41
43
  const { launchOptions = {} } = launchContext;
42
44
  if (launchOptions.executablePath) {
43
45
  return launchOptions.executablePath;
@@ -79,12 +81,11 @@ function getDefaultExecutablePath(launchContext, config) {
79
81
  * Optional settings passed to `browserType.launch()`. In addition to
80
82
  * [Playwright's options](https://playwright.dev/docs/api/class-browsertype?_highlight=launch#browsertypelaunchoptions)
81
83
  * the object may contain our own {@link PlaywrightLaunchContext} that enable additional features.
82
- * @param [config]
84
+ * @param [configuration]
83
85
  * @returns
84
86
  * Promise that resolves to Playwright's `Browser` instance.
85
87
  */
86
- export async function launchPlaywright(launchContext, config = Configuration.getGlobalConfig()) {
87
- const playwrightLauncher = new PlaywrightLauncher(launchContext, config);
88
+ export async function launchPlaywright(launchContext, configuration = Configuration.getGlobalConfiguration()) {
89
+ const playwrightLauncher = new PlaywrightLauncher(launchContext, configuration);
88
90
  return playwrightLauncher.launch();
89
91
  }
90
- //# sourceMappingURL=playwright-launcher.js.map
@@ -17,11 +17,11 @@
17
17
  * ```
18
18
  * @module playwrightUtils
19
19
  */
20
- import { Configuration, type Request, type Session } from '@crawlee/browser';
21
- import type { BatchAddRequestsResult } from '@crawlee/types';
22
- import { type CheerioRoot, type Dictionary } from '@crawlee/utils';
20
+ import { Configuration, type Request } from '@crawlee/browser';
21
+ import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
22
+ import { type CheerioRoot } from '@crawlee/utils/internal';
23
23
  // @ts-ignore optional peer dependency or compatibility with es2022
24
- import type { Page, Response } from 'playwright';
24
+ import type { Download, Page, Response } from 'playwright';
25
25
  import type { EnqueueLinksByClickingElementsOptions } from '../enqueue-links/click-elements.js';
26
26
  import { enqueueLinksByClickingElements } from '../enqueue-links/click-elements.js';
27
27
  import { RenderingTypePredictor } from './rendering-type-prediction.js';
@@ -265,9 +265,9 @@ export interface SaveSnapshotOptions {
265
265
  keyValueStoreName?: string | null;
266
266
  /**
267
267
  * Configuration of the crawler that will be used to save the snapshot.
268
- * @default Configuration.getGlobalConfig()
268
+ * @default Configuration.getGlobalConfiguration()
269
269
  */
270
- config?: Configuration;
270
+ configuration?: Configuration;
271
271
  }
272
272
  /**
273
273
  * Saves a full screenshot and HTML of the current page into a Key-Value store.
@@ -303,6 +303,13 @@ export interface HandleCloudflareChallengeOptions {
303
303
  isChallengeCallback?: (page: Page) => Promise<boolean>;
304
304
  /** Allows overriding the detection of Cloudflare "blocked page". */
305
305
  isBlockedCallback?: (page: Page) => Promise<boolean>;
306
+ /** Allows overriding how the checkbox click position is calculated. */
307
+ clickPositionCallback?: (page: Page) => Promise<{
308
+ x: number;
309
+ y: number;
310
+ } | null>;
311
+ /** Optional delay (in seconds) before the first click attempt on the challenge checkbox. Defaults to 1s. */
312
+ preChallengeSleepSecs?: number;
306
313
  }
307
314
  /**
308
315
  * This helper tries to solve the Cloudflare challenge automatically by clicking on the checkbox.
@@ -311,24 +318,24 @@ export interface HandleCloudflareChallengeOptions {
311
318
  * result in a SessionError which will be automatically retried, so only successful requests will get
312
319
  * into the `requestHandler`.
313
320
  *
321
+ * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
322
+ * it can be propagated back to the crawling context via a hook return value (see
323
+ * {@link handleCloudflareChallengeHook}).
324
+ *
314
325
  * Works best with camoufox.
315
326
  *
316
327
  * **Example usage**
317
328
  * ```ts
318
329
  * postNavigationHooks: [
319
- * async ({ handleCloudflareChallenge }) => {
320
- * await handleCloudflareChallenge();
321
- * },
330
+ * async (context) => ({ response: await context.handleCloudflareChallenge() }),
322
331
  * ],
323
332
  * ```
324
333
  *
325
334
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
326
335
  * @param url current URL for request identification, only used for logging
327
- * @param [session] current session object
328
336
  * @param [options]
329
337
  */
330
- declare function handleCloudflareChallenge(page: Page, url: string, session?: Session, options?: HandleCloudflareChallengeOptions): Promise<void>;
331
- /** @internal */
338
+ declare function handleCloudflareChallenge(page: Page, url: string, options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
332
339
  export interface PlaywrightContextUtils {
333
340
  /**
334
341
  * Injects a JavaScript file into current `page`.
@@ -447,8 +454,7 @@ export interface PlaywrightContextUtils {
447
454
  * in `href` elements, but rather navigations are triggered in click handlers.
448
455
  * If you're looking to find URLs in `href` attributes of the page, see {@link enqueueLinks}.
449
456
  *
450
- * Optionally, the function allows you to filter the target links' URLs using an array of {@link PseudoUrl} objects
451
- * and override settings of the enqueued {@link Request} objects.
457
+ * Optionally, the function allows you to filter the target links' URLs using an array of glob or regexp patterns.
452
458
  *
453
459
  * **IMPORTANT**: To be able to do this, this function uses various mutations on the page,
454
460
  * such as changing the Z-index of elements being clicked and their visibility. Therefore,
@@ -469,9 +475,9 @@ export interface PlaywrightContextUtils {
469
475
  * async requestHandler({ enqueueLinksByClickingElements }) {
470
476
  * await enqueueLinksByClickingElements({
471
477
  * selector: 'a.product-detail',
472
- * globs: [
473
- * 'https://www.example.com/handbags/**'
474
- * 'https://www.example.com/purses/**'
478
+ * include: [
479
+ * 'https://www.example.com/handbags/**',
480
+ * 'https://www.example.com/purses/**',
475
481
  * ],
476
482
  * });
477
483
  * });
@@ -479,7 +485,7 @@ export interface PlaywrightContextUtils {
479
485
  *
480
486
  * @returns Promise that resolves to {@link BatchAddRequestsResult} object.
481
487
  */
482
- enqueueLinksByClickingElements(options: Omit<EnqueueLinksByClickingElementsOptions, 'page' | 'requestQueue'>): Promise<BatchAddRequestsResult>;
488
+ enqueueLinksByClickingElements(options: Omit<EnqueueLinksByClickingElementsOptions, 'page' | 'requestManager'>): Promise<BatchAddRequestsResult>;
483
489
  /**
484
490
  * Compiles a Playwright script into an async function that may be executed at any time
485
491
  * by providing it with the following object:
@@ -509,6 +515,15 @@ export interface PlaywrightContextUtils {
509
515
  compileScript(scriptString: string, ctx?: Dictionary): CompiledScriptFunction;
510
516
  /**
511
517
  * Tries to close cookie consent modals on the page. Based on the I Don't Care About Cookies browser extension.
518
+ *
519
+ * Note that this method requires the idcac-playwright package to be installed.
520
+ * Crawlee does not include it by default due to licensing issues.
521
+ *
522
+ * To use this method, please install the package manually by running:
523
+ *
524
+ * ```bash
525
+ * npm install idcac-playwright
526
+ * ```
512
527
  */
513
528
  closeCookieModals(): Promise<void>;
514
529
  /**
@@ -518,20 +533,43 @@ export interface PlaywrightContextUtils {
518
533
  * result in a SessionError which will be automatically retried, so only successful requests will get
519
534
  * into the `requestHandler`.
520
535
  *
521
- * Works best with camoufox.
536
+ * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned,
537
+ * which can be returned from the hook to update the crawling context's `response`. For the common case,
538
+ * prefer the pre-wrapped {@link handleCloudflareChallengeHook} hook.
522
539
  *
523
540
  * **Example usage**
524
541
  * ```ts
525
542
  * postNavigationHooks: [
526
- * async ({ handleCloudflareChallenge }) => {
527
- * await handleCloudflareChallenge();
528
- * },
543
+ * async (context) => ({ response: await context.handleCloudflareChallenge() }),
529
544
  * ],
530
545
  * ```
531
546
  *
532
547
  * @param [options]
533
548
  */
534
- handleCloudflareChallenge(options?: HandleCloudflareChallengeOptions): Promise<void>;
549
+ handleCloudflareChallenge(options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
550
+ /**
551
+ * Returns the list of {@link https://playwright.dev/docs/api/class-download | Download} objects
552
+ * collected during the current page navigation and request handler.
553
+ *
554
+ * Useful for accessing files that the page downloads automatically.
555
+ * For most use cases, prefer re-enqueueing the URL to {@link FileDownload}.
556
+ * Use this only when direct access to the Playwright `Download` object is required.
557
+ *
558
+ * **Example usage**
559
+ * ```ts
560
+ * requestHandler: async ({ listDownloads }) => {
561
+ * for (const download of await listDownloads()) {
562
+ * try {
563
+ * const stream = await download.createReadStream();
564
+ * // stream to storage...
565
+ * } catch {
566
+ * // download failed or was cancelled
567
+ * }
568
+ * }
569
+ * },
570
+ * ```
571
+ */
572
+ listDownloads(): Promise<Download[]>;
535
573
  }
536
574
  export { enqueueLinksByClickingElements };
537
575
  /** @internal */
@@ -549,4 +587,3 @@ export declare const playwrightUtils: {
549
587
  RenderingTypePredictor: typeof RenderingTypePredictor;
550
588
  handleCloudflareChallenge: typeof handleCloudflareChallenge;
551
589
  };
552
- //# sourceMappingURL=playwright-utils.d.ts.map