Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

chore!: unify argument validation to zod (#3935)

Vlad Frangudd6e3b9929db
diff --git a/docs/public-api/crawlee-basic.api.md b/docs/public-api/crawlee-basic.api.md
index 0040bcbc0..26f65da7a 100644
--- a/docs/public-api/crawlee-basic.api.md
+++ b/docs/public-api/crawlee-basic.api.md
@@ -6,18 +6,14 @@
import type { AddRequestsBatchedOptions } from '@crawlee/core';
import type { AddRequestsBatchedResult } from '@crawlee/core';
-import { AnyPredicate } from 'ow';
-import { ArrayPredicate } from 'ow';
import type { Awaitable } from '@crawlee/types';
-import type { BaseHttpClient } from '@crawlee/types';
-import { BasePredicate } from 'ow';
-import { BooleanPredicate } from 'ow';
+import { BaseHttpClient } from '@crawlee/http-client';
import { Cheerio } from '@crawlee/utils/internal';
import { CheerioAPI } from '@crawlee/utils/internal';
import { CheerioRoot } from '@crawlee/utils/internal';
import { ConcurrencySystem } from '@crawlee/core';
import { ConcurrencySystemOptions } from '@crawlee/core';
-import type { Configuration } from '@crawlee/core';
+import { Configuration } from '@crawlee/core';
import { ContextPipeline } from '@crawlee/core';
import type { CrawleeLogger } from '@crawlee/core';
import { CrawlingContext } from '@crawlee/core';
@@ -25,7 +21,7 @@ import { Dataset } from '@crawlee/core';
import type { DatasetExportOptions } from '@crawlee/core';
import type { Dictionary } from '@crawlee/types';
import { Element as Element_2 } from '@crawlee/utils/internal';
-import type { EventManager } from '@crawlee/core';
+import { EventManager } from '@crawlee/core';
import type { FinalStatistics } from '@crawlee/core';
import type { GetUserDataFromRequest } from '@crawlee/core';
import { IConcurrencySystem } from '@crawlee/core';
@@ -35,9 +31,6 @@ import { IRequestManager } from '@crawlee/core';
import type { ISession } from '@crawlee/types';
import type { ISessionPool } from '@crawlee/types';
import { IStatistics } from '@crawlee/core';
-import { NumberPredicate } from 'ow';
-import { ObjectPredicate } from 'ow';
-import { Predicate } from 'ow';
import type { ProxyInfo } from '@crawlee/types';
import type { ReadonlyDeep } from 'type-fest';
import { Request as Request_2 } from '@crawlee/core';
@@ -51,10 +44,10 @@ import type { StatisticState } from '@crawlee/core';
import type { StorageBackend } from '@crawlee/types';
import type { StorageIdentifier } from '@crawlee/core';
import { StorageWritePolicy } from '@crawlee/core';
-import { StringPredicate } from 'ow';
import type { TaskLoopPredicates } from '@crawlee/core';
import { TimeoutError } from '@apify/timeout';
import type { TypedRequestsLike } from '@crawlee/core';
+import { z } from 'zod';
// @public (undocumented)
export class BasicCrawler<Context extends CrawlingContext = CrawlingContext, ContextExtension = Dictionary<never>, ExtendedContext extends Context = Context & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>> {
@@ -118,44 +111,94 @@ export class BasicCrawler<Context extends CrawlingContext = CrawlingContext, Con
// (undocumented)
protected readonly onSkippedRequest?: SkippedRequestCallback;
// (undocumented)
+ protected static optionsSchema: z.ZodObject<{
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
+ }, z.core.$strict>;
+ // (undocumented)
protected static optionsShape: {
- contextPipelineBuilder: ObjectPredicate<object> & BasePredicate<object | undefined>;
- extendContext: Predicate<Function> & BasePredicate<Function | undefined>;
- requestList: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestQueue: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- requestHandlerTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- errorHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- failedRequestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- maxRequestRetries: NumberPredicate & BasePredicate<number | undefined>;
- sameDomainDelaySecs: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;
- maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;
- taskLoopOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;
- sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- proxyConfiguration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;
- statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;
- additionalHttpErrorStatusCodes: ArrayPredicate<number>;
- ignoreHttpErrorStatusCodes: ArrayPredicate<number>;
- blockedStatusCodes: ArrayPredicate<number>;
- retryOnBlocked: BooleanPredicate & BasePredicate<boolean | undefined>;
- respectRobotsTxtFile: AnyPredicate<boolean | object>;
- transactionalStorage: BasePredicate<boolean | Partial<StorageWritePolicy> | undefined>;
- onSkippedRequest: Predicate<Function> & BasePredicate<Function | undefined>;
- httpClient: ObjectPredicate<object> & BasePredicate<object | undefined>;
- configuration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- storageBackend: ObjectPredicate<object> & BasePredicate<object | undefined>;
- eventManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- logger: ObjectPredicate<object> & BasePredicate<object | undefined>;
- minConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerMinute: NumberPredicate & BasePredicate<number | undefined>;
- keepAlive: BooleanPredicate & BasePredicate<boolean | undefined>;
- statistics: ObjectPredicate<object> & BasePredicate<object | undefined>;
- id: StringPredicate & BasePredicate<string | undefined>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
};
pause(timeoutSecs?: number): Promise<void>;
readonly proxyConfiguration?: IProxyConfiguration;
diff --git a/docs/public-api/crawlee-browser.api.md b/docs/public-api/crawlee-browser.api.md
index 9d202ad41..20d5b581a 100644
--- a/docs/public-api/crawlee-browser.api.md
+++ b/docs/public-api/crawlee-browser.api.md
@@ -4,39 +4,34 @@
```ts
-import { AnyPredicate } from 'ow';
-import { ArrayPredicate } from 'ow';
import type { Awaitable } from '@crawlee/types';
-import { BasePredicate } from 'ow';
+import { BaseHttpClient } from '@crawlee/http-client';
import { BasicCrawler } from '@crawlee/basic';
import { BasicCrawlerOptions } from '@crawlee/basic';
import type { BatchAddRequestsResult } from '@crawlee/types';
-import { BooleanPredicate } from 'ow';
import type { BrowserController } from '@crawlee/browser-pool';
import type { BrowserPlugin } from '@crawlee/browser-pool';
import type { BrowserPluginOptions } from '@crawlee/browser-pool';
import type { BrowserPoolHooks } from '@crawlee/browser-pool';
import type { BrowserPoolOptions } from '@crawlee/browser-pool';
import type { CommonPage } from '@crawlee/browser-pool';
+import { Configuration } from '@crawlee/basic';
import { ContextPipeline } from '@crawlee/basic';
import type { CrawlerRemoteBrowserOptions } from '@crawlee/browser-pool';
import type { CrawlingContext } from '@crawlee/basic';
import type { Dictionary } from '@crawlee/types';
import type { EnqueueLinksOptions } from '@crawlee/basic';
import type { ErrorHandler } from '@crawlee/basic';
+import { EventManager } from '@crawlee/basic';
import type { GetUserDataFromRequest } from '@crawlee/basic';
import type { IBrowserPool } from '@crawlee/types';
import type { InferBrowserPluginArray } from '@crawlee/browser-pool';
import type { LaunchContext } from '@crawlee/browser-pool';
import type { LoadedRequest } from '@crawlee/basic';
-import { NumberPredicate } from 'ow';
-import { ObjectPredicate } from 'ow';
-import { Predicate } from 'ow';
import { Request as Request_2 } from '@crawlee/basic';
import type { RequestHandler } from '@crawlee/basic';
import type { RouterHandler } from '@crawlee/basic';
-import { StorageWritePolicy } from '@crawlee/basic';
-import { StringPredicate } from 'ow';
+import { z } from 'zod';
// Not exported by the entry point; reachable only as a referenced type.
// @public (undocumented)
@@ -65,53 +60,116 @@ export abstract class BrowserCrawler<Page extends CommonPage = CommonPage, Respo
// (undocumented)
protected abstract navigationHandler(crawlingContext: BrowserCrawlingContext<Page, Response>, gotoOptions: GoToOptions): Promise<Context['response'] | null | undefined>;
// (undocumented)
+ protected static optionsSchema: z.ZodObject<{
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
+ headless: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ browserPoolOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
+ }, z.core.$strict>;
+ // (undocumented)
protected static optionsShape: {
- navigationTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- preNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- postNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- launchContext: ObjectPredicate<object> & BasePredicate<object | undefined>;
- headless: AnyPredicate<string | boolean>;
- browserPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- remoteBrowser: ObjectPredicate<object> & BasePredicate<object | undefined>;
- browserPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- saveResponseCookies: BooleanPredicate & BasePredicate<boolean | undefined>;
- proxyConfiguration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- contextPipelineBuilder: ObjectPredicate<object> & BasePredicate<object | undefined>;
- extendContext: Predicate<Function> & BasePredicate<Function | undefined>;
- requestList: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestQueue: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- requestHandlerTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- errorHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- failedRequestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- maxRequestRetries: NumberPredicate & BasePredicate<number | undefined>;
- sameDomainDelaySecs: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;
- maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;
- taskLoopOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;
- sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;
- statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;
- additionalHttpErrorStatusCodes: ArrayPredicate<number>;
- ignoreHttpErrorStatusCodes: ArrayPredicate<number>;
- blockedStatusCodes: ArrayPredicate<number>;
- retryOnBlocked: BooleanPredicate & BasePredicate<boolean | undefined>;
- respectRobotsTxtFile: AnyPredicate<boolean | object>;
- transactionalStorage: BasePredicate<boolean | Partial<StorageWritePolicy> | undefined>;
- onSkippedRequest: Predicate<Function> & BasePredicate<Function | undefined>;
- httpClient: ObjectPredicate<object> & BasePredicate<object | undefined>;
- configuration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- storageBackend: ObjectPredicate<object> & BasePredicate<object | undefined>;
- eventManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- logger: ObjectPredicate<object> & BasePredicate<object | undefined>;
- minConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerMinute: NumberPredicate & BasePredicate<number | undefined>;
- keepAlive: BooleanPredicate & BasePredicate<boolean | undefined>;
- statistics: ObjectPredicate<object> & BasePredicate<object | undefined>;
- id: StringPredicate & BasePredicate<string | undefined>;
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
+ headless: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ browserPoolOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
};
protected runRequestHandler(crawlingContext: ExtendedContext): Promise<void>;
}
diff --git a/docs/public-api/crawlee-core.api.md b/docs/public-api/crawlee-core.api.md
index d32341b16..681c17f93 100644
--- a/docs/public-api/crawlee-core.api.md
+++ b/docs/public-api/crawlee-core.api.md
@@ -5,9 +5,10 @@
```ts
import type { AllowedHttpMethods } from '@crawlee/types';
+import { ArgumentValidationError } from '@crawlee/utils';
import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';
import type { Awaitable } from '@crawlee/types';
-import type { BaseHttpClient } from '@crawlee/types';
+import { BaseHttpClient } from '@crawlee/http-client';
import type { BatchAddRequestsResult } from '@crawlee/types';
import type { BetterIntervalID } from '@apify/utilities';
import type { Constructor } from '@crawlee/types';
@@ -29,6 +30,7 @@ import { LoggerJson } from '@apify/log';
import type { LoggerOptions } from '@apify/log';
import { LoggerText } from '@apify/log';
import { LogLevel } from '@apify/log';
+import { parseArgument } from '@crawlee/utils';
import { ParseSitemapOptions } from '@crawlee/utils';
import type { ProcessedRequest } from '@crawlee/types';
import type { ProxyInfo } from '@crawlee/types';
@@ -37,6 +39,7 @@ import type { ReadonlyDeep } from 'type-fest';
import type { RequestQueueBackend } from '@crawlee/types';
import type { RequestQueueInfo } from '@crawlee/types';
import { RobotsTxtFile } from '@crawlee/utils';
+import { schemas } from '@crawlee/utils/internal';
import type { SendRequestOptions } from '@crawlee/types';
import type { SessionFingerprint } from '@crawlee/types';
import { SessionState } from '@crawlee/types';
@@ -47,6 +50,7 @@ import { StorageBackend } from '@crawlee/types';
import { StorageIdentifier } from '@crawlee/types';
import { tryAbsoluteURL } from '@crawlee/utils/internal';
import { z } from 'zod';
+import { ZodType } from 'zod';
// @public (undocumented)
export interface AddRequestsBatchedOptions extends RequestQueueOperationOptions {
@@ -73,6 +77,8 @@ export class ApifyLogAdapter extends BaseCrawleeLogger {
logWithLevel(level: number, message: string, data?: Record<string, unknown>): void;
}
+export { ArgumentValidationError }
+
// Not exported by the entry point; reachable only as a referenced type.
// @public (undocumented)
class BaseClient {
@@ -175,10 +181,10 @@ export interface ClientLoadSignalOptions {
}
// @public
-export const coerceBoolean: z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>;
+export const coerceBoolean: z.ZodPreprocess<z.ZodBoolean>;
// @public (undocumented)
-export const coerceNumber: z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>;
+export const coerceNumber: z.ZodPreprocess<z.ZodNumber>;
// @public
export interface ConcurrencyConsumer {
@@ -300,25 +306,25 @@ export interface CpuLoadSignalOptions {
// @public (undocumented)
export const crawleeConfigFields: {
defaultDatasetId: ConfigField<z.ZodDefault<z.ZodString>>;
- purgeOnStart: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
+ purgeOnStart: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean>>>;
defaultKeyValueStoreId: ConfigField<z.ZodDefault<z.ZodString>>;
defaultRequestQueueId: ConfigField<z.ZodDefault<z.ZodString>>;
- maxUsedCpuRatio: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>>>;
- availableMemoryRatio: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>>>;
- memoryMbytes: ConfigField<z.ZodOptional<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>>>;
- persistStateIntervalMillis: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>>>;
- internalTimeoutMillis: ConfigField<z.ZodOptional<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>>>;
- systemInfoIntervalMillis: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodNumber>>>;
+ maxUsedCpuRatio: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber>>>;
+ availableMemoryRatio: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber>>>;
+ memoryMbytes: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>>;
+ persistStateIntervalMillis: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber>>>;
+ internalTimeoutMillis: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodNumber>>>;
+ systemInfoIntervalMillis: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodNumber>>>;
inputKey: ConfigField<z.ZodDefault<z.ZodString>>;
- headless: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
- xvfb: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
+ headless: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean>>>;
+ xvfb: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean>>>;
chromeExecutablePath: ConfigField<z.ZodOptional<z.ZodString>>;
defaultBrowserPath: ConfigField<z.ZodOptional<z.ZodString>>;
- disableBrowserSandbox: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
- logLevel: ConfigField<z.ZodOptional<z.ZodPipe<z.ZodTransform<{} | null | undefined, unknown>, z.ZodEnum<typeof LogLevel>>>>;
- persistStorage: ConfigField<z.ZodDefault<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
+ disableBrowserSandbox: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean>>>;
+ logLevel: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodEnum<typeof LogLevel>>>>;
+ persistStorage: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean>>>;
storageDir: ConfigField<z.ZodDefault<z.ZodString>>;
- containerized: ConfigField<z.ZodOptional<z.ZodPipe<z.ZodTransform<unknown, unknown>, z.ZodBoolean>>>;
+ containerized: ConfigField<z.ZodOptional<z.ZodPreprocess<z.ZodBoolean>>>;
};
export { CrawleeLogger }
@@ -1149,6 +1155,8 @@ interface NewUrlOptions {
export class NonRetryableError extends Error {
}
+export { parseArgument }
+
// @public
export function parseRetryAfterHeader(value?: string | null): number | null;
@@ -1666,6 +1674,8 @@ export interface SchemaIssue {
})[];
}
+export { schemas }
+
// Not exported by the entry point; reachable only as a referenced type.
// @public
type SchemaUserData<Schema extends StandardSchemaV1> = StandardSchemaV1.InferOutput<Schema> extends Dictionary ? StandardSchemaV1.InferOutput<Schema> : Dictionary;
diff --git a/docs/public-api/crawlee-http.api.md b/docs/public-api/crawlee-http.api.md
index 4eff6be95..336e6767a 100644
--- a/docs/public-api/crawlee-http.api.md
+++ b/docs/public-api/crawlee-http.api.md
@@ -4,27 +4,23 @@
```ts
-import { AnyPredicate } from 'ow';
-import { ArrayPredicate } from 'ow';
import type { Awaitable } from '@crawlee/types';
-import { BasePredicate } from 'ow';
+import { BaseHttpClient } from '@crawlee/http-client';
import { BasicCrawler } from '@crawlee/basic';
import { BasicCrawlerOptions } from '@crawlee/basic';
-import { BooleanPredicate } from 'ow';
import { CheerioRoot } from '@crawlee/utils/internal';
import { ConcurrencySystem } from '@crawlee/basic';
import type { ConcurrencySystemOptions } from '@crawlee/basic';
+import { Configuration } from '@crawlee/basic';
import { ContextPipeline } from '@crawlee/basic';
import type { CrawlingContext } from '@crawlee/basic';
import type { CrawlingContext as CrawlingContext_2 } from '@crawlee/core';
import type { Dictionary } from '@crawlee/types';
import { ErrorHandler } from '@crawlee/basic';
+import { EventManager } from '@crawlee/basic';
import { GetUserDataFromRequest } from '@crawlee/basic';
import type { JsonValue } from 'type-fest';
import { LoadedRequest } from '@crawlee/core';
-import { NumberPredicate } from 'ow';
-import { ObjectPredicate } from 'ow';
-import { Predicate } from 'ow';
import { Request as Request_2 } from '@crawlee/basic';
import type { Request as Request_3 } from '@crawlee/core';
import { RequestHandler } from '@crawlee/basic';
@@ -34,9 +30,8 @@ import { RouterHandler } from '@crawlee/basic';
import { RouterRoutes } from '@crawlee/basic';
import type { RouteSchemas } from '@crawlee/basic';
import type { RoutesFromSchemas } from '@crawlee/basic';
-import { StorageWritePolicy } from '@crawlee/basic';
-import { StringPredicate } from 'ow';
import { Transform } from 'node:stream';
+import { z } from 'zod';
// @public
export function ByteCounterStream(input: {
@@ -115,52 +110,110 @@ export class HttpCrawler<Context extends InternalHttpCrawlingContext<any, any> =
// (undocumented)
protected isRequestBlocked(crawlingContext: InternalHttpCrawlingContext): Promise<string | false>;
// (undocumented)
+ protected static optionsSchema: z.ZodObject<{
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ ignoreTlsErrors: z.ZodDefault<z.ZodBoolean>;
+ additionalMimeTypes: z.ZodDefault<z.ZodArray<z.ZodString>>;
+ suggestResponseEncoding: z.ZodOptional<z.ZodString>;
+ forceResponseEncoding: z.ZodOptional<z.ZodString>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
+ }, z.core.$strict>;
+ // (undocumented)
protected static optionsShape: {
- navigationTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- ignoreTlsErrors: BooleanPredicate & BasePredicate<boolean | undefined>;
- additionalMimeTypes: ArrayPredicate<string>;
- suggestResponseEncoding: StringPredicate & BasePredicate<string | undefined>;
- forceResponseEncoding: StringPredicate & BasePredicate<string | undefined>;
- saveResponseCookies: BooleanPredicate & BasePredicate<boolean | undefined>;
- preNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- postNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- contextPipelineBuilder: ObjectPredicate<object> & BasePredicate<object | undefined>;
- extendContext: Predicate<Function> & BasePredicate<Function | undefined>;
- requestList: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestQueue: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- requestHandlerTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- errorHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- failedRequestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- maxRequestRetries: NumberPredicate & BasePredicate<number | undefined>;
- sameDomainDelaySecs: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;
- maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;
- taskLoopOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;
- sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- proxyConfiguration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;
- statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;
- additionalHttpErrorStatusCodes: ArrayPredicate<number>;
- ignoreHttpErrorStatusCodes: ArrayPredicate<number>;
- blockedStatusCodes: ArrayPredicate<number>;
- retryOnBlocked: BooleanPredicate & BasePredicate<boolean | undefined>;
- respectRobotsTxtFile: AnyPredicate<boolean | object>;
- transactionalStorage: BasePredicate<boolean | Partial<StorageWritePolicy> | undefined>;
- onSkippedRequest: Predicate<Function> & BasePredicate<Function | undefined>;
- httpClient: ObjectPredicate<object> & BasePredicate<object | undefined>;
- configuration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- storageBackend: ObjectPredicate<object> & BasePredicate<object | undefined>;
- eventManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- logger: ObjectPredicate<object> & BasePredicate<object | undefined>;
- minConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerMinute: NumberPredicate & BasePredicate<number | undefined>;
- keepAlive: BooleanPredicate & BasePredicate<boolean | undefined>;
- statistics: ObjectPredicate<object> & BasePredicate<object | undefined>;
- id: StringPredicate & BasePredicate<string | undefined>;
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ ignoreTlsErrors: z.ZodDefault<z.ZodBoolean>;
+ additionalMimeTypes: z.ZodDefault<z.ZodArray<z.ZodString>>;
+ suggestResponseEncoding: z.ZodOptional<z.ZodString>;
+ forceResponseEncoding: z.ZodOptional<z.ZodString>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
};
}
diff --git a/docs/public-api/crawlee-jsdom.api.md b/docs/public-api/crawlee-jsdom.api.md
index b5a122e69..50d2ab91a 100644
--- a/docs/public-api/crawlee-jsdom.api.md
+++ b/docs/public-api/crawlee-jsdom.api.md
@@ -4,35 +4,30 @@
```ts
-import { AnyPredicate } from 'ow';
-import { ArrayPredicate } from 'ow';
-import { BasePredicate } from 'ow';
+import { BaseHttpClient } from '@crawlee/http-client';
import type { BatchAddRequestsResult } from '@crawlee/types';
-import { BooleanPredicate } from 'ow';
import { CheerioAPI } from 'cheerio';
import { CheerioRoot } from '@crawlee/utils/internal';
+import { Configuration } from '@crawlee/http';
import { ContextPipeline } from '@crawlee/http';
import type { CrawlingContext } from '@crawlee/http';
import type { Dictionary } from '@crawlee/types';
import type { DOMWindow } from 'jsdom';
import type { EnqueueLinksOptions } from '@crawlee/http';
import type { ErrorHandler } from '@crawlee/http';
+import { EventManager } from '@crawlee/http';
import type { GetUserDataFromRequest } from '@crawlee/http';
import { HttpCrawler } from '@crawlee/http';
import type { HttpCrawlerOptions } from '@crawlee/http';
import type { InternalHttpCrawlingContext } from '@crawlee/http';
import type { InternalHttpHook } from '@crawlee/http';
-import { NumberPredicate } from 'ow';
-import { ObjectPredicate } from 'ow';
-import { Predicate } from 'ow';
import type { RequestHandler } from '@crawlee/http';
import type { RouterHandler } from '@crawlee/http';
import type { RouterRoutes } from '@crawlee/http';
import type { RouteSchemas } from '@crawlee/http';
import type { RoutesFromSchemas } from '@crawlee/http';
-import { StorageWritePolicy } from '@crawlee/http';
-import { StringPredicate } from 'ow';
import { VirtualConsole } from 'jsdom';
+import { z } from 'zod';
// @public
export function createJSDOMRouter<Context extends JSDOMCrawlingContext = JSDOMCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
@@ -58,54 +53,114 @@ export class JSDOMCrawler<ContextExtension = Dictionary<never>, ExtendedContext
}>;
getVirtualConsole(): VirtualConsole;
// (undocumented)
+ protected static optionsSchema: z.ZodObject<{
+ runScripts: z.ZodOptional<z.ZodBoolean>;
+ hideInternalConsole: z.ZodOptional<z.ZodBoolean>;
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ ignoreTlsErrors: z.ZodDefault<z.ZodBoolean>;
+ additionalMimeTypes: z.ZodDefault<z.ZodArray<z.ZodString>>;
+ suggestResponseEncoding: z.ZodOptional<z.ZodString>;
+ forceResponseEncoding: z.ZodOptional<z.ZodString>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
+ }, z.core.$strict>;
+ // (undocumented)
protected static optionsShape: {
- runScripts: BooleanPredicate & BasePredicate<boolean | undefined>;
- hideInternalConsole: BooleanPredicate & BasePredicate<boolean | undefined>;
- navigationTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- ignoreTlsErrors: BooleanPredicate & BasePredicate<boolean | undefined>;
- additionalMimeTypes: ArrayPredicate<string>;
- suggestResponseEncoding: StringPredicate & BasePredicate<string | undefined>;
- forceResponseEncoding: StringPredicate & BasePredicate<string | undefined>;
- saveResponseCookies: BooleanPredicate & BasePredicate<boolean | undefined>;
- preNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- postNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- contextPipelineBuilder: ObjectPredicate<object> & BasePredicate<object | undefined>;
- extendContext: Predicate<Function> & BasePredicate<Function | undefined>;
- requestList: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestQueue: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- requestHandlerTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- errorHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- failedRequestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- maxRequestRetries: NumberPredicate & BasePredicate<number | undefined>;
- sameDomainDelaySecs: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;
- maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;
- taskLoopOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;
- sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- proxyConfiguration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;
- statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;
- additionalHttpErrorStatusCodes: ArrayPredicate<number>;
- ignoreHttpErrorStatusCodes: ArrayPredicate<number>;
- blockedStatusCodes: ArrayPredicate<number>;
- retryOnBlocked: BooleanPredicate & BasePredicate<boolean | undefined>;
- respectRobotsTxtFile: AnyPredicate<boolean | object>;
- transactionalStorage: BasePredicate<boolean | Partial<StorageWritePolicy> | undefined>;
- onSkippedRequest: Predicate<Function> & BasePredicate<Function | undefined>;
- httpClient: ObjectPredicate<object> & BasePredicate<object | undefined>;
- configuration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- storageBackend: ObjectPredicate<object> & BasePredicate<object | undefined>;
- eventManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- logger: ObjectPredicate<object> & BasePredicate<object | undefined>;
- minConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerMinute: NumberPredicate & BasePredicate<number | undefined>;
- keepAlive: BooleanPredicate & BasePredicate<boolean | undefined>;
- statistics: ObjectPredicate<object> & BasePredicate<object | undefined>;
- id: StringPredicate & BasePredicate<string | undefined>;
+ runScripts: z.ZodOptional<z.ZodBoolean>;
+ hideInternalConsole: z.ZodOptional<z.ZodBoolean>;
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ ignoreTlsErrors: z.ZodDefault<z.ZodBoolean>;
+ additionalMimeTypes: z.ZodDefault<z.ZodArray<z.ZodString>>;
+ suggestResponseEncoding: z.ZodOptional<z.ZodString>;
+ forceResponseEncoding: z.ZodOptional<z.ZodString>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
};
}
diff --git a/docs/public-api/crawlee-playwright.api.md b/docs/public-api/crawlee-playwright.api.md
index c69fff43c..d309831d8 100644
--- a/docs/public-api/crawlee-playwright.api.md
+++ b/docs/public-api/crawlee-playwright.api.md
@@ -5,14 +5,11 @@
```ts
import type { AnyNode } from 'domhandler';
-import { AnyPredicate } from 'ow';
-import { ArrayPredicate } from 'ow';
import type { Awaitable } from '@crawlee/types';
-import { BasePredicate } from 'ow';
+import { BaseHttpClient } from '@crawlee/http-client';
import { BasicCrawler } from '@crawlee/basic';
import type { BasicCrawlerOptions } from '@crawlee/basic';
import { BatchAddRequestsResult } from '@crawlee/types';
-import { BooleanPredicate } from 'ow';
import type { Browser } from 'playwright';
import { BrowserCrawler } from '@crawlee/browser';
import type { BrowserCrawlerOptions } from '@crawlee/browser';
@@ -28,19 +25,17 @@ import { ContextPipeline } from '@crawlee/browser';
import type { ContextPipeline as ContextPipeline_2 } from '@crawlee/core';
import { CrawlingContext } from '@crawlee/browser';
import type { CrawlingContext as CrawlingContext_2 } from '@crawlee/core';
-import type { Dictionary } from '@crawlee/types';
+import { Dictionary } from '@crawlee/types';
import type { Download } from 'playwright';
import type { EnqueueLinksOptions } from '@crawlee/core';
+import { EventManager } from '@crawlee/browser';
import type { GetUserDataFromRequest } from '@crawlee/browser';
import type { GetUserDataFromRequest as GetUserDataFromRequest_2 } from '@crawlee/core';
import { IRequestManager } from '@crawlee/browser';
import type { LaunchOptions } from 'playwright';
import type { LoadedRequest } from '@crawlee/browser';
-import { NumberPredicate } from 'ow';
-import { ObjectPredicate } from 'ow';
import type { Page } from 'playwright';
import { PlaywrightPlugin } from '@crawlee/browser-pool';
-import { Predicate } from 'ow';
import type { RecoverableStatePersistenceOptions } from '@crawlee/core';
import type { Request as Request_2 } from '@crawlee/core';
import { Request as Request_3 } from '@crawlee/browser';
@@ -57,9 +52,8 @@ import type { StatisticPersistedState } from '@crawlee/core';
import { Statistics } from '@crawlee/core';
import type { StatisticState } from '@crawlee/core';
import type { StorageTransactionView } from '@crawlee/core';
-import { StorageWritePolicy } from '@crawlee/browser';
-import { StringPredicate } from 'ow';
import type { UrlPatternInput } from '@crawlee/browser';
+import { z } from 'zod';
// Not exported by the entry point; reachable only as a referenced type.
// @public (undocumented)
@@ -353,56 +347,118 @@ export class PlaywrightCrawler<ContextExtension = Dictionary<never>, ExtendedCon
// (undocumented)
protected navigationHandler(crawlingContext: PlaywrightCrawlingContext, gotoOptions: PlaywrightDirectNavigationOptions): Promise<Response_2 | null>;
// (undocumented)
+ protected static optionsSchema: z.ZodObject<{
+ browserPoolOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ launcher: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
+ headless: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
+ }, z.core.$strict>;
+ // (undocumented)
protected static optionsShape: {
- browserPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- launcher: ObjectPredicate<object> & BasePredicate<object | undefined>;
- ignoreIframes: BooleanPredicate & BasePredicate<boolean | undefined>;
- ignoreShadowRoots: BooleanPredicate & BasePredicate<boolean | undefined>;
- navigationTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- preNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- postNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- launchContext: ObjectPredicate<object> & BasePredicate<object | undefined>;
- headless: AnyPredicate<string | boolean>;
- browserPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- remoteBrowser: ObjectPredicate<object> & BasePredicate<object | undefined>;
- saveResponseCookies: BooleanPredicate & BasePredicate<boolean | undefined>;
- proxyConfiguration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- contextPipelineBuilder: ObjectPredicate<object> & BasePredicate<object | undefined>;
- extendContext: Predicate<Function> & BasePredicate<Function | undefined>;
- requestList: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestQueue: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- requestHandlerTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- errorHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- failedRequestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- maxRequestRetries: NumberPredicate & BasePredicate<number | undefined>;
- sameDomainDelaySecs: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;
- maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;
- taskLoopOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;
- sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;
- statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;
- additionalHttpErrorStatusCodes: ArrayPredicate<number>;
- ignoreHttpErrorStatusCodes: ArrayPredicate<number>;
- blockedStatusCodes: ArrayPredicate<number>;
- retryOnBlocked: BooleanPredicate & BasePredicate<boolean | undefined>;
- respectRobotsTxtFile: AnyPredicate<boolean | object>;
- transactionalStorage: BasePredicate<boolean | Partial<StorageWritePolicy> | undefined>;
- onSkippedRequest: Predicate<Function> & BasePredicate<Function | undefined>;
- httpClient: ObjectPredicate<object> & BasePredicate<object | undefined>;
- configuration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- storageBackend: ObjectPredicate<object> & BasePredicate<object | undefined>;
- eventManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- logger: ObjectPredicate<object> & BasePredicate<object | undefined>;
- minConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerMinute: NumberPredicate & BasePredicate<number | undefined>;
- keepAlive: BooleanPredicate & BasePredicate<boolean | undefined>;
- statistics: ObjectPredicate<object> & BasePredicate<object | undefined>;
- id: StringPredicate & BasePredicate<string | undefined>;
+ browserPoolOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ launcher: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
+ headless: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
};
}
diff --git a/docs/public-api/crawlee-puppeteer.api.md b/docs/public-api/crawlee-puppeteer.api.md
index 0d848e243..e13eee255 100644
--- a/docs/public-api/crawlee-puppeteer.api.md
+++ b/docs/public-api/crawlee-puppeteer.api.md
@@ -4,11 +4,8 @@
```ts
-import { AnyPredicate } from 'ow';
-import { ArrayPredicate } from 'ow';
-import { BasePredicate } from 'ow';
+import { BaseHttpClient } from '@crawlee/http-client';
import { BatchAddRequestsResult } from '@crawlee/types';
-import { BooleanPredicate } from 'ow';
import type { Browser } from 'puppeteer';
import { BrowserCrawler } from '@crawlee/browser';
import type { BrowserCrawlerOptions } from '@crawlee/browser';
@@ -21,16 +18,14 @@ import type { ClickOptions } from 'puppeteer';
import { Configuration } from '@crawlee/browser';
import { ContextPipeline } from '@crawlee/browser';
import { CrawlingContext } from '@crawlee/browser';
-import type { Dictionary } from '@crawlee/types';
+import { Dictionary } from '@crawlee/types';
+import { EventManager } from '@crawlee/browser';
import type { GetUserDataFromRequest } from '@crawlee/browser';
import type { HTTPRequest } from 'puppeteer';
import type { HTTPResponse } from 'puppeteer';
import { IRequestManager } from '@crawlee/browser';
import type { LaunchOptions } from 'puppeteer';
-import { NumberPredicate } from 'ow';
-import { ObjectPredicate } from 'ow';
import type { Page } from 'puppeteer';
-import { Predicate } from 'ow';
import { PuppeteerPlugin } from '@crawlee/browser-pool';
import { Request as Request_2 } from '@crawlee/browser';
import type { RequestTransform } from '@crawlee/browser';
@@ -40,10 +35,9 @@ import type { RouterRoutes } from '@crawlee/browser';
import type { RouteSchemas } from '@crawlee/browser';
import type { RoutesFromSchemas } from '@crawlee/browser';
import type { SkippedRequestCallback } from '@crawlee/browser';
-import { StorageWritePolicy } from '@crawlee/browser';
-import { StringPredicate } from 'ow';
import type { Target } from 'puppeteer';
import type { UrlPatternInput } from '@crawlee/browser';
+import { z } from 'zod';
// @public
function addInterceptRequestHandler(page: Page, handler: InterceptHandler): Promise<void>;
@@ -200,53 +194,116 @@ export class PuppeteerCrawler<ContextExtension = Dictionary<never>, ExtendedCont
// (undocumented)
protected navigationHandler(crawlingContext: PuppeteerCrawlingContext, gotoOptions: PuppeteerDirectNavigationOptions): Promise<HTTPResponse | null>;
// (undocumented)
+ protected static optionsSchema: z.ZodObject<{
+ browserPoolOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
+ headless: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
+ }, z.core.$strict>;
+ // (undocumented)
protected static optionsShape: {
- browserPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- navigationTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- preNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- postNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- launchContext: ObjectPredicate<object> & BasePredicate<object | undefined>;
- headless: AnyPredicate<string | boolean>;
- browserPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- remoteBrowser: ObjectPredicate<object> & BasePredicate<object | undefined>;
- saveResponseCookies: BooleanPredicate & BasePredicate<boolean | undefined>;
- proxyConfiguration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- contextPipelineBuilder: ObjectPredicate<object> & BasePredicate<object | undefined>;
- extendContext: Predicate<Function> & BasePredicate<Function | undefined>;
- requestList: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestQueue: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- requestHandlerTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- errorHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- failedRequestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- maxRequestRetries: NumberPredicate & BasePredicate<number | undefined>;
- sameDomainDelaySecs: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;
- maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;
- taskLoopOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;
- sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;
- statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;
- additionalHttpErrorStatusCodes: ArrayPredicate<number>;
- ignoreHttpErrorStatusCodes: ArrayPredicate<number>;
- blockedStatusCodes: ArrayPredicate<number>;
- retryOnBlocked: BooleanPredicate & BasePredicate<boolean | undefined>;
- respectRobotsTxtFile: AnyPredicate<boolean | object>;
- transactionalStorage: BasePredicate<boolean | Partial<StorageWritePolicy> | undefined>;
- onSkippedRequest: Predicate<Function> & BasePredicate<Function | undefined>;
- httpClient: ObjectPredicate<object> & BasePredicate<object | undefined>;
- configuration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- storageBackend: ObjectPredicate<object> & BasePredicate<object | undefined>;
- eventManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- logger: ObjectPredicate<object> & BasePredicate<object | undefined>;
- minConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerMinute: NumberPredicate & BasePredicate<number | undefined>;
- keepAlive: BooleanPredicate & BasePredicate<boolean | undefined>;
- statistics: ObjectPredicate<object> & BasePredicate<object | undefined>;
- id: StringPredicate & BasePredicate<string | undefined>;
+ browserPoolOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
+ headless: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
};
}
diff --git a/docs/public-api/crawlee-stagehand.api.md b/docs/public-api/crawlee-stagehand.api.md
index bd340377c..0c7cccade 100644
--- a/docs/public-api/crawlee-stagehand.api.md
+++ b/docs/public-api/crawlee-stagehand.api.md
@@ -9,10 +9,7 @@ import { ActOptions } from '@browserbasehq/stagehand';
import { ActResult } from '@browserbasehq/stagehand';
import { AgentConfig } from '@browserbasehq/stagehand';
import { AgentResult } from '@browserbasehq/stagehand';
-import { AnyPredicate } from 'ow';
-import { ArrayPredicate } from 'ow';
-import { BasePredicate } from 'ow';
-import { BooleanPredicate } from 'ow';
+import { BaseHttpClient } from '@crawlee/http-client';
import type { Browser } from 'playwright';
import type { BrowserController } from '@crawlee/browser-pool';
import { BrowserCrawler } from '@crawlee/browser';
@@ -23,9 +20,11 @@ import type { BrowserLaunchContext } from '@crawlee/browser';
import { BrowserPlugin } from '@crawlee/browser-pool';
import type { BrowserPluginOptions } from '@crawlee/browser-pool';
import type { BrowserType } from 'playwright';
+import { Configuration } from '@crawlee/browser';
import type { ContextPipeline } from '@crawlee/browser';
import type { CrawlingContext } from '@crawlee/browser';
import type { Dictionary } from '@crawlee/types';
+import { EventManager } from '@crawlee/browser';
import { ExtractOptions } from '@browserbasehq/stagehand';
import type { GetUserDataFromRequest } from '@crawlee/browser';
import type { LaunchContext } from '@crawlee/browser-pool';
@@ -34,11 +33,8 @@ import type { LLMClient } from '@browserbasehq/stagehand';
import type { LoadedContext } from '@crawlee/browser';
import { ModelConfiguration } from '@browserbasehq/stagehand';
import type { NonStreamingAgentInstance } from '@browserbasehq/stagehand';
-import { NumberPredicate } from 'ow';
-import { ObjectPredicate } from 'ow';
import { ObserveOptions } from '@browserbasehq/stagehand';
import type { Page } from 'playwright';
-import { Predicate } from 'ow';
import type { RequestHandler } from '@crawlee/browser';
import type { Response as Response_2 } from 'playwright';
import type { RouterHandler } from '@crawlee/browser';
@@ -46,10 +42,8 @@ import type { RouterRoutes } from '@crawlee/browser';
import type { RouteSchemas } from '@crawlee/browser';
import type { RoutesFromSchemas } from '@crawlee/browser';
import { Stagehand } from '@browserbasehq/stagehand';
-import { StorageWritePolicy } from '@crawlee/browser';
import type { StreamingAgentInstance } from '@browserbasehq/stagehand';
-import { StringPredicate } from 'ow';
-import type { z } from 'zod';
+import { z } from 'zod';
export { Action }
@@ -87,54 +81,118 @@ export class StagehandCrawler<ContextExtension = Dictionary<never>, ExtendedCont
protected buildContextPipeline(): ContextPipeline<CrawlingContext, StagehandCrawlingContext>;
protected navigationHandler(crawlingContext: StagehandCrawlingContext, gotoOptions: StagehandGotoOptions): Promise<Response_2 | null>;
// (undocumented)
+ protected static optionsSchema: z.ZodObject<{
+ stagehandOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ browserPoolOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
+ headless: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
+ }, z.core.$strict>;
+ // (undocumented)
protected static optionsShape: {
- stagehandOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- browserPoolOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- navigationTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- preNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- postNavigationHooks: ArrayPredicate<unknown> & BasePredicate<unknown[] | undefined>;
- launchContext: ObjectPredicate<object> & BasePredicate<object | undefined>;
- headless: AnyPredicate<string | boolean>;
- browserPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- remoteBrowser: ObjectPredicate<object> & BasePredicate<object | undefined>;
- saveResponseCookies: BooleanPredicate & BasePredicate<boolean | undefined>;
- proxyConfiguration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- contextPipelineBuilder: ObjectPredicate<object> & BasePredicate<object | undefined>;
- extendContext: Predicate<Function> & BasePredicate<Function | undefined>;
- requestList: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestQueue: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- requestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- requestHandlerTimeoutSecs: NumberPredicate & BasePredicate<number | undefined>;
- errorHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- failedRequestHandler: Predicate<Function> & BasePredicate<Function | undefined>;
- maxRequestRetries: NumberPredicate & BasePredicate<number | undefined>;
- sameDomainDelaySecs: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerCrawl: NumberPredicate & BasePredicate<number | undefined>;
- maxCrawlDepth: NumberPredicate & BasePredicate<number | undefined>;
- taskLoopOptions: ObjectPredicate<object> & BasePredicate<object | undefined>;
- concurrencySystem: ObjectPredicate<object> & BasePredicate<object | undefined>;
- sessionPool: ObjectPredicate<object> & BasePredicate<object | undefined>;
- statusMessageLoggingInterval: NumberPredicate & BasePredicate<number | undefined>;
- statusMessageCallback: Predicate<Function> & BasePredicate<Function | undefined>;
- additionalHttpErrorStatusCodes: ArrayPredicate<number>;
- ignoreHttpErrorStatusCodes: ArrayPredicate<number>;
- blockedStatusCodes: ArrayPredicate<number>;
- retryOnBlocked: BooleanPredicate & BasePredicate<boolean | undefined>;
- respectRobotsTxtFile: AnyPredicate<boolean | object>;
- transactionalStorage: BasePredicate<boolean | Partial<StorageWritePolicy> | undefined>;
- onSkippedRequest: Predicate<Function> & BasePredicate<Function | undefined>;
- httpClient: ObjectPredicate<object> & BasePredicate<object | undefined>;
- configuration: ObjectPredicate<object> & BasePredicate<object | undefined>;
- storageBackend: ObjectPredicate<object> & BasePredicate<object | undefined>;
- eventManager: ObjectPredicate<object> & BasePredicate<object | undefined>;
- logger: ObjectPredicate<object> & BasePredicate<object | undefined>;
- minConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxConcurrency: NumberPredicate & BasePredicate<number | undefined>;
- maxRequestsPerMinute: NumberPredicate & BasePredicate<number | undefined>;
- keepAlive: BooleanPredicate & BasePredicate<boolean | undefined>;
- statistics: ObjectPredicate<object> & BasePredicate<object | undefined>;
- id: StringPredicate & BasePredicate<string | undefined>;
+ stagehandOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ browserPoolOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
+ headless: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
+ requestQueue: z.ZodOptional<z.ZodEnum<{
+ deferred: "deferred";
+ writeThrough: "writeThrough";
+ }>>;
+ }, z.core.$strict>]>>;
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
+ id: z.ZodOptional<z.ZodString>;
};
}
diff --git a/docs/public-api/crawlee-utils.api.md b/docs/public-api/crawlee-utils.api.md
index a81cdb1ca..278ffb96c 100644
--- a/docs/public-api/crawlee-utils.api.md
+++ b/docs/public-api/crawlee-utils.api.md
@@ -4,10 +4,18 @@
```ts
-import type { BaseHttpClient } from '@crawlee/types';
+import type { BaseHttpClient } from '@crawlee/http-client';
import type { CheerioAPI } from 'cheerio';
import type { CrawleeLogger } from '@crawlee/types';
import type { Dictionary } from '@crawlee/types';
+import type { z } from 'zod';
+
+// @public
+export class ArgumentValidationError extends Error {
+ constructor(error: z.ZodError, value: unknown, label?: string);
+ readonly cause: z.ZodError;
+ readonly issues: z.ZodError['issues'];
+}
// Not exported by the entry point; reachable only as a referenced type.
// @public (undocumented)
diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.md
index c4825a5f5..ce14f1e3e 100644
--- a/docs/upgrading/upgrading_v4.md
+++ b/docs/upgrading/upgrading_v4.md
@@ -54,6 +54,7 @@ The purely mechanical renames, collected in one place. Where a row links to a se
| `autoscaledPoolOptions` | `taskLoopOptions` ([narrowed](#autoscaledpooloptions-is-now-taskloopoptions-and-no-longer-carries-concurrency-config)) |
| `gotScraping` (from `@crawlee/utils`) | `GotScrapingHttpClient` (`@crawlee/got-scraping-client`) |
| `SDK_`-prefixed internal KVS keys | `CRAWLEE_`-prefixed ([details](#internal-kvs-keys-renamed)) |
+| `ArgumentError` (from `ow`) | `ArgumentValidationError` ([details](#argument-validation-errors-use-zod)) |
## Changes most users will hit
@@ -75,6 +76,42 @@ Support for older TypeScript versions was dropped. Crawlee ships compiled JavaSc
Previously, we kept the dependency on cheerio locked to the latest RC version, since there were many breaking changes introduced in v1.0. This release bumps cheerio to the stable v1. Also, we now use the default `parse5` internally.
+### Argument validation errors use zod
+
+Argument validation moved from `ow` to [zod](https://zod.dev). Invalid inputs now throw `ArgumentValidationError` (previously ow's `ArgumentError`) — update any code catching it by name or `instanceof`.
+
+The messages read field-first and name the received type, value, and the validated interface:
+
+```text
+// v3 (ow)
+Expected property `maxRequestRetries` to be of type `number` but received type `string` in object `HttpCrawlerOptions`
+
+// v4 (zod)
+Invalid input: expected number, received the string `3` at `maxRequestRetries` in `HttpCrawlerOptions`
+```
+
+Unlike ow, all problems are reported at once (one line per issue), and arrays name their element type:
+
+```text
+Invalid input: expected number, received the string `many` at `maxRequestRetries` in `HttpCrawlerOptions`
+Invalid input: expected an array of numbers, received the number `500` at `additionalHttpErrorStatusCodes` in `HttpCrawlerOptions`
+```
+
+For programmatic handling, the error exposes zod's structured output — `error.issues` (the [zod issues](https://zod.dev/error-customization) array) and `error.cause` (the raw `ZodError`):
+
+```ts
+try {
+ new CheerioCrawler({ maxRequestRetries: '3' } as any);
+} catch (error) {
+ if (error instanceof ArgumentValidationError) {
+ error.issues[0].path; // ['maxRequestRetries']
+ error.cause; // ZodError
+ }
+}
+```
+
+One behavioral change: options validated against class interfaces (`httpClient`, `configuration`, `eventManager`) now require actual instances (`instanceof BaseHttpClient`, …) rather than duck-typed plain objects — extend the class (or `Object.create(BaseHttpClient.prototype)` in tests) instead of passing an object literal.
+
### Zod 4.1+ required
`@crawlee/core` used to accept zod 3 as well; it now needs 4.1 or newer, for the codecs it validates persisted state with. Zod is an ordinary dependency rather than a peer, so a project pinned to zod 3 keeps working — it just ends up with both versions installed.
diff --git a/package.json b/package.json
index b39a2f98c..bbedd0099 100644
--- a/package.json
+++ b/package.json
@@ -131,7 +131,7 @@
"typescript": "^6.0.0",
"vite-tsconfig-paths": "^5.1.4",
"vitest": "^4.1.0-beta.6",
- "zod": "^4.0.0"
+ "zod": "catalog:"
},
"lint-staged": {
"{packages,test,docs}/**/*.{js,ts,mjs,mts,cjs,cts}": [
diff --git a/packages/basic-crawler/package.json b/packages/basic-crawler/package.json
index 7064b6ead..f90710ecb 100644
--- a/packages/basic-crawler/package.json
+++ b/packages/basic-crawler/package.json
@@ -47,10 +47,10 @@
"@crawlee/types": "workspace:*",
"@crawlee/utils": "workspace:*",
"csv-stringify": "^6.5.2",
- "ow": "^2.0.0",
"tldts": "^7.0.6",
"tslib": "^2.8.1",
- "type-fest": "^4.41.0"
+ "type-fest": "^4.41.0",
+ "zod": "catalog:"
},
"optionalDependencies": {
"@crawlee/impit-client": "workspace:^"
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.ts
index 3afc05371..b9b991d64 100644
--- a/packages/basic-crawler/src/internals/basic-crawler.ts
+++ b/packages/basic-crawler/src/internals/basic-crawler.ts
@@ -6,12 +6,10 @@ import type {
AddRequestsBatchedResult,
AutoscaledPoolOptions,
ConcurrencySystemOptions,
- Configuration,
CrawleeLogger,
CrawlingContext,
DatasetExportOptions,
EnqueueLinksOptions,
- EventManager,
EventStatusMessageData,
FinalStatistics,
GetUserDataFromRequest,
@@ -38,6 +36,7 @@ import {
bindMethodsToServiceLocator,
BLOCKED_STATUS_CODES,
ConcurrencySystem,
+ Configuration,
ContextPipeline,
ContextPipelineCleanupError,
ContextPipelineInitializationError,
@@ -48,6 +47,7 @@ import {
Dataset,
enqueueLinks,
EnqueueStrategy,
+ EventManager,
EventType,
getObjectType,
KeyValueStore,
@@ -58,6 +58,7 @@ import {
NavigationSkippedError,
NonRetryableError,
OwnedOrInjected,
+ parseArgument,
purgeDefaultStorages,
RequestHandlerError,
parseRetryAfterHeader,
@@ -68,6 +69,7 @@ import {
RetryRequestError,
supportsDomainThrottling,
Router,
+ schemas,
ServiceLocator,
serviceLocator,
Session,
@@ -78,10 +80,9 @@ import {
validators,
withDirectStorageAccess,
} from '@crawlee/core';
-import { FetchHttpClient } from '@crawlee/http-client';
+import { BaseHttpClient, FetchHttpClient } from '@crawlee/http-client';
import type {
Awaitable,
- BaseHttpClient,
BatchAddRequestsResult,
Dictionary,
ISession,
@@ -92,9 +93,9 @@ import type {
} from '@crawlee/types';
import { isAsyncIterable, isIterable, ROTATE_PROXY_ERRORS } from '@crawlee/utils/internal';
import { RobotsTxtFile } from '@crawlee/utils';
-import ow, { ArgumentError, type BasePredicate } from 'ow';
import { getDomain } from 'tldts';
import type { ReadonlyDeep, SetRequired } from 'type-fest';
+import { z } from 'zod';
import { LruCache } from '@apify/datastructures';
import { addTimeoutToPromise, extendTimeout, TimeoutError } from '@apify/timeout';
@@ -109,10 +110,11 @@ import {
} from './request-timeout.js';
import { createSendRequest } from './send-request.js';
-class LazyDefaultHttpClient implements BaseHttpClient {
+class LazyDefaultHttpClient extends BaseHttpClient {
readonly #delegatePromise: Promise<BaseHttpClient>;
constructor(options?: { logger?: CrawleeLogger }) {
+ super(options);
this.#delegatePromise = import('@crawlee/impit-client')
.then(({ ImpitHttpClient }) => new ImpitHttpClient(options))
.catch(() => {
@@ -124,7 +126,11 @@ class LazyDefaultHttpClient implements BaseHttpClient {
});
}
- async sendRequest(...args: Parameters<BaseHttpClient['sendRequest']>): Promise<Response> {
+ protected fetch(): Promise<Response> {
+ throw new Error('LazyDefaultHttpClient delegates `sendRequest` entirely; `fetch` is never called.');
+ }
+
+ override async sendRequest(...args: Parameters<BaseHttpClient['sendRequest']>): Promise<Response> {
return (await this.#delegatePromise).sendRequest(...args);
}
}
@@ -832,62 +838,65 @@ export class BasicCrawler<
};
protected static optionsShape = {
- contextPipelineBuilder: ow.optional.object,
- extendContext: ow.optional.function,
+ contextPipelineBuilder: schemas.anyObject.optional(),
+ extendContext: schemas.anyFunction.optional(),
- requestList: ow.optional.object.validate(validators.requestList),
- requestQueue: ow.optional.object.validate(validators.requestQueue),
- requestManager: ow.optional.object,
+ requestList: validators.requestList.optional(),
+ requestQueue: validators.requestQueue.optional(),
+ requestManager: validators.requestManager.optional(),
// Subclasses override this function instead of passing it
// in constructor, so this validation needs to apply only
// if the user creates an instance of BasicCrawler directly.
- requestHandler: ow.optional.function,
- requestHandlerTimeoutSecs: ow.optional.number,
- errorHandler: ow.optional.function,
- failedRequestHandler: ow.optional.function,
- maxRequestRetries: ow.optional.number,
- sameDomainDelaySecs: ow.optional.number,
- maxRequestsPerCrawl: ow.optional.number,
- maxCrawlDepth: ow.optional.number,
- taskLoopOptions: ow.optional.object,
- concurrencySystem: ow.optional.object,
- sessionPool: ow.optional.object.validate(validators.sessionPool),
- proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),
-
- statusMessageLoggingInterval: ow.optional.number,
- statusMessageCallback: ow.optional.function,
-
- additionalHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),
- ignoreHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),
-
- blockedStatusCodes: ow.optional.array.ofType(ow.number),
- retryOnBlocked: ow.optional.boolean,
- respectRobotsTxtFile: ow.optional.any(ow.boolean, ow.object),
- transactionalStorage: ow.optional.any(
- ow.boolean,
- ow.object.exactShape({
- requestQueue: ow.optional.string.oneOf(['deferred', 'writeThrough']),
- }),
- ) as BasePredicate<boolean | Partial<StorageWritePolicy> | undefined>,
- onSkippedRequest: ow.optional.function,
- httpClient: ow.optional.object,
-
- configuration: ow.optional.object,
- storageBackend: ow.optional.object,
- eventManager: ow.optional.object,
- logger: ow.optional.object,
+ requestHandler: schemas.anyFunction.optional(),
+ requestHandlerTimeoutSecs: schemas.anyNumber.optional(),
+ errorHandler: schemas.anyFunction.optional(),
+ failedRequestHandler: schemas.anyFunction.optional(),
+ maxRequestRetries: schemas.anyNumber.default(3),
+ sameDomainDelaySecs: schemas.anyNumber.default(0),
+ maxRequestsPerCrawl: schemas.anyNumber.optional(),
+ maxCrawlDepth: schemas.anyNumber.optional(),
+ // No zod default — subclasses provide their own fallback (e.g. HTTP-optimized pool options).
+ taskLoopOptions: schemas.anyObject.optional(),
+ concurrencySystem: schemas.anyObject.optional(),
+ sessionPool: validators.sessionPool.optional(),
+ proxyConfiguration: validators.proxyConfiguration.optional(),
+
+ statusMessageLoggingInterval: schemas.anyNumber.default(10),
+ statusMessageCallback: schemas.anyFunction.optional(),
+
+ additionalHttpErrorStatusCodes: schemas.arrayOf(schemas.anyNumber, 'numbers').default(() => []),
+ ignoreHttpErrorStatusCodes: schemas.arrayOf(schemas.anyNumber, 'numbers').default(() => []),
+
+ blockedStatusCodes: schemas.arrayOf(schemas.anyNumber, 'numbers').optional(),
+ retryOnBlocked: z.boolean().default(false),
+ respectRobotsTxtFile: z.union([z.boolean(), schemas.anyObject]).default(false),
+ transactionalStorage: z
+ .union([z.boolean(), z.strictObject({ requestQueue: z.enum(['deferred', 'writeThrough']).optional() })])
+ .optional(),
+ onSkippedRequest: schemas.anyFunction.optional(),
+ httpClient: schemas.httpClient.optional(),
+
+ configuration: z.instanceof(Configuration).optional(),
+ storageBackend: validators.storageBackend.optional(),
+ eventManager: z.instanceof(EventManager).optional(),
+ logger: validators.logger.optional(),
// AutoscaledPool shorthands
- minConcurrency: ow.optional.number,
- maxConcurrency: ow.optional.number,
- maxRequestsPerMinute: ow.optional.number.integerOrInfinite.positive.greaterThanOrEqual(1),
- keepAlive: ow.optional.boolean,
+ minConcurrency: schemas.anyNumber.optional(),
+ maxConcurrency: schemas.anyNumber.optional(),
+ maxRequestsPerMinute: schemas.anyNumber
+ .refine((value) => Number.isInteger(value) || value === Infinity, 'Expected an integer or infinite number')
+ .refine((value) => value >= 1, 'Expected a number greater than or equal to 1')
+ .optional(),
+ keepAlive: z.boolean().optional(),
- statistics: ow.optional.object,
+ statistics: schemas.anyObject.optional(),
- id: ow.optional.string,
+ id: z.string().optional(),
};
+ protected static optionsSchema = z.strictObject(BasicCrawler.optionsShape);
+
/**
* All `BasicCrawler` parameters are passed via an options object.
*/
@@ -895,7 +904,7 @@ export class BasicCrawler<
options: BasicCrawlerOptions<Context, ContextExtension, ExtendedContext, Routes> &
RequireContextPipeline<CrawlingContext, Context> = {} as any, // cast because the constructor logic handles missing `contextPipelineBuilder` - the type is just for DX
) {
- ow(options, 'BasicCrawlerOptions', ow.object.exactShape(BasicCrawler.optionsShape));
+ const parsedOptions = parseArgument(options, BasicCrawler.optionsSchema, 'BasicCrawlerOptions');
const {
// oxlint-disable-next-line typescript/no-deprecated -- still accepted and folded into `requestManager` for back-compat
@@ -903,8 +912,8 @@ export class BasicCrawler<
// oxlint-disable-next-line typescript/no-deprecated -- still accepted and folded into `requestManager` for back-compat
requestQueue,
requestManager,
- maxRequestRetries = 3,
- sameDomainDelaySecs = 0,
+ maxRequestRetries,
+ sameDomainDelaySecs,
maxRequestsPerCrawl,
maxCrawlDepth,
taskLoopOptions = {},
@@ -913,8 +922,8 @@ export class BasicCrawler<
sessionPool,
proxyConfiguration,
- additionalHttpErrorStatusCodes = [],
- ignoreHttpErrorStatusCodes = [],
+ additionalHttpErrorStatusCodes,
+ ignoreHttpErrorStatusCodes,
// Service locator options
configuration,
@@ -928,21 +937,21 @@ export class BasicCrawler<
maxRequestsPerMinute,
blockedStatusCodes: blockedStatusCodesInput,
- retryOnBlocked = false,
- respectRobotsTxtFile = false,
+ retryOnBlocked,
+ respectRobotsTxtFile,
transactionalStorage,
onSkippedRequest,
requestHandler,
requestHandlerTimeoutSecs,
errorHandler,
failedRequestHandler,
- statusMessageLoggingInterval = 10,
+ statusMessageLoggingInterval,
statusMessageCallback,
statistics,
httpClient,
id,
- } = options;
+ } = parsedOptions;
// All concurrency configuration lives on the `ConcurrencySystem`, so the shortcuts have nowhere to go once
// one is supplied - and silently dropping a `maxConcurrency` the user asked for is how crawls end up
@@ -951,11 +960,10 @@ export class BasicCrawler<
concurrencySystem !== undefined &&
(minConcurrency !== undefined || maxConcurrency !== undefined || maxRequestsPerMinute !== undefined)
) {
- throw new ArgumentError(
+ throw new Error(
'The `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts cannot be combined with ' +
'`concurrencySystem` - they configure the default `ConcurrencySystem` that a supplied one ' +
'replaces. Pass them to the `ConcurrencySystem` constructor instead.',
- this.constructor,
);
}
@@ -988,8 +996,8 @@ export class BasicCrawler<
try {
serviceLocatorScope.enterScope();
this.#contextPipelineOptions = {
- contextPipelineBuilder: options.contextPipelineBuilder,
- extendContext: options.extendContext,
+ contextPipelineBuilder: parsedOptions.contextPipelineBuilder,
+ extendContext: parsedOptions.extendContext,
};
this.#log = serviceLocator.getLogger().child({ prefix: this.constructor.name });
@@ -1941,12 +1949,9 @@ export class BasicCrawler<
const maxCrawlDepth = this.maxCrawlDepth;
const validateRequestUserData = this.validateRequestUserData.bind(this);
- ow(
- requests,
- ow.object
- .is((value: unknown) => isIterable(value) || isAsyncIterable(value))
- .message((value) => `Expected an iterable or async iterable, got ${getObjectType(value)}`),
- );
+ if (!isIterable(requests) && !isAsyncIterable(requests)) {
+ throw new Error(`Expected an iterable or async iterable, got ${getObjectType(requests)}`);
+ }
async function* filteredRequests() {
for await (const request of requests) {
diff --git a/packages/basic-crawler/src/internals/send-request.ts b/packages/basic-crawler/src/internals/send-request.ts
index 850426447..8706f8227 100644
--- a/packages/basic-crawler/src/internals/send-request.ts
+++ b/packages/basic-crawler/src/internals/send-request.ts
@@ -1,5 +1,6 @@
import type { Request as CrawleeRequest } from '@crawlee/core';
-import type { BaseHttpClient, HttpRequestOptions, ISession, SendRequestOptions } from '@crawlee/types';
+import type { BaseHttpClient } from '@crawlee/http-client';
+import type { HttpRequestOptions, ISession, SendRequestOptions } from '@crawlee/types';
/**
* Prepares a function to be used as the `sendRequest` context helper.
diff --git a/packages/browser-crawler/package.json b/packages/browser-crawler/package.json
index 14b2743b2..ad7c87ce7 100644
--- a/packages/browser-crawler/package.json
+++ b/packages/browser-crawler/package.json
@@ -52,9 +52,9 @@
"@crawlee/browser-pool": "workspace:*",
"@crawlee/types": "workspace:*",
"@crawlee/utils": "workspace:*",
- "ow": "^2.0.0",
"tslib": "^2.8.1",
- "type-fest": "^4.41.0"
+ "type-fest": "^4.41.0",
+ "zod": "catalog:"
},
"peerDependencies": {
"playwright": "*",
diff --git a/packages/browser-crawler/src/internals/browser-crawler.ts b/packages/browser-crawler/src/internals/browser-crawler.ts
index 5e13ff6cb..6e3799704 100644
--- a/packages/browser-crawler/src/internals/browser-crawler.ts
+++ b/packages/browser-crawler/src/internals/browser-crawler.ts
@@ -21,10 +21,12 @@ import {
enqueueLinks,
NavigationSkippedError,
OwnedOrInjected,
+ parseArgument,
remainingNavigationWindowMillis,
RequestState,
RequestThrottledError,
resolveBaseUrlForEnqueueLinksFiltering,
+ schemas,
SessionError,
toughCookieToBrowserPoolCookie,
tryAbsoluteURL,
@@ -52,8 +54,8 @@ import type {
import type { RobotsTxtFile } from '@crawlee/utils';
import { CLOUDFLARE_RETRY_CSS_SELECTORS, RETRY_CSS_SELECTORS } from '@crawlee/utils/internal';
import { sleep } from '@crawlee/utils';
-import ow from 'ow';
import type { ReadonlyDeep } from 'type-fest';
+import { z } from 'zod';
import { addTimeoutToPromise, TimeoutError, tryCancel } from '@apify/timeout';
@@ -387,19 +389,25 @@ export abstract class BrowserCrawler<
protected static override optionsShape = {
...BasicCrawler.optionsShape,
- navigationTimeoutSecs: ow.optional.number.greaterThan(0),
- preNavigationHooks: ow.optional.array,
- postNavigationHooks: ow.optional.array,
-
- launchContext: ow.optional.object,
- headless: ow.optional.any(ow.boolean, ow.string),
- browserPool: ow.optional.object.validate(validators.browserPool),
- remoteBrowser: ow.optional.object,
- browserPoolOptions: ow.optional.object,
- saveResponseCookies: ow.optional.boolean,
- proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),
+ navigationTimeoutSecs: schemas.anyNumber
+ .refine((value) => value > 0, 'Expected a number greater than 0')
+ .default(60),
+ preNavigationHooks: schemas.anyArray.default(() => []),
+ postNavigationHooks: schemas.anyArray.default(() => []),
+
+ launchContext: schemas.anyObject.default(() => ({})),
+ headless: z.union([z.boolean(), z.string()]).optional(),
+ browserPool: validators.browserPool.optional(),
+ remoteBrowser: schemas.anyObject.optional(),
+ browserPoolOptions: schemas.anyObject.optional(),
+ saveResponseCookies: z.boolean().default(true),
+ proxyConfiguration: validators.proxyConfiguration.optional(),
+ ignoreIframes: z.boolean().default(false),
+ ignoreShadowRoots: z.boolean().default(false),
};
+ protected static override optionsSchema = z.strictObject(BrowserCrawler.optionsShape);
+
/**
* All `BrowserCrawler` parameters are passed via an options object.
*/
@@ -408,23 +416,22 @@ export abstract class BrowserCrawler<
contextPipelineBuilder: () => ContextPipeline<CrawlingContext, Context>;
},
) {
- ow(options, 'BrowserCrawlerOptions', ow.object.exactShape(BrowserCrawler.optionsShape));
const {
- navigationTimeoutSecs = 60,
- saveResponseCookies = true,
- launchContext = {},
+ navigationTimeoutSecs,
+ saveResponseCookies,
+ launchContext,
browserPool,
remoteBrowser,
browserPoolOptions,
- preNavigationHooks = [],
- postNavigationHooks = [],
+ preNavigationHooks,
+ postNavigationHooks,
headless,
- ignoreIframes = false,
- ignoreShadowRoots = false,
+ ignoreIframes,
+ ignoreShadowRoots,
contextPipelineBuilder,
extendContext,
...basicCrawlerOptions
- } = options;
+ } = parseArgument(options, BrowserCrawler.optionsSchema, 'BrowserCrawlerOptions');
const skipGuard = <Ctx extends Context>(
action: (ctx: Ctx) => Awaitable<void | Partial<Ctx>>,
diff --git a/packages/browser-crawler/src/internals/browser-launcher.ts b/packages/browser-crawler/src/internals/browser-launcher.ts
index 824d9f02c..5d7ff98f5 100644
--- a/packages/browser-crawler/src/internals/browser-launcher.ts
+++ b/packages/browser-crawler/src/internals/browser-launcher.ts
@@ -2,10 +2,10 @@ import fs from 'node:fs';
import { createRequire } from 'node:module';
import os from 'node:os';
-import { Configuration } from '@crawlee/basic';
+import { Configuration, schemas } from '@crawlee/basic';
import type { BrowserPlugin, BrowserPluginOptions } from '@crawlee/browser-pool';
import type { Constructor, Dictionary } from '@crawlee/types';
-import ow from 'ow';
+import { z } from 'zod';
const DEFAULT_VIEWPORT = {
width: 1366,
@@ -105,16 +105,18 @@ export abstract class BrowserLauncher<
userAgent?: string;
protected static optionsShape = {
- proxyUrl: ow.optional.string.url,
- useChrome: ow.optional.boolean,
- useIncognitoPages: ow.optional.boolean,
- browserPerProxy: ow.optional.boolean,
- ignoreProxyCertificate: ow.optional.boolean,
- userDataDir: ow.optional.string,
- launchOptions: ow.optional.object,
- userAgent: ow.optional.string,
+ proxyUrl: z.url().optional(),
+ useChrome: z.boolean().optional(),
+ useIncognitoPages: z.boolean().optional(),
+ browserPerProxy: z.boolean().optional(),
+ ignoreProxyCertificate: z.boolean().optional(),
+ userDataDir: z.string().optional(),
+ launchOptions: schemas.anyObject.optional(),
+ userAgent: z.string().optional(),
};
+ protected static optionsSchema = z.strictObject(BrowserLauncher.optionsShape);
+
static requireLauncherOrThrow<T>(launcher: string, apifyImageName: string): T {
try {
return require(launcher); // eslint-disable-line
diff --git a/packages/browser-pool/package.json b/packages/browser-pool/package.json
index 3804982a5..d6fa53377 100644
--- a/packages/browser-pool/package.json
+++ b/packages/browser-pool/package.json
@@ -37,12 +37,12 @@
"fingerprint-injector": "^2.1.68",
"lodash.merge": "^4.6.2",
"nanoid": "^5.1.5",
- "ow": "^2.0.0",
"p-limit": "^6.2.0",
"proxy-chain": "^2.5.8",
"quick-lru": "^7.0.1",
"tiny-typed-emitter": "^2.1.0",
- "tslib": "^2.8.1"
+ "tslib": "^2.8.1",
+ "zod": "catalog:"
},
"peerDependencies": {
"playwright": "*",
diff --git a/packages/browser-pool/src/browser-pool.ts b/packages/browser-pool/src/browser-pool.ts
index 5f9945af0..8c78ef8e7 100644
--- a/packages/browser-pool/src/browser-pool.ts
+++ b/packages/browser-pool/src/browser-pool.ts
@@ -1,15 +1,15 @@
import { AsyncResource } from 'node:async_hooks';
-import { type CrawleeLogger, SessionError, serviceLocator } from '@crawlee/core';
+import { type CrawleeLogger, parseArgument, schemas, SessionError, serviceLocator } from '@crawlee/core';
import type { IBrowserPool, NewPageOptions, PageState } from '@crawlee/types';
import type { BrowserFingerprintWithHeaders } from 'fingerprint-generator';
import { FingerprintGenerator } from 'fingerprint-generator';
import { FingerprintInjector } from 'fingerprint-injector';
import { nanoid } from 'nanoid';
-import ow from 'ow';
import pLimit from 'p-limit';
import QuickLRU from 'quick-lru';
import { TypedEmitter } from 'tiny-typed-emitter';
+import { z } from 'zod';
import { addTimeoutToPromise, tryCancel } from '@apify/timeout';
@@ -29,6 +29,23 @@ const PAGE_CLOSE_TIMEOUT_MILLIS = 5000;
const PAGE_CLOSE_KILL_TIMEOUT_MILLIS = 1000;
const BROWSER_KILLER_INTERVAL_MILLIS = 10 * 1000;
+const browserPoolOptionsSchema = z.strictObject({
+ browserPlugins: schemas.anyArray.refine((value) => value.length >= 1, 'Expected a non-empty array'),
+ maxOpenPagesPerBrowser: schemas.anyNumber.default(20),
+ retireBrowserAfterPageCount: schemas.anyNumber.default(100),
+ operationTimeoutSecs: schemas.anyNumber.default(15),
+ closeInactiveBrowserAfterSecs: schemas.anyNumber.default(300),
+ retireInactiveBrowserAfterSecs: schemas.anyNumber.default(10),
+ preLaunchHooks: schemas.anyArray.default(() => []),
+ postLaunchHooks: schemas.anyArray.default(() => []),
+ prePageCreateHooks: schemas.anyArray.default(() => []),
+ postPageCreateHooks: schemas.anyArray.default(() => []),
+ prePageCloseHooks: schemas.anyArray.default(() => []),
+ postPageCloseHooks: schemas.anyArray.default(() => []),
+ useFingerprints: z.boolean().default(true),
+ fingerprintOptions: schemas.anyObject.default(() => ({})),
+});
+
export interface BrowserPoolEvents<BC extends BrowserController, Page> {
[BROWSER_POOL_EVENTS.PAGE_CREATED]: (page: Page) => void | Promise<void>;
[BROWSER_POOL_EVENTS.PAGE_CLOSED]: (page: Page) => void | Promise<void>;
@@ -350,42 +367,22 @@ export class BrowserPool<
this.browserKillerInterval!.unref();
- ow(
- options,
- ow.object.exactShape({
- browserPlugins: ow.array.minLength(1),
- maxOpenPagesPerBrowser: ow.optional.number,
- retireBrowserAfterPageCount: ow.optional.number,
- operationTimeoutSecs: ow.optional.number,
- closeInactiveBrowserAfterSecs: ow.optional.number,
- retireInactiveBrowserAfterSecs: ow.optional.number,
- preLaunchHooks: ow.optional.array,
- postLaunchHooks: ow.optional.array,
- prePageCreateHooks: ow.optional.array,
- postPageCreateHooks: ow.optional.array,
- prePageCloseHooks: ow.optional.array,
- postPageCloseHooks: ow.optional.array,
- useFingerprints: ow.optional.boolean,
- fingerprintOptions: ow.optional.object,
- }),
- );
-
const {
browserPlugins,
- maxOpenPagesPerBrowser = 20,
- retireBrowserAfterPageCount = 100,
- operationTimeoutSecs = 15,
- closeInactiveBrowserAfterSecs = 300,
- retireInactiveBrowserAfterSecs = 10,
- preLaunchHooks = [],
- postLaunchHooks = [],
- prePageCreateHooks = [],
- postPageCreateHooks = [],
- prePageCloseHooks = [],
- postPageCloseHooks = [],
- useFingerprints = true,
- fingerprintOptions = {},
- } = options;
+ maxOpenPagesPerBrowser,
+ retireBrowserAfterPageCount,
+ operationTimeoutSecs,
+ closeInactiveBrowserAfterSecs,
+ retireInactiveBrowserAfterSecs,
+ preLaunchHooks,
+ postLaunchHooks,
+ prePageCreateHooks,
+ postPageCreateHooks,
+ prePageCloseHooks,
+ postPageCloseHooks,
+ useFingerprints,
+ fingerprintOptions,
+ } = parseArgument(options, browserPoolOptionsSchema);
const firstPluginConstructor = browserPlugins[0].constructor as typeof BrowserPlugin;
diff --git a/packages/core/package.json b/packages/core/package.json
index f5ea38df3..ec797c596 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -53,22 +53,21 @@
"@apify/timeout": "^0.4.4",
"@apify/utilities": "^2.15.5",
"@crawlee/fs-storage": "workspace:*",
+ "@crawlee/http-client": "workspace:*",
"@crawlee/types": "workspace:*",
"@crawlee/utils": "workspace:*",
"@sapphire/async-queue": "^1.5.5",
- "@sapphire/shapeshift": "^4.0.0",
"@vladfrangu/async_event_emitter": "^2.4.6",
"content-type": "^1.0.5",
"csv-stringify": "^6.5.2",
"json5": "^2.2.3",
"mime-types": "^3.0.1",
"minimatch": "^10.0.1",
- "ow": "^2.0.0",
"stream-json": "^1.9.1",
"tldts": "^7.0.6",
"tough-cookie": "^6.0.0",
"tslib": "^2.8.1",
"type-fest": "^4.41.0",
- "zod": "^4.1.0"
+ "zod": "catalog:"
}
}
diff --git a/packages/core/src/autoscaling/autoscaled_pool.ts b/packages/core/src/autoscaling/autoscaled_pool.ts
index 63915cf27..d3c3db009 100644
--- a/packages/core/src/autoscaling/autoscaled_pool.ts
+++ b/packages/core/src/autoscaling/autoscaled_pool.ts
@@ -1,4 +1,4 @@
-import ow from 'ow';
+import { z } from 'zod';
import { addTimeoutToPromise } from '@apify/timeout';
import type { BetterIntervalID } from '@apify/utilities';
@@ -8,6 +8,28 @@ import type { ConcurrencyConsumer, IConcurrencySystem } from './concurrency_syst
import { CriticalError } from '../errors.js';
import type { CrawleeLogger } from '../log.js';
import { serviceLocator } from '../service_locator.js';
+import { parseArgument, schemas, validators } from '../validators.js';
+
+// `schemas.anyObject` and `objectWithKeys`-based validators pass values through by reference
+// (object schemas return a pruned plain copy), so class instances like loggers and the
+// concurrency system keep their prototype.
+const autoscaledPoolOptionsSchema = z.strictObject({
+ runTaskFunction: schemas.anyFunction,
+ isFinishedFunction: schemas.anyFunction,
+ isTaskReadyFunction: schemas.anyFunction,
+ maybeRunIntervalSecs: schemas.anyNumber
+ .refine((value) => value > 0, 'Expected a number greater than 0')
+ .default(0.5),
+ taskTimeoutSecs: schemas.anyNumber
+ .refine((value) => value >= 0, 'Expected a number greater than or equal to 0')
+ .default(0),
+ log: validators.logger.default(() => serviceLocator.getLogger()),
+ concurrencySystem: schemas.anyObject,
+ consumer: schemas.anyObject.refine(
+ (value) => typeof value.id === 'string' && value.id.length > 0,
+ "Expected an object with a non-empty string 'id'",
+ ),
+});
/**
* The two predicates that steer a task loop: *is there work ready?* and *are we done?* These are the parts of the loop
@@ -151,30 +173,16 @@ export class AutoscaledPool {
#ownConcurrency = 0;
constructor(options: AutoscaledPoolOptions) {
- ow(
- options,
- ow.object.exactShape({
- runTaskFunction: ow.function,
- isFinishedFunction: ow.function,
- isTaskReadyFunction: ow.function,
- maybeRunIntervalSecs: ow.optional.number.greaterThan(0),
- taskTimeoutSecs: ow.optional.number.greaterThanOrEqual(0),
- log: ow.optional.object,
- concurrencySystem: ow.object,
- consumer: ow.object.partialShape({ id: ow.string.nonEmpty }),
- }),
- );
-
const {
runTaskFunction,
isFinishedFunction,
isTaskReadyFunction,
- maybeRunIntervalSecs = 0.5,
- taskTimeoutSecs = 0,
- log = serviceLocator.getLogger(),
+ maybeRunIntervalSecs,
+ taskTimeoutSecs,
+ log,
concurrencySystem,
consumer,
- } = options;
+ } = parseArgument(options, autoscaledPoolOptionsSchema, 'AutoscaledPoolOptions');
this.#log = log.child({ prefix: 'AutoscaledPool' });
diff --git a/packages/core/src/autoscaling/concurrency_system.ts b/packages/core/src/autoscaling/concurrency_system.ts
index a89031fd8..b50228381 100644
--- a/packages/core/src/autoscaling/concurrency_system.ts
+++ b/packages/core/src/autoscaling/concurrency_system.ts
@@ -1,16 +1,44 @@
-import ow from 'ow';
+import { z } from 'zod';
import type { BetterIntervalID } from '@apify/utilities';
import { betterClearInterval, betterSetInterval } from '@apify/utilities';
import type { CrawleeLogger } from '../log.js';
import { serviceLocator } from '../service_locator.js';
+import { parseArgument, schemas, validators } from '../validators.js';
import type { LoadSignal } from './load_signal.js';
import { Snapshotter } from './snapshotter.js';
import type { LoadSignalsOptions } from './snapshotter.js';
import type { SystemInfo } from './system_status.js';
import { SystemStatus } from './system_status.js';
+const concurrencySchema = z.number().int().gte(1).optional();
+
+// `schemas.anyObject` passes values through by reference, so the load signal instances inside
+// `loadSignals` and class instances like loggers keep their prototype.
+const concurrencySystemOptionsSchema = z.strictObject({
+ maxConcurrency: z.number().int().gte(1).default(200),
+ minConcurrency: z.number().int().gte(1).default(1),
+ desiredConcurrency: z.number().int().gte(1).optional(),
+ desiredConcurrencyRatio: z.number().gt(0).lt(1).default(0.9),
+ scaleUpStepRatio: z.number().gt(0).lt(1).default(0.05),
+ scaleDownStepRatio: z.number().gt(0).lt(1).default(0.05),
+ loggingIntervalSecs: schemas.anyNumber
+ .refine((value) => value > 0, 'Expected a number greater than 0')
+ .nullish()
+ .default(60),
+ autoscaleIntervalSecs: schemas.anyNumber
+ .refine((value) => value > 0, 'Expected a number greater than 0')
+ .default(10),
+ loadSignals: schemas.anyObject.default(() => ({})),
+ snapshotHistorySecs: schemas.anyNumber.refine((value) => value > 0, 'Expected a number greater than 0').optional(),
+ currentHistorySecs: schemas.anyNumber.refine((value) => value > 0, 'Expected a number greater than 0').optional(),
+ log: validators.logger.default(() => serviceLocator.getLogger()),
+ maxTasksPerMinute: z
+ .union([z.number().int().gte(1), z.literal(Number.POSITIVE_INFINITY)])
+ .default(Number.POSITIVE_INFINITY),
+});
+
export interface ConcurrencySystemOptions {
/**
* The minimum number of tasks running in parallel.
@@ -216,40 +244,21 @@ export class ConcurrencySystem implements IConcurrencySystem {
#warnedAboutQueryWhileStopped = false;
constructor(options: ConcurrencySystemOptions = {}) {
- ow(
- options,
- ow.object.exactShape({
- maxConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),
- minConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),
- desiredConcurrency: ow.optional.number.integer.greaterThanOrEqual(1),
- desiredConcurrencyRatio: ow.optional.number.greaterThan(0).lessThan(1),
- scaleUpStepRatio: ow.optional.number.greaterThan(0).lessThan(1),
- scaleDownStepRatio: ow.optional.number.greaterThan(0).lessThan(1),
- loggingIntervalSecs: ow.any(ow.number.greaterThan(0), ow.nullOrUndefined),
- autoscaleIntervalSecs: ow.optional.number.greaterThan(0),
- loadSignals: ow.optional.object,
- snapshotHistorySecs: ow.optional.number.greaterThan(0),
- currentHistorySecs: ow.optional.number.greaterThan(0),
- log: ow.optional.object,
- maxTasksPerMinute: ow.optional.number.integerOrInfinite.greaterThanOrEqual(1),
- }),
- );
-
const {
- maxConcurrency = 200,
- minConcurrency = 1,
+ maxConcurrency,
+ minConcurrency,
desiredConcurrency,
- desiredConcurrencyRatio = 0.9,
- scaleUpStepRatio = 0.05,
- scaleDownStepRatio = 0.05,
- loggingIntervalSecs = 60,
- autoscaleIntervalSecs = 10,
- loadSignals = {},
+ desiredConcurrencyRatio,
+ scaleUpStepRatio,
+ scaleDownStepRatio,
+ loggingIntervalSecs,
+ autoscaleIntervalSecs,
+ loadSignals,
snapshotHistorySecs,
currentHistorySecs,
- log = serviceLocator.getLogger(),
- maxTasksPerMinute = Infinity,
- } = options;
+ log,
+ maxTasksPerMinute,
+ } = parseArgument(options, concurrencySystemOptionsSchema, 'ConcurrencySystemOptions');
this.log = log.child({ prefix: 'ConcurrencySystem' });
@@ -297,7 +306,7 @@ export class ConcurrencySystem implements IConcurrencySystem {
* If you're not sure, just keep the default value and the concurrency will scale up automatically.
*/
set minConcurrency(value: number) {
- ow(value, ow.optional.number.integer.greaterThanOrEqual(1));
+ parseArgument(value, concurrencySchema);
this.#minConcurrency = value;
this.clampDesiredConcurrency();
}
@@ -316,7 +325,7 @@ export class ConcurrencySystem implements IConcurrencySystem {
* limit as they settle).
*/
set maxConcurrency(value: number) {
- ow(value, ow.optional.number.integer.greaterThanOrEqual(1));
+ parseArgument(value, concurrencySchema);
this.#maxConcurrency = value;
this.clampDesiredConcurrency();
}
@@ -334,7 +343,7 @@ export class ConcurrencySystem implements IConcurrencySystem {
* in parallel if there's large enough supply of tasks.
*/
set desiredConcurrency(value: number) {
- ow(value, ow.optional.number.integer.greaterThanOrEqual(1));
+ parseArgument(value, concurrencySchema);
this.#desiredConcurrency = value;
this.clampDesiredConcurrency();
}
diff --git a/packages/core/src/configuration.ts b/packages/core/src/configuration.ts
index 059857507..d186d7521 100644
--- a/packages/core/src/configuration.ts
+++ b/packages/core/src/configuration.ts
@@ -47,7 +47,7 @@ const logLevelSchema = z.preprocess((val) => {
const key = s.toUpperCase() as keyof typeof LogLevel;
if (key in LogLevel) return LogLevel[key];
return val;
-}, z.nativeEnum(LogLevel));
+}, z.enum(LogLevel));
// --- Crawlee config field definitions ---
@@ -246,8 +246,8 @@ export class Configuration {
}
// 4. Schema default (by parsing undefined through the schema)
- const result = fieldDef.schema.safeParse(undefined);
- values[key] = result.success ? result.data : undefined;
+ const parsed = fieldDef.schema.safeParse(undefined);
+ values[key] = parsed.success ? parsed.data : undefined;
}
return values;
diff --git a/packages/core/src/crawlers/statistics.ts b/packages/core/src/crawlers/statistics.ts
index 05c8789e2..b9e51e5de 100644
--- a/packages/core/src/crawlers/statistics.ts
+++ b/packages/core/src/crawlers/statistics.ts
@@ -1,10 +1,10 @@
-import ow from 'ow';
import { z } from 'zod';
import type { CrawleeLogger } from '../log.js';
import { RecoverableState } from '../recoverable_state.js';
import { serviceLocator } from '../service_locator.js';
-import type { KeyValueStore } from '../storages/key_value_store.js';
+import { KeyValueStore } from '../storages/key_value_store.js';
+import { parseArgument, schemas, validators } from '../validators.js';
import { ErrorTracker } from './error_tracker.js';
/**
@@ -24,6 +24,17 @@ class Job {
}
}
+const statisticsOptionsSchema = z.strictObject({
+ logIntervalSecs: schemas.anyNumber.default(60),
+ logMessage: z.string().default('Statistics'),
+ log: validators.logger.optional(),
+ keyValueStore: z.instanceof(KeyValueStore).optional(),
+ // `schemas.anyObject` passes values through by reference (object schemas return a pruned plain copy).
+ persistenceOptions: schemas.anyObject.default(() => ({ enable: true })),
+ saveErrorSnapshots: z.boolean().default(false),
+ id: z.union([schemas.anyNumber, z.string()]).optional(),
+});
+
const errorTrackerConfig = {
showErrorCode: true,
showErrorName: true,
@@ -305,34 +316,13 @@ export class Statistics implements IStatistics {
* persistence or error snapshots, share it across sequential runs, or subclass it to track extra fields.
*/
constructor(options: StatisticsOptions = {}) {
- ow(
- options,
- ow.object.exactShape({
- logIntervalSecs: ow.optional.number,
- logMessage: ow.optional.string,
- log: ow.optional.object,
- keyValueStore: ow.optional.object,
- persistenceOptions: ow.optional.object,
- saveErrorSnapshots: ow.optional.boolean,
- id: ow.optional.any(ow.number, ow.string),
- }),
- );
-
- const {
- logIntervalSecs = 60,
- logMessage = 'Statistics',
- keyValueStore,
- persistenceOptions = {
- enable: true,
- },
- saveErrorSnapshots = false,
- id,
- } = options;
+ const { logIntervalSecs, logMessage, log, keyValueStore, persistenceOptions, saveErrorSnapshots, id } =
+ parseArgument(options, statisticsOptionsSchema);
this.id = id ?? String(Statistics.id++);
this.persistStateKey = `CRAWLEE_CRAWLER_STATISTICS_${this.id}`;
- this.log = (options.log ?? serviceLocator.getLogger()).child({ prefix: 'Statistics' });
+ this.log = (log ?? serviceLocator.getLogger()).child({ prefix: 'Statistics' });
this.errorTracker = new ErrorTracker({ ...errorTrackerConfig, saveErrorSnapshots });
this.errorTrackerRetry = new ErrorTracker({ ...errorTrackerConfig, saveErrorSnapshots });
this.#logIntervalMillis = logIntervalSecs * 1000;
diff --git a/packages/core/src/debug.ts b/packages/core/src/debug.ts
index 37a9f1b00..d1783aa83 100644
--- a/packages/core/src/debug.ts
+++ b/packages/core/src/debug.ts
@@ -2,9 +2,9 @@ import type { IncomingMessage } from 'node:http';
import { inspect } from 'node:util';
import type { Dictionary } from '@crawlee/types';
-import ow from 'ow';
import type { Request } from './request.js';
+import { parseArgument, schemas } from './validators.js';
interface BrowserResponseLike {
status(): number;
@@ -26,9 +26,9 @@ export function createRequestDebugInfo(
response: IncomingMessage | Partial<BrowserResponseLike> = {},
additionalFields: Dictionary = {},
): Dictionary {
- ow(request, ow.object);
- ow(response, ow.object);
- ow(additionalFields, ow.object);
+ parseArgument(request, schemas.anyObject);
+ parseArgument(response, schemas.anyObject);
+ parseArgument(additionalFields, schemas.anyObject);
return {
requestId: request.id,
diff --git a/packages/core/src/enqueue_links/enqueue_links.ts b/packages/core/src/enqueue_links/enqueue_links.ts
index 4fedb4f3d..d6a6ea634 100644
--- a/packages/core/src/enqueue_links/enqueue_links.ts
+++ b/packages/core/src/enqueue_links/enqueue_links.ts
@@ -1,8 +1,8 @@
import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
import { EnqueueStrategy, type RobotsTxtFile } from '@crawlee/utils';
-import ow from 'ow';
import { getDomain } from 'tldts';
import type { SetRequired } from 'type-fest';
+import { z } from 'zod';
import type { RequestOptions } from '../request.js';
import { Request } from '../request.js';
@@ -12,6 +12,7 @@ import type {
AddRequestsBatchedResult,
RequestQueueOperationOptions,
} from '../storages/request_queue.js';
+import { parseArgument, schemas } from '../validators.js';
import type {
RequestTransform,
SkippedRequestCallback,
@@ -24,6 +25,7 @@ import {
constructUrlPatternObjects,
createRequestOptions,
filterRequestOptionsByPatterns,
+ urlPatternSchema,
} from './shared.js';
export { EnqueueStrategy };
@@ -179,6 +181,29 @@ export interface EnqueueLinksOptions extends RequestQueueOperationOptions {
onSkippedRequest?: SkippedRequestCallback;
}
+// `schemas.anyObject` passes values through by reference (object schemas return a pruned plain
+// copy), so `userData` keeps its identity for the enqueued requests.
+const enqueueLinksOptionsSchema = z.strictObject({
+ urls: schemas.arrayOf(z.string(), 'strings'),
+ requestManager: schemas.objectWithKeys(['addRequestsBatched']),
+ robotsTxtFile: schemas.objectWithKeys(['isAllowed']).optional(),
+ respectRobotsTxtFile: z.union([z.boolean(), z.strictObject({ userAgent: z.string().optional() })]).optional(),
+ onSkippedRequest: schemas.anyFunction.optional(),
+ forefront: z.boolean().optional(),
+ skipNavigation: z.boolean().optional(),
+ sessionId: z.string().optional(),
+ limit: schemas.anyNumber.optional(),
+ selector: z.string().optional(),
+ baseUrl: z.string().optional(),
+ userData: schemas.anyObject.optional(),
+ label: z.string().optional(),
+ include: schemas.arrayOf(urlPatternSchema, 'URL patterns').min(1).optional(),
+ exclude: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
+ transformRequestFunction: schemas.anyFunction.optional(),
+ strategy: z.enum(EnqueueStrategy).optional(),
+ waitForAllRequestsToBeAdded: z.boolean().optional(),
+});
+
/**
* This function enqueues the urls provided to the {@apilink RequestQueue} provided. If you want to automatically find and enqueue links,
* you should use the context-aware `enqueueLinks` function provided on the crawler contexts.
@@ -221,31 +246,7 @@ export async function enqueueLinks(
);
}
- const urlPatternValidator = ow.any(ow.string, ow.regExp, ow.object.hasKeys('glob'), ow.object.hasKeys('regexp'));
-
- ow(
- options as any,
- ow.object.exactShape({
- urls: ow.array.ofType(ow.string),
- requestManager: ow.object.hasKeys('addRequestsBatched'),
- robotsTxtFile: ow.optional.object.hasKeys('isAllowed'),
- respectRobotsTxtFile: ow.optional.any(ow.boolean, ow.object.exactShape({ userAgent: ow.optional.string })),
- onSkippedRequest: ow.optional.function,
- forefront: ow.optional.boolean,
- skipNavigation: ow.optional.boolean,
- sessionId: ow.optional.string,
- limit: ow.optional.number,
- selector: ow.optional.string,
- baseUrl: ow.optional.string,
- userData: ow.optional.object,
- label: ow.optional.string,
- include: ow.optional.array.minLength(1).ofType(urlPatternValidator),
- exclude: ow.optional.array.ofType(urlPatternValidator),
- transformRequestFunction: ow.optional.function,
- strategy: ow.optional.string.oneOf(Object.values(EnqueueStrategy)),
- waitForAllRequestsToBeAdded: ow.optional.boolean,
- }),
- );
+ const parsedOptions = parseArgument(options, enqueueLinksOptionsSchema, 'EnqueueLinksOptions');
const {
requestManager,
@@ -258,21 +259,21 @@ export async function enqueueLinks(
waitForAllRequestsToBeAdded,
robotsTxtFile,
onSkippedRequest,
- } = options;
+ } = parsedOptions;
const urlExcludePatternObjects: UrlPatternObject[] = exclude?.length ? constructUrlPatternObjects(exclude) : [];
const urlPatternObjects: UrlPatternObject[] = include?.length ? constructUrlPatternObjects(include) : [];
// The strategy always applies, even when `include` patterns are provided - the two are AND-ed together
// (a URL must match an `include` pattern *and* satisfy the strategy). This mirrors crawlee-python.
- options.strategy ??= EnqueueStrategy.SameHostname;
+ parsedOptions.strategy ??= EnqueueStrategy.SameHostname;
const enqueueStrategyPatterns: UrlPatternObject[] = [];
- if (options.baseUrl) {
- const url = new URL(options.baseUrl);
+ if (parsedOptions.baseUrl) {
+ const url = new URL(parsedOptions.baseUrl);
- switch (options.strategy) {
+ switch (parsedOptions.strategy) {
case EnqueueStrategy.SameHostname:
// We need to get the origin of the passed in domain in the event someone sets baseUrl
// to an url like https://example.com/deep/default/path and one of the found urls is an
@@ -326,11 +327,13 @@ export async function enqueueLinks(
}
}
- let requestOptions = createRequestOptions(urls, options);
+ let requestOptions = createRequestOptions(urls, parsedOptions);
- if (robotsTxtFile && options.respectRobotsTxtFile !== false) {
+ if (robotsTxtFile && parsedOptions.respectRobotsTxtFile !== false) {
const robotsUserAgent =
- typeof options.respectRobotsTxtFile === 'object' ? (options.respectRobotsTxtFile.userAgent ?? '*') : '*';
+ typeof parsedOptions.respectRobotsTxtFile === 'object'
+ ? (parsedOptions.respectRobotsTxtFile.userAgent ?? '*')
+ : '*';
const skippedRequests: RequestOptions[] = [];
requestOptions = requestOptions.filter((request) => {
@@ -355,7 +358,7 @@ export async function enqueueLinks(
requestOptions,
enqueueStrategyPatterns.length > 0 ? enqueueStrategyPatterns : undefined,
urlExcludePatternObjects,
- options.strategy,
+ parsedOptions.strategy,
(url) => skippedRequests.push(url),
);
} else {
@@ -364,7 +367,7 @@ export async function enqueueLinks(
requestOptions,
urlPatternObjects,
urlExcludePatternObjects,
- options.strategy,
+ parsedOptions.strategy,
(url) => skippedRequests.push(url),
);
// ...then filter by the enqueue links strategy (making this an AND check)
@@ -372,7 +375,7 @@ export async function enqueueLinks(
afterUserPatterns,
enqueueStrategyPatterns.length > 0 ? enqueueStrategyPatterns : undefined,
[],
- options.strategy,
+ parsedOptions.strategy,
(url) => skippedRequests.push(url),
);
}
diff --git a/packages/core/src/enqueue_links/shared.ts b/packages/core/src/enqueue_links/shared.ts
index e399a8ec2..b865ba43c 100644
--- a/packages/core/src/enqueue_links/shared.ts
+++ b/packages/core/src/enqueue_links/shared.ts
@@ -2,8 +2,10 @@ import { URL } from 'node:url';
import type { Awaitable } from '@crawlee/types';
import { Minimatch } from 'minimatch';
+import { z } from 'zod';
import type { RequestOptions } from '../request.js';
+import { schemas } from '../validators.js';
import type { EnqueueLinksOptions } from './enqueue_links.js';
export { tryAbsoluteURL } from '@crawlee/utils/internal';
@@ -37,6 +39,17 @@ export type RegExpInput = RegExp | RegExpObject;
/** Unified URL pattern input — accepts glob strings, glob objects, RegExp instances, or regexp objects. */
export type UrlPatternInput = GlobInput | RegExpInput;
+/**
+ * Accepts one {@apilink UrlPatternInput} — a glob string, a RegExp instance, or a `{ glob }` / `{ regexp }` object.
+ * @internal
+ */
+export const urlPatternSchema = z.union([
+ z.string(),
+ z.instanceof(RegExp),
+ schemas.objectWithKeys(['glob']),
+ schemas.objectWithKeys(['regexp']),
+]) as z.ZodType<UrlPatternInput>;
+
export type SkippedRequestReason =
| 'robotsTxt'
| 'limit'
diff --git a/packages/core/src/memory-storage/resource-clients/dataset.ts b/packages/core/src/memory-storage/resource-clients/dataset.ts
index 1023f035d..b5a5aa877 100644
--- a/packages/core/src/memory-storage/resource-clients/dataset.ts
+++ b/packages/core/src/memory-storage/resource-clients/dataset.ts
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
import type * as storage from '@crawlee/types';
import type { Dictionary } from '@crawlee/types';
-import { s } from '@sapphire/shapeshift';
+import { parseArgument, schemas } from '@crawlee/utils/internal';
import type { MemoryStorageBackend } from '../memory-storage.js';
import { BaseClient } from './common/base-client.js';
@@ -80,13 +80,7 @@ export class DatasetBackend<Data extends Dictionary = Dictionary>
}
getData(options: storage.DatasetBackendListOptions = {}): Promise<storage.PaginatedList<Data>> {
- const { desc, limit, offset } = s
- .object({
- desc: s.boolean().optional(),
- limit: s.number().int().optional(),
- offset: s.number().int().optional(),
- })
- .parse(options);
+ const { desc, limit, offset } = parseArgument(options, schemas.datasetListItemsOptions);
return this.getDataPage({
desc,
diff --git a/packages/core/src/memory-storage/resource-clients/key-value-store.ts b/packages/core/src/memory-storage/resource-clients/key-value-store.ts
index c07da456a..70f2d2240 100644
--- a/packages/core/src/memory-storage/resource-clients/key-value-store.ts
+++ b/packages/core/src/memory-storage/resource-clients/key-value-store.ts
@@ -1,7 +1,8 @@
import { randomUUID } from 'node:crypto';
import type * as storage from '@crawlee/types';
-import { s } from '@sapphire/shapeshift';
+import { parseArgument, schemas } from '@crawlee/utils/internal';
+import { z } from 'zod';
import type { MemoryStorageBackend } from '../memory-storage.js';
import { isStream, toBuffer } from '../utils.js';
@@ -10,6 +11,22 @@ import mime from 'mime-types';
const DEFAULT_LOCAL_FILE_EXTENSION = 'bin';
+const keySchema = z.string();
+const inputRecordSchema = z.object({
+ key: z.string().min(1),
+ value: z.union([
+ z.null(),
+ z.string(),
+ z.number(),
+ z.instanceof(Buffer),
+ z.instanceof(ArrayBuffer),
+ schemas.typedArray,
+ // only checks the value is an actual object, not null, nor array
+ schemas.plainObject,
+ ]),
+ contentType: z.string().min(1).optional(),
+});
+
/**
* Key under which a run's input is stored in the default key-value store. Matches Crawlee's default
* `inputKey` (`CRAWLEE_INPUT_KEY`) and the `INPUT` files `FileSystemStorageBackend` preserves on purge.
@@ -93,13 +110,7 @@ export class KeyValueStoreBackend extends BaseClient implements storage.KeyValue
}
async listKeys(options: storage.KeyValueStoreListKeysOptions = {}): Promise<storage.KeyValueStoreListKeysResult> {
- const { prefix, exclusiveStartKey, limit } = s
- .object({
- prefix: s.string().optional(),
- exclusiveStartKey: s.string().optional(),
- limit: s.number().int().greaterThan(0).optional(),
- })
- .parse(options);
+ const { prefix, exclusiveStartKey, limit } = parseArgument(options, schemas.keyValueStoreListKeysOptions);
const items: storage.KeyValueStoreItemData[] = [];
@@ -150,7 +161,7 @@ export class KeyValueStoreBackend extends BaseClient implements storage.KeyValue
* @param key The key of the record to generate the public URL for.
*/
async getPublicUrl(key: string): Promise<string | undefined> {
- s.string().parse(key);
+ parseArgument(key, keySchema);
return undefined;
}
@@ -162,13 +173,13 @@ export class KeyValueStoreBackend extends BaseClient implements storage.KeyValue
* @returns `true` if the record exists, `false` if it does not.
*/
async recordExists(key: string): Promise<boolean> {
- s.string().parse(key);
+ parseArgument(key, keySchema);
return this.#keyValueEntries.has(key);
}
async getValue(key: string): Promise<storage.KeyValueStoreRecord | undefined> {
- s.string().parse(key);
+ parseArgument(key, keySchema);
const entry = this.#keyValueEntries.get(key);
@@ -192,20 +203,7 @@ export class KeyValueStoreBackend extends BaseClient implements storage.KeyValue
}
async setValue(record: storage.KeyValueStoreInputRecord): Promise<void> {
- s.object({
- key: s.string().lengthGreaterThan(0),
- value: s.union([
- s.null(),
- s.string(),
- s.number(),
- s.instance(Buffer),
- s.instance(ArrayBuffer),
- s.typedArray(),
- // disabling validation will make shapeshift only check the object given is an actual object, not null, nor array
- s.object({}).setValidationEnabled(false),
- ]),
- contentType: s.string().lengthGreaterThan(0).optional(),
- }).parse(record);
+ parseArgument(record, inputRecordSchema);
const { key } = record;
let { value } = record;
@@ -245,7 +243,7 @@ export class KeyValueStoreBackend extends BaseClient implements storage.KeyValue
}
async deleteValue(key: string): Promise<void> {
- s.string().parse(key);
+ parseArgument(key, keySchema);
if (this.#keyValueEntries.has(key)) {
this.#keyValueEntries.delete(key);
diff --git a/packages/core/src/memory-storage/resource-clients/request-queue.ts b/packages/core/src/memory-storage/resource-clients/request-queue.ts
index b8b47dcfe..4c098832a 100644
--- a/packages/core/src/memory-storage/resource-clients/request-queue.ts
+++ b/packages/core/src/memory-storage/resource-clients/request-queue.ts
@@ -1,30 +1,14 @@
import { randomUUID } from 'node:crypto';
import type * as storage from '@crawlee/types';
+import { parseArgument, schemas } from '@crawlee/utils/internal';
import { AsyncQueue } from '@sapphire/async-queue';
-import { s } from '@sapphire/shapeshift';
+import { z } from 'zod';
import type { MemoryStorageBackend } from '../memory-storage.js';
import { purgeNullsFromObject, uniqueKeyToRequestId } from '../utils.js';
import { BaseClient } from './common/base-client.js';
-const requestShape = s
- .object({
- id: s.string(),
- url: s.string().url({ allowedProtocols: ['http:', 'https:'] }),
- uniqueKey: s.string(),
- method: s.string().optional(),
- retryCount: s.number().int().optional(),
- handledAt: s.union([s.string(), s.date().valid()]).optional(),
- })
- .passthrough();
-
-const requestShapeWithoutId = requestShape.omit(['id']);
-
-const batchRequestShapeWithoutId = requestShapeWithoutId.array();
-
-const requestOptionsShape = s.object({
- forefront: s.boolean().optional(),
-});
+const uniqueKeySchema = z.string();
export interface RequestQueueBackendOptions {
name?: string;
@@ -248,8 +232,8 @@ export class RequestQueueBackend extends BaseClient implements storage.RequestQu
requests: storage.RequestSchema[],
options: storage.RequestQueueOperationOptions = {},
): Promise<storage.BatchAddRequestsResult> {
- batchRequestShapeWithoutId.parse(requests);
- requestOptionsShape.parse(options);
+ parseArgument(requests, schemas.storageRequestBatch);
+ parseArgument(options, schemas.requestQueueOperationOptions);
// Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so that the
// shared `requests` map, `forefrontRequestIds` array and request counts are not corrupted by a
@@ -309,7 +293,7 @@ export class RequestQueueBackend extends BaseClient implements storage.RequestQu
}
async getRequest(uniqueKey: string): Promise<storage.UpdateRequestSchema | undefined> {
- s.string().parse(uniqueKey);
+ parseArgument(uniqueKey, uniqueKeySchema);
this.updateTimestamps(false);
const id = uniqueKeyToRequestId(uniqueKey);
const json = this.#requests.get(id)?.json;
@@ -317,7 +301,7 @@ export class RequestQueueBackend extends BaseClient implements storage.RequestQu
}
async markRequestAsHandled(request: storage.UpdateRequestSchema): Promise<storage.QueueOperationInfo | undefined> {
- requestShape.parse(request);
+ parseArgument(request, schemas.storageRequest);
this.updateTimestamps(false);
// Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
@@ -369,8 +353,8 @@ export class RequestQueueBackend extends BaseClient implements storage.RequestQu
request: storage.UpdateRequestSchema,
options: storage.RequestQueueOperationOptions = {},
): Promise<storage.QueueOperationInfo | undefined> {
- requestShape.parse(request);
- requestOptionsShape.parse(options);
+ parseArgument(request, schemas.storageRequest);
+ parseArgument(options, schemas.requestQueueOperationOptions);
this.updateTimestamps(false);
// Serialize against other mutators (and the head scans in `isEmpty`/`isFinished`) so the shared
diff --git a/packages/core/src/proxy_configuration.ts b/packages/core/src/proxy_configuration.ts
index 6a55f6d81..fd1c2ac7c 100644
--- a/packages/core/src/proxy_configuration.ts
+++ b/packages/core/src/proxy_configuration.ts
@@ -1,7 +1,16 @@
import type { Dictionary, ProxyInfo } from '@crawlee/types';
-import ow from 'ow';
+import { z } from 'zod';
import type { Request } from './request.js';
+import { parseArgument, schemas } from './validators.js';
+
+const proxyConfigurationOptionsSchema = z.strictObject({
+ proxyUrls: z
+ .array(z.union([z.url(), z.null()]))
+ .nonempty()
+ .optional(),
+ newUrlFunction: schemas.anyFunction.optional(),
+});
export interface ProxyConfigurationFunction {
(options?: { request?: Request }): string | null | Promise<string | null>;
@@ -112,16 +121,11 @@ export class ProxyConfiguration implements IProxyConfiguration {
);
}
- ow(
- rest,
- ow.object.exactShape({
- proxyUrls: ow.optional.array.nonEmpty.ofType(ow.any(ow.string.url, ow.null)),
- newUrlFunction: ow.optional.function,
- }),
+ const { proxyUrls, newUrlFunction } = parseArgument(
+ rest as ProxyConfigurationOptions,
+ proxyConfigurationOptionsSchema,
);
- const { proxyUrls, newUrlFunction } = options;
-
if (proxyUrls && newUrlFunction) this.throwCannotCombineCustomMethods();
if (!proxyUrls && !newUrlFunction && validateRequired) this.throwNoOptionsProvided();
diff --git a/packages/core/src/request.ts b/packages/core/src/request.ts
index 2b1f642ce..b80e84de6 100644
--- a/packages/core/src/request.ts
+++ b/packages/core/src/request.ts
@@ -3,8 +3,7 @@ import crypto from 'node:crypto';
import util from 'node:util';
import type { AllowedHttpMethods, Dictionary } from '@crawlee/types';
-import type { BasePredicate } from 'ow';
-import ow from 'ow';
+import { z } from 'zod';
import { cryptoRandomObjectId, normalizeUrl } from '@apify/utilities';
@@ -12,30 +11,11 @@ import type { EnqueueLinksOptions } from './enqueue_links/enqueue_links.js';
import type { SkippedRequestReason } from './enqueue_links/shared.js';
import { serviceLocator } from './service_locator.js';
import { keys } from './typedefs.js';
+import { parseArgument, schemas } from './validators.js';
-// new properties on the Request object breaks serialization
-const requestOptionalPredicates = {
- id: ow.optional.string,
- loadedUrl: ow.optional.string.url,
- uniqueKey: ow.optional.string,
- method: ow.optional.string,
- payload: ow.optional.any(ow.string, ow.uint8Array),
- noRetry: ow.optional.boolean,
- retryCount: ow.optional.number,
- sessionId: ow.optional.string,
- maxRetries: ow.optional.number,
- errorMessages: ow.optional.array.ofType(ow.string),
- headers: ow.optional.object,
- userData: ow.optional.object,
- label: ow.optional.string,
- handledAt: ow.optional.any(ow.string.date, ow.date),
- keepUrlFragment: ow.optional.boolean,
- useExtendedUniqueKey: ow.optional.boolean,
- alwaysEnqueue: ow.optional.boolean,
- skipNavigation: ow.optional.boolean,
- crawlDepth: ow.optional.number.greaterThanOrEqual(0),
- state: ow.optional.number.greaterThanOrEqual(0).lessThanOrEqual(6),
-};
+const dateString = z.string().refine((value) => !Number.isNaN(Date.parse(value)), {
+ message: 'Invalid input: expected a date string',
+});
export enum RequestState {
UNPROCESSED,
@@ -48,6 +28,39 @@ export enum RequestState {
SKIPPED,
}
+const requestUrlSchema = z.object({ url: z.string() });
+
+// new properties on the Request object breaks serialization
+const requestOptionalSchemaShapes: Record<string, z.ZodType> = {
+ id: z.string().optional(),
+ loadedUrl: z.url().optional(),
+ uniqueKey: z.string().optional(),
+ method: z.string().optional(),
+ payload: z.union([z.string(), z.instanceof(Uint8Array)]).optional(),
+ noRetry: z.boolean().optional(),
+ retryCount: schemas.anyNumber.optional(),
+ sessionId: z.string().optional(),
+ maxRetries: schemas.anyNumber.optional(),
+ errorMessages: schemas.arrayOf(z.string(), 'strings').optional(),
+ headers: z.looseObject({}).optional(),
+ userData: z.looseObject({}).optional(),
+ label: z.string().optional(),
+ handledAt: z.union([dateString, z.date()]).optional(),
+ keepUrlFragment: z.boolean().optional(),
+ useExtendedUniqueKey: z.boolean().optional(),
+ alwaysEnqueue: z.boolean().optional(),
+ skipNavigation: z.boolean().optional(),
+ crawlDepth: schemas.anyNumber
+ .refine((value) => value >= 0, 'Expected a number greater than or equal to 0')
+ .optional(),
+ state: z.enum(RequestState).optional(),
+};
+
+// Each schema is wrapped in a single-key object so validation errors carry the property name.
+const requestOptionalSchemas: Partial<Record<string, z.ZodType>> = Object.fromEntries(
+ Object.entries(requestOptionalSchemaShapes).map(([key, schema]) => [key, z.object({ [key]: schema })]),
+);
+
/**
* Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata.
* The `Request` object also stores information about errors that occurred during processing of the request.
@@ -141,23 +154,30 @@ class CrawleeRequest<UserData extends Dictionary = Dictionary> {
* `Request` parameters including the URL, HTTP method and headers, and others.
*/
constructor(options: RequestOptions<UserData>) {
- ow(options, 'RequestOptions', ow.object);
- ow(options.url, 'RequestOptions.url', ow.string);
- // 'ow' validation is slow, because it checks all predicates
+ // A bare URL is a common slip — point at the object form instead of a generic type error.
+ if (typeof options === 'string') {
+ throw new TypeError(
+ `\`Request\` options must be an object, got the string '${options}'. ` +
+ 'Did you mean `new Request({ url })`?',
+ );
+ }
+
+ parseArgument(options, schemas.anyObject, 'RequestOptions');
+ parseArgument(options, requestUrlSchema, 'RequestOptions');
+ // Full-shape validation is slow, because it checks all predicates
// even if the validated object has only 1 property.
// This custom validation loop iterates only over existing
// properties and speeds up the validation cca 3-fold.
- // See https://github.com/sindresorhus/ow/issues/193
keys(options).forEach((prop) => {
// skip url, because it is validated above
if (prop === 'url') {
return;
}
- const predicate = requestOptionalPredicates[prop as keyof typeof requestOptionalPredicates];
+ const schema = requestOptionalSchemas[prop as string];
const value = options[prop];
- if (predicate) {
- ow(value, `RequestOptions.${prop}`, predicate as BasePredicate);
+ if (schema) {
+ parseArgument({ [prop]: value }, schema, 'RequestOptions');
}
});
diff --git a/packages/core/src/serialization.ts b/packages/core/src/serialization.ts
index eabf34a28..b2c7ba7c0 100644
--- a/packages/core/src/serialization.ts
+++ b/packages/core/src/serialization.ts
@@ -2,11 +2,15 @@ import { pipeline as streamPipeline, Readable, Writable } from 'node:stream';
import util from 'node:util';
import zlib from 'node:zlib';
-import ow from 'ow';
import StreamArray from 'stream-json/streamers/StreamArray.js';
+import { z } from 'zod';
+
+import { parseArgument, schemas } from './validators.js';
const pipeline = util.promisify(streamPipeline);
+const uint8ArraySchema = z.instanceof(Uint8Array);
+
type Chain = ReturnType<typeof StreamArray.withParser>;
/**
@@ -62,7 +66,7 @@ class ArrayToJson<T> extends Readable {
* @internal
*/
export async function serializeArray<T>(data: T[]): Promise<Buffer> {
- ow(data, ow.array);
+ parseArgument(data, schemas.anyArray);
const { chunks, collector } = createChunkCollector();
await pipeline(new ArrayToJson(data), zlib.createGzip(), collector);
@@ -79,7 +83,7 @@ export async function serializeArray<T>(data: T[]): Promise<Buffer> {
* @internal
*/
export async function deserializeArray<T extends string | Buffer>(compressedData: Buffer | Uint8Array): Promise<T[]> {
- ow(compressedData, ow.uint8Array);
+ parseArgument(compressedData, uint8ArraySchema);
const { chunks, collector } = createChunkCollector<T>({ fromValuesStream: true });
await pipeline(Readable.from([compressedData]), zlib.createGunzip(), StreamArray.withParser(), collector);
@@ -96,7 +100,7 @@ export async function deserializeArray<T extends string | Buffer>(compressedData
* @internal
*/
export function createDeserialize(compressedData: Buffer | Uint8Array): Readable {
- ow(compressedData, ow.uint8Array);
+ parseArgument(compressedData, uint8ArraySchema);
const streamArray = StreamArray.withParser();
const destination = pluckValue(streamArray);
diff --git a/packages/core/src/session_pool/session.ts b/packages/core/src/session_pool/session.ts
index b26826408..bdf95887c 100644
--- a/packages/core/src/session_pool/session.ts
+++ b/packages/core/src/session_pool/session.ts
@@ -1,12 +1,33 @@
import type { Dictionary, ISession, ProxyInfo, SessionFingerprint, SessionState } from '@crawlee/types';
-import ow from 'ow';
import { CookieJar } from 'tough-cookie';
+import { z } from 'zod';
import { cryptoRandomObjectId } from '@apify/utilities';
import { getDefaultCookieExpirationDate } from '../cookie_utils.js';
import type { CrawleeLogger } from '../log.js';
import { serviceLocator } from '../service_locator.js';
+import { parseArgument, schemas, validators } from '../validators.js';
+
+// `schemas.anyObject` passes values through by reference (object schemas return a pruned plain
+// copy), so class instances like cookie jars and loggers keep their prototype.
+const sessionOptionsSchema = z.strictObject({
+ id: z.string().default(() => `session_${cryptoRandomObjectId(10)}`),
+ cookieJar: schemas.anyObject.default(() => new CookieJar()),
+ proxyInfo: schemas.anyObject.optional(),
+ maxAgeSecs: schemas.anyNumber.default(3000),
+ userData: schemas.anyObject.default(() => ({})),
+ maxErrorScore: schemas.anyNumber.default(3),
+ errorScoreDecrement: schemas.anyNumber.default(0.5),
+ createdAt: z.date().default(() => new Date()),
+ expiresAt: z.date().optional(),
+ usageCount: schemas.anyNumber.default(0),
+ errorScore: schemas.anyNumber.default(0),
+ maxUsageCount: schemas.anyNumber.default(50),
+ retired: z.boolean().default(false),
+ log: validators.logger.default(() => serviceLocator.getLogger()),
+ fingerprint: schemas.anyObject.optional(),
+});
export interface SessionOptions {
/** Id of session used for generating fingerprints. It is used as proxy session name. */
@@ -155,45 +176,23 @@ export class Session implements ISession {
* Session configuration.
*/
constructor(options: SessionOptions = {}) {
- ow(
- options,
- ow.object.exactShape({
- id: ow.optional.string,
- cookieJar: ow.optional.object,
- proxyInfo: ow.optional.object,
- maxAgeSecs: ow.optional.number,
- userData: ow.optional.object,
- maxErrorScore: ow.optional.number,
- errorScoreDecrement: ow.optional.number,
- createdAt: ow.optional.date,
- expiresAt: ow.optional.date,
- usageCount: ow.optional.number,
- errorScore: ow.optional.number,
- maxUsageCount: ow.optional.number,
- retired: ow.optional.boolean,
- log: ow.optional.object,
- fingerprint: ow.optional.object,
- }),
- );
-
const {
- id = `session_${cryptoRandomObjectId(10)}`,
- cookieJar = new CookieJar(),
- proxyInfo = undefined,
- maxAgeSecs = 3000,
- userData = {},
- maxErrorScore = 3,
- errorScoreDecrement = 0.5,
- createdAt = new Date(),
- usageCount = 0,
- errorScore = 0,
- maxUsageCount = 50,
- retired = false,
- log = serviceLocator.getLogger(),
+ id,
+ cookieJar,
+ proxyInfo,
+ maxAgeSecs,
+ userData,
+ maxErrorScore,
+ errorScoreDecrement,
+ createdAt,
+ usageCount,
+ errorScore,
+ maxUsageCount,
+ retired,
+ log,
fingerprint,
- } = options;
-
- const { expiresAt = getDefaultCookieExpirationDate(maxAgeSecs) } = options;
+ expiresAt = getDefaultCookieExpirationDate(maxAgeSecs),
+ } = parseArgument(options, sessionOptionsSchema);
this.#log = log.child({ prefix: 'Session' });
diff --git a/packages/core/src/session_pool/session_pool.ts b/packages/core/src/session_pool/session_pool.ts
index 16754c7c7..3b5ec298a 100644
--- a/packages/core/src/session_pool/session_pool.ts
+++ b/packages/core/src/session_pool/session_pool.ts
@@ -1,6 +1,6 @@
import type { Dictionary, ISessionPool } from '@crawlee/types';
import { AsyncQueue } from '@sapphire/async-queue';
-import ow from 'ow';
+import { z } from 'zod';
import type { PersistenceOptions } from '../crawlers/statistics.js';
import type { EventManager } from '../events/event_manager.js';
@@ -8,6 +8,7 @@ import { EventType } from '../events/event_manager.js';
import type { CrawleeLogger } from '../log.js';
import { serviceLocator } from '../service_locator.js';
import { KeyValueStore } from '../storages/key_value_store.js';
+import { parseArgument, schemas, validators } from '../validators.js';
import { MAX_POOL_SIZE, PERSIST_STATE_KEY } from './consts.js';
import { createDefaultSessionFingerprint } from './fingerprint.js';
import type { SessionOptions } from './session.js';
@@ -16,6 +17,23 @@ import { Session } from './session.js';
const SESSION_REUSE_STRATEGIES = ['random', 'round-robin', 'use-until-failure'] as const;
export type SessionReuseStrategy = (typeof SESSION_REUSE_STRATEGIES)[number];
+// `schemas.anyObject` passes values through by reference (object schemas return a pruned plain
+// copy), so class instances like loggers keep their prototype.
+const sessionPoolOptionsSchema = z.strictObject({
+ id: z.union([schemas.anyNumber, z.string()]).optional(),
+ maxPoolSize: schemas.anyNumber.default(MAX_POOL_SIZE),
+ persistStateKeyValueStoreId: z.string().optional(),
+ persistStateKey: z.string().optional(),
+ createSessionFunction: schemas.anyFunction.optional(),
+ sessionOptions: schemas.anyObject.default(() => ({})),
+ log: validators.logger.default(() => serviceLocator.getLogger()),
+ persistenceOptions: schemas.anyObject.default(() => ({ enable: true })),
+ sessionReuseStrategy: z.enum(SESSION_REUSE_STRATEGIES).default('random'),
+});
+const createSessionOptionsSchema = z.strictObject({
+ sessionOptions: schemas.anyObject.default(() => ({})),
+});
+
/**
* Factory user-function which creates customized {@apilink Session} instances.
*/
@@ -154,34 +172,17 @@ export class SessionPool implements ISessionPool {
#roundRobinIndex = 0;
constructor(options: SessionPoolOptions = {}) {
- ow(
- options,
- ow.object.exactShape({
- id: ow.optional.any(ow.number, ow.string),
- maxPoolSize: ow.optional.number,
- persistStateKeyValueStoreId: ow.optional.string,
- persistStateKey: ow.optional.string,
- createSessionFunction: ow.optional.function,
- sessionOptions: ow.optional.object,
- log: ow.optional.object,
- persistenceOptions: ow.optional.object,
- sessionReuseStrategy: ow.optional.string.oneOf([...SESSION_REUSE_STRATEGIES]),
- }),
- );
-
const {
id,
- maxPoolSize = MAX_POOL_SIZE,
+ maxPoolSize,
persistStateKeyValueStoreId,
persistStateKey,
createSessionFunction,
- sessionOptions = {},
- log = serviceLocator.getLogger(),
- persistenceOptions = {
- enable: true,
- },
- sessionReuseStrategy = 'random',
- } = options;
+ sessionOptions,
+ log,
+ persistenceOptions,
+ sessionReuseStrategy,
+ } = parseArgument(options, sessionPoolOptionsSchema);
this.id = id != null ? String(id) : String(SessionPool.#nextId++);
this.#sessionReuseStrategy = sessionReuseStrategy;
@@ -433,8 +434,7 @@ export class SessionPool implements ISessionPool {
* @returns New session.
*/
private async defaultCreateSessionFunction(options: { sessionOptions?: SessionOptions } = {}): Promise<Session> {
- ow(options, ow.object.exactShape({ sessionOptions: ow.optional.object }));
- const { sessionOptions = {} } = options;
+ const { sessionOptions } = parseArgument(options, createSessionOptionsSchema);
return new Session(sessionOptions);
}
diff --git a/packages/core/src/storages/dataset.ts b/packages/core/src/storages/dataset.ts
index 3ebd767a5..7d5fc63e6 100644
--- a/packages/core/src/storages/dataset.ts
+++ b/packages/core/src/storages/dataset.ts
@@ -1,11 +1,12 @@
import type { Awaitable, DatasetBackend, DatasetInfo, Dictionary, PaginatedList } from '@crawlee/types';
-import ow from 'ow';
+import { z } from 'zod';
import { tryCancel } from '@apify/timeout';
import { Configuration } from '../configuration.js';
import type { CrawleeLogger } from '../log.js';
import { serviceLocator } from '../service_locator.js';
+import { parseArgument, schemas, validators } from '../validators.js';
import type { DatasetJournalEntry, JournalEntry } from './transaction.js';
import { activeStorageTransaction, rejectOperationInTransaction, snapshotValue } from './transaction.js';
import { KeyValueStore } from './key_value_store.js';
@@ -16,6 +17,11 @@ import type { StorageIdentifier } from './storage_instance_manager.js';
import { resolveStorageIdentifier } from './storage_instance_manager.js';
import { createDualIterable, purgeDefaultStorages } from './utils.js';
+const openOptionsSchema = z.strictObject({
+ configuration: z.instanceof(Configuration).optional(),
+ storageBackend: validators.storageBackend.optional(),
+});
+
/** @internal */
export const DATASET_ITERATORS_DEFAULT_LIMIT = 10000;
@@ -231,7 +237,7 @@ export class Dataset<Data extends Dictionary = Dictionary> {
async pushData(data: Data | Data[]): Promise<void> {
const transaction = activeStorageTransaction();
- ow(data, 'data', ow.object);
+ parseArgument(data, schemas.anyObject);
// Normalize to array and validate each item
const items = Array.isArray(data) ? data : [data];
@@ -796,19 +802,12 @@ export class Dataset<Data extends Dictionary = Dictionary> {
): Promise<Dataset<Data>> {
tryCancel();
- ow(
- options,
- ow.object.exactShape({
- configuration: ow.optional.object.instanceOf(Configuration),
- storageBackend: ow.optional.object,
- }),
- );
-
- options.configuration ??= Configuration.getGlobalConfiguration();
+ const parsedOptions = parseArgument(options, openOptionsSchema);
- const storageBackend = options.storageBackend ?? serviceLocator.getStorageBackend();
+ const configuration = parsedOptions.configuration ?? Configuration.getGlobalConfiguration();
+ const storageBackend = parsedOptions.storageBackend ?? serviceLocator.getStorageBackend();
- await purgeDefaultStorages({ onlyPurgeOnce: true, storageBackend, configuration: options.configuration });
+ await purgeDefaultStorages({ onlyPurgeOnce: true, storageBackend, configuration });
const resolved = await resolveStorageIdentifier(identifier, storageBackend, 'Dataset');
diff --git a/packages/core/src/storages/key_value_store.ts b/packages/core/src/storages/key_value_store.ts
index f5fec0a5e..58a583463 100644
--- a/packages/core/src/storages/key_value_store.ts
+++ b/packages/core/src/storages/key_value_store.ts
@@ -5,13 +5,14 @@ import type {
KeyValueStoreInfo,
KeyValueStoreItemData,
} from '@crawlee/types';
-import ow, { ArgumentError } from 'ow';
+import { z } from 'zod';
import { KEY_VALUE_STORE_KEY_REGEX } from '@apify/consts';
import { tryCancel } from '@apify/timeout';
import { Configuration } from '../configuration.js';
import { serviceLocator } from '../service_locator.js';
+import { parseArgument, schemas, validators } from '../validators.js';
import type { JournalEntry, KeyValueStoreJournalEntry } from './transaction.js';
import {
activeStorageTransaction,
@@ -32,6 +33,21 @@ import { isBuffer, isStream } from '../byte_utils.js';
/** @internal */
const KVS_KEYS_DEFAULT_LIMIT = 1000;
+const keySchema = z.string().nonempty();
+const setValueKeySchema = z.string().nonempty().regex(KEY_VALUE_STORE_KEY_REGEX, {
+ message: `The "key" argument must be at most 256 characters long and only contain the following characters: a-zA-Z0-9!-_.'()`,
+});
+const recordOptionsSchema = z.strictObject({
+ contentType: z.string().nonempty().optional(),
+});
+const iteratorOptionsSchema = z.strictObject({
+ prefix: z.string().optional(),
+});
+const openOptionsSchema = z.strictObject({
+ configuration: z.instanceof(Configuration).optional(),
+ storageBackend: validators.storageBackend.optional(),
+});
+
/**
* The `KeyValueStore` class represents a key-value store, a simple data storage that is used
* for saving and reading data records or files. Each data record is
@@ -224,7 +240,7 @@ export class KeyValueStore {
async getValue<T = unknown>(key: string, defaultValue?: T): Promise<T | null> {
tryCancel();
- ow(key, ow.string.nonEmpty);
+ parseArgument(key, keySchema);
const record = await this.readRecord(key);
// A missing record falls back to the default; a record that parses to a falsy value (including
@@ -322,7 +338,7 @@ export class KeyValueStore {
async getRecord(key: string): Promise<KeyValueStoreRawRecord | null> {
tryCancel();
- ow(key, ow.string.nonEmpty);
+ parseArgument(key, keySchema);
return this.readRecord(key);
}
@@ -335,7 +351,7 @@ export class KeyValueStore {
async recordExists(key: string): Promise<boolean> {
tryCancel();
- ow(key, ow.string.nonEmpty);
+ parseArgument(key, keySchema);
const entry = this.bufferedJournalEntries()?.get(key);
if (entry) {
@@ -503,29 +519,14 @@ export class KeyValueStore {
async setValue<T>(key: string, value: T | null, options: RecordOptions = {}): Promise<void> {
const transaction = activeStorageTransaction();
- ow(key, 'key', ow.string.nonEmpty);
- ow(
- key,
- ow.string.validate((k) => ({
- validator: ow.isValid(k, ow.string.matches(KEY_VALUE_STORE_KEY_REGEX)),
- message: `The "key" argument "${key}" must be at most 256 characters long and only contain the following characters: a-zA-Z0-9!-_.'()`,
- })),
- );
+ parseArgument(key, setValueKeySchema);
if (options.contentType && !(typeof value === 'string' || isBuffer(value) || isStream(value))) {
- throw new ArgumentError(
+ throw new Error(
'The "value" parameter must be a String, Buffer, ArrayBuffer, TypedArray, or Stream when "options.contentType" is specified.',
- this.setValue,
);
}
- ow(
- options,
- ow.object.exactShape({
- contentType: ow.optional.string.nonEmpty,
- }),
- );
-
- // Make copy of options, don't update what user passed.
- const optionsCopy = { ...options };
+ // The parse result is a fresh copy, so we never update what user passed.
+ const optionsCopy = parseArgument(options, recordOptionsSchema);
// The whole transaction branch sits *above* the auto-saved cache update below, so a buffered
// write touches nothing outside the journal. That cache is shared, process-lifetime frontend
@@ -650,17 +651,12 @@ export class KeyValueStore {
async forEachKey(iteratee: KeyConsumer, options: KeyValueStoreIteratorOptions = {}): Promise<void> {
tryCancel();
- ow(iteratee, ow.function);
- ow(
- options,
- ow.object.exactShape({
- prefix: ow.optional.string,
- }),
- );
+ parseArgument(iteratee, schemas.anyFunction);
+ const parsedOptions = parseArgument(options, iteratorOptionsSchema);
let index = 0;
- for await (const page of this.fetchKeyPages(options)) {
+ for await (const page of this.fetchKeyPages(parsedOptions)) {
for (const item of page) {
await iteratee(item.key, index++, { size: item.size });
}
@@ -813,18 +809,12 @@ export class KeyValueStore {
): Promise<KeyValueStore> {
tryCancel();
- ow(
- options,
- ow.object.exactShape({
- configuration: ow.optional.object.instanceOf(Configuration),
- storageBackend: ow.optional.object,
- }),
- );
+ const parsedOptions = parseArgument(options, openOptionsSchema);
- options.configuration ??= Configuration.getGlobalConfiguration();
- const storageBackend = options.storageBackend ?? serviceLocator.getStorageBackend();
+ const configuration = parsedOptions.configuration ?? Configuration.getGlobalConfiguration();
+ const storageBackend = parsedOptions.storageBackend ?? serviceLocator.getStorageBackend();
- await purgeDefaultStorages({ onlyPurgeOnce: true, storageBackend, configuration: options.configuration });
+ await purgeDefaultStorages({ onlyPurgeOnce: true, storageBackend, configuration });
const resolved = await resolveStorageIdentifier(identifier, storageBackend, 'KeyValueStore');
diff --git a/packages/core/src/storages/request_list.ts b/packages/core/src/storages/request_list.ts
index 491339a66..6f78403d1 100644
--- a/packages/core/src/storages/request_list.ts
+++ b/packages/core/src/storages/request_list.ts
@@ -1,6 +1,7 @@
-import type { BaseHttpClient, Dictionary } from '@crawlee/types';
+import type { BaseHttpClient } from '@crawlee/http-client';
+import type { Dictionary } from '@crawlee/types';
import { downloadListOfUrls } from '@crawlee/utils';
-import ow, { ArgumentError } from 'ow';
+import { z } from 'zod';
import type { Configuration } from '../configuration.js';
import { EventType } from '../events/event_manager.js';
@@ -9,6 +10,7 @@ import type { IProxyConfiguration } from '../proxy_configuration.js';
import { type InternalSource, Request, type RequestOptions, type Source } from '../request.js';
import { createDeserialize, serializeArray } from '../serialization.js';
import { serviceLocator } from '../service_locator.js';
+import { parseArgument, schemas, validators } from '../validators.js';
import { KeyValueStore } from './key_value_store.js';
import type { IRequestLoader } from './request_loader.js';
import type { IRequestManager } from './request_manager.js';
@@ -22,6 +24,25 @@ export const REQUESTS_PERSISTENCE_KEY = 'REQUEST_LIST_REQUESTS';
const CONTENT_TYPE_BINARY = 'application/octet-stream';
+const requestListOptionsSchema = z.strictObject({
+ sources: schemas.anyArray.optional(), // check only for array and not subtypes to avoid iteration over the whole thing
+ sourcesFunction: schemas.anyFunction.optional(),
+ persistStateKey: z.string().optional(),
+ persistRequestsKey: z.string().optional(),
+ state: z
+ .strictObject({
+ nextIndex: schemas.anyNumber,
+ nextUniqueKey: z.string(),
+ inProgress: schemas.anyObject, // persisted as an array of unique keys
+ })
+ .optional(),
+ keepDuplicateUrls: z.boolean().default(false),
+ proxyConfiguration: validators.proxyConfiguration.optional(),
+ httpClient: schemas.httpClient.optional(),
+});
+const listNameSchema = z.string().nullish();
+const openOptionsSchema = z.looseObject({});
+
export interface RequestListOptions {
/**
* An array of sources of URLs for the {@apilink RequestList}. It can be either an array of strings,
@@ -305,33 +326,13 @@ export class RequestList implements IRequestLoader {
persistRequestsKey,
state,
proxyConfiguration,
- keepDuplicateUrls = false,
+ keepDuplicateUrls,
httpClient,
- } = options;
+ } = parseArgument(options, requestListOptionsSchema);
if (!(sources || sourcesFunction)) {
- throw new ArgumentError(
- 'At least one of "sources" or "sourcesFunction" must be provided.',
- this.constructor,
- );
+ throw new Error('At least one of "sources" or "sourcesFunction" must be provided.');
}
- ow(
- options,
- ow.object.exactShape({
- sources: ow.optional.array, // check only for array and not subtypes to avoid iteration over the whole thing
- sourcesFunction: ow.optional.function,
- persistStateKey: ow.optional.string,
- persistRequestsKey: ow.optional.string,
- state: ow.optional.object.exactShape({
- nextIndex: ow.number,
- nextUniqueKey: ow.string,
- inProgress: ow.object,
- }),
- keepDuplicateUrls: ow.optional.boolean,
- proxyConfiguration: ow.optional.object,
- httpClient: ow.optional.object,
- }),
- );
this.#persistStateKey = persistStateKey ? `CRAWLEE_${persistStateKey}` : persistStateKey;
this.#persistRequestsKey = persistRequestsKey ? `CRAWLEE_${persistRequestsKey}` : persistRequestsKey;
@@ -912,12 +913,9 @@ export class RequestList implements IRequestLoader {
const listName = listNameOrOptions;
- ow(listName, ow.optional.any(ow.string, ow.null));
- ow(sources, ow.array);
- ow(
- options,
- ow.object.is((v) => !Array.isArray(v)),
- );
+ parseArgument(listName, listNameSchema);
+ parseArgument(sources, schemas.anyArray);
+ parseArgument(options, openOptionsSchema);
const rl = new RequestList({
...options,
diff --git a/packages/core/src/storages/request_queue.ts b/packages/core/src/storages/request_queue.ts
index df28b5b55..2954462cd 100644
--- a/packages/core/src/storages/request_queue.ts
+++ b/packages/core/src/storages/request_queue.ts
@@ -1,7 +1,7 @@
import { inspect } from 'node:util';
+import type { BaseHttpClient } from '@crawlee/http-client';
import type {
- BaseHttpClient,
BatchAddRequestsResult,
Constructor,
Dictionary,
@@ -12,8 +12,8 @@ import type {
} from '@crawlee/types';
import { isAsyncIterable, isIterable } from '@crawlee/utils/internal';
import { downloadListOfUrls } from '@crawlee/utils';
-import ow from 'ow';
import type { ReadonlyDeep } from 'type-fest';
+import { z } from 'zod';
import { LruCache } from '@apify/datastructures';
import { tryCancel } from '@apify/timeout';
@@ -27,6 +27,7 @@ import type { IProxyConfiguration } from '../proxy_configuration.js';
import type { InternalSource, RequestOptions, Source } from '../request.js';
import { Request } from '../request.js';
import { serviceLocator } from '../service_locator.js';
+import { parseArgument, schemas, validators } from '../validators.js';
import type { JournalEntry, StorageTransaction } from './transaction.js';
import { activeStorageTransaction, rejectOperationInTransaction } from './transaction.js';
import { drainRequestBatches } from './batched_adds.js';
@@ -45,6 +46,44 @@ import { RequestDeduplicationCache } from './request_dedup_cache.js';
*/
const MAX_CACHED_REQUESTS = 2_000_000;
+const iterableSchema = z.custom((value) => isIterable(value) || isAsyncIterable(value), {
+ error: (issue) => `Expected an iterable or async iterable, got ${getObjectType(issue.input)}`,
+});
+const operationOptionsSchema = z.strictObject({
+ forefront: z.boolean().default(false),
+});
+const addRequestsOptionsSchema = z.strictObject({
+ forefront: z.boolean().default(false),
+ cache: z.boolean().default(true),
+});
+const addRequestsBatchedOptionsSchema = z.strictObject({
+ forefront: z.boolean().optional(),
+ waitForAllRequestsToBeAdded: z.boolean().default(false),
+ batchSize: schemas.anyNumber.default(1000),
+ waitBetweenBatchesMillis: schemas.anyNumber.default(1000),
+ maxNewRequests: schemas.anyNumber.optional(),
+});
+const newRequestLikeSchema = z.looseObject({
+ url: z.string(),
+ id: z.undefined().optional(),
+});
+const handledRequestSchema = z.looseObject({
+ id: z.string(),
+ uniqueKey: z.string(),
+ handledAt: z.string().optional(),
+});
+const reclaimedRequestSchema = z.looseObject({
+ id: z.string(),
+ uniqueKey: z.string(),
+});
+const uniqueKeySchema = z.string();
+const openOptionsSchema = z.strictObject({
+ configuration: z.instanceof(Configuration).optional(),
+ storageBackend: validators.storageBackend.optional(),
+ proxyConfiguration: validators.proxyConfiguration.optional(),
+ httpClient: schemas.httpClient.optional(),
+});
+
/**
* Represents a queue of URLs to crawl, which is used for deep crawling of websites
* where you start with several URLs and then recursively
@@ -186,15 +225,8 @@ export class RequestQueue implements IStorage, IRequestManager {
): Promise<RequestQueueOperationInfo> {
const transaction = activeStorageTransaction();
- ow(requestLike, ow.object);
- ow(
- options,
- ow.object.exactShape({
- forefront: ow.optional.boolean,
- }),
- );
-
- const { forefront = false } = options;
+ parseArgument(requestLike, schemas.anyObject);
+ const { forefront } = parseArgument(options, operationOptionsSchema);
if ('requestsFromUrl' in requestLike) {
const requests = await this.fetchRequestsFromUrl(requestLike as InternalSource);
@@ -203,15 +235,9 @@ export class RequestQueue implements IStorage, IRequestManager {
return { ...processedRequests[0], forefront };
}
- ow(
- requestLike,
- ow.object.partialShape({
- url: ow.string,
- id: ow.undefined,
- }),
- );
+ parseArgument(requestLike, newRequestLikeSchema);
- const request = requestLike instanceof Request ? requestLike : new Request(requestLike);
+ const request = requestLike instanceof Request ? requestLike : new Request(requestLike as RequestOptions);
if (transaction?.policy.requestQueue === 'deferred') {
return this.addRequestDeferred(transaction, request, forefront);
@@ -445,21 +471,8 @@ export class RequestQueue implements IStorage, IRequestManager {
): Promise<BatchAddRequestsResult> {
const transaction = activeStorageTransaction();
- ow(
- requestsLike,
- ow.object
- .is((value: unknown) => isIterable(value) || isAsyncIterable(value))
- .message((value) => `Expected an iterable or async iterable, got ${getObjectType(value)}`),
- );
- ow(
- options,
- ow.object.exactShape({
- forefront: ow.optional.boolean,
- cache: ow.optional.boolean,
- }),
- );
-
- const { forefront = false, cache = true } = options;
+ parseArgument(requestsLike, iterableSchema);
+ const { forefront, cache } = parseArgument(options, addRequestsOptionsSchema);
const uniqueKeyToCacheKey = new Map<string, string>();
const getCachedRequestId = (uniqueKey: string) => {
@@ -571,23 +584,10 @@ export class RequestQueue implements IStorage, IRequestManager {
requests: ReadonlyDeep<RequestsLike>,
options: AddRequestsBatchedOptions = {},
): Promise<AddRequestsBatchedResult> {
- ow(
- requests,
- ow.object
- .is((value: unknown) => isIterable(value) || isAsyncIterable(value))
- .message((value) => `Expected an iterable or async iterable, got ${getObjectType(value)}`),
- );
+ parseArgument(requests, iterableSchema);
- ow(
- options,
- ow.object.exactShape({
- forefront: ow.optional.boolean,
- waitForAllRequestsToBeAdded: ow.optional.boolean,
- batchSize: ow.optional.number,
- waitBetweenBatchesMillis: ow.optional.number,
- maxNewRequests: ow.optional.number,
- }),
- );
+ const { forefront, waitForAllRequestsToBeAdded, batchSize, waitBetweenBatchesMillis, maxNewRequests } =
+ parseArgument(options, addRequestsBatchedOptionsSchema);
const addRequest = this.addRequest.bind(this);
@@ -619,7 +619,7 @@ export class RequestQueue implements IStorage, IRequestManager {
if (opts && typeof opts === 'object' && 'requestsFromUrl' in opts) {
// Handle URL lists right away
- await addRequest(opts, { forefront: options.forefront });
+ await addRequest(opts, { forefront });
} else {
// Yield valid requests
yield typeof opts === 'string' ? { url: opts } : (opts as RequestOptions);
@@ -629,10 +629,10 @@ export class RequestQueue implements IStorage, IRequestManager {
return drainRequestBatches<RequestOptions>({
items: generateRequests(),
- batchSize: options.batchSize ?? 1000,
- waitBetweenBatchesMillis: options.waitBetweenBatchesMillis ?? 1000,
- waitForAllRequestsToBeAdded: options.waitForAllRequestsToBeAdded ?? false,
- maxNewRequests: options.maxNewRequests,
+ batchSize,
+ waitBetweenBatchesMillis,
+ waitForAllRequestsToBeAdded,
+ maxNewRequests,
/**
* Requests the backend reports as unprocessed are warned about and skipped rather than retried:
@@ -642,7 +642,7 @@ export class RequestQueue implements IStorage, IRequestManager {
*/
processChunk: async (chunk, isInitial) => {
const { processedRequests, unprocessedRequests } = await this.addRequests(chunk, {
- forefront: options.forefront,
+ forefront,
cache: isInitial,
});
@@ -675,7 +675,7 @@ export class RequestQueue implements IStorage, IRequestManager {
async getRequest<T extends Dictionary = Dictionary>(uniqueKey: string): Promise<Request<T> | null> {
const transaction = activeStorageTransaction();
- ow(uniqueKey, ow.string);
+ parseArgument(uniqueKey, uniqueKeySchema);
// Requests buffered by the active transaction (under the `deferred` write policy) are visible to it.
const buffered = transaction && this.bufferedRequests(transaction).get(uniqueKey);
@@ -735,21 +735,14 @@ export class RequestQueue implements IStorage, IRequestManager {
'it is part of the crawler request-processing bookkeeping, which a transaction must not affect.',
);
- ow(
- request,
- ow.object.partialShape({
- id: ow.string,
- uniqueKey: ow.string,
- handledAt: ow.optional.string,
- }),
- );
+ parseArgument(request, handledRequestSchema);
const forefront = this.requestCache.get(getRequestId(request.uniqueKey))?.forefront ?? false;
const handledAt = request.handledAt ?? new Date().toISOString();
this.#statsTracker.add('writeCount');
const processedRequest = await this.backend.markRequestAsHandled({
- ...request,
+ ...(request as Request & { id: string }),
handledAt,
});
@@ -786,24 +779,13 @@ export class RequestQueue implements IStorage, IRequestManager {
'it is part of the crawler request-processing bookkeeping, which a transaction must not affect.',
);
- ow(
- request,
- ow.object.partialShape({
- id: ow.string,
- uniqueKey: ow.string,
- }),
- );
- ow(
- options,
- ow.object.exactShape({
- forefront: ow.optional.boolean,
- }),
- );
-
- const { forefront = false } = options;
+ parseArgument(request, reclaimedRequestSchema);
+ const { forefront } = parseArgument(options, operationOptionsSchema);
this.#statsTracker.add('writeCount');
- const processedRequest = await this.backend.reclaimRequest(request, { forefront });
+ const processedRequest = await this.backend.reclaimRequest(request as Request & { id: string }, {
+ forefront,
+ });
// The request was not in progress — nothing to reclaim.
if (!processedRequest) {
@@ -1082,18 +1064,10 @@ export class RequestQueue implements IStorage, IRequestManager {
): Promise<RequestQueue> {
tryCancel();
- ow(
- options,
- ow.object.exactShape({
- configuration: ow.optional.object.instanceOf(Configuration),
- storageBackend: ow.optional.object,
- proxyConfiguration: ow.optional.object,
- httpClient: ow.optional.object,
- }),
- );
+ const parsedOptions = parseArgument(options, openOptionsSchema);
- const storageBackend = options.storageBackend ?? serviceLocator.getStorageBackend();
- const configuration = options.configuration ?? serviceLocator.getConfiguration();
+ const storageBackend = parsedOptions.storageBackend ?? serviceLocator.getStorageBackend();
+ const configuration = parsedOptions.configuration ?? serviceLocator.getConfiguration();
await purgeDefaultStorages({ onlyPurgeOnce: true, storageBackend, configuration });
@@ -1106,8 +1080,8 @@ export class RequestQueue implements IStorage, IRequestManager {
backendOpener: () => storageBackend.createRequestQueueBackend(resolved),
backendCacheKey: storageBackend.getStorageBackendCacheKey?.() ?? storageBackend.constructor.name,
});
- queue.#proxyConfiguration = options.proxyConfiguration;
- queue.#httpClient = options.httpClient;
+ queue.#proxyConfiguration = parsedOptions.proxyConfiguration;
+ queue.#httpClient = parsedOptions.httpClient;
return queue;
}
diff --git a/packages/core/src/storages/sitemap_request_loader.ts b/packages/core/src/storages/sitemap_request_loader.ts
index 90bb02e27..f6f031600 100644
--- a/packages/core/src/storages/sitemap_request_loader.ts
+++ b/packages/core/src/storages/sitemap_request_loader.ts
@@ -1,22 +1,38 @@
import { Transform } from 'node:stream';
-import type { BaseHttpClient } from '@crawlee/types';
+import type { BaseHttpClient } from '@crawlee/http-client';
import { EnqueueStrategy, parseSitemap, type ParseSitemapOptions } from '@crawlee/utils';
import { minimatch } from 'minimatch';
-import ow from 'ow';
import type { RequiredDeep } from 'type-fest';
+import { z } from 'zod';
import type { UrlPatternInput, UrlPatternObject } from '../enqueue_links/shared.js';
-import { constructUrlPatternObjects } from '../enqueue_links/shared.js';
+import { constructUrlPatternObjects, urlPatternSchema } from '../enqueue_links/shared.js';
import { type EventManager, EventType } from '../events/event_manager.js';
import type { CrawleeLogger } from '../log.js';
import { Request } from '../request.js';
import { serviceLocator } from '../service_locator.js';
+import { parseArgument, schemas } from '../validators.js';
import { KeyValueStore } from './key_value_store.js';
import type { IRequestLoader } from './request_loader.js';
import type { IRequestManager } from './request_manager.js';
import { purgeDefaultStorages } from './utils.js';
+const sitemapRequestLoaderOptionsSchema = z.strictObject({
+ sitemapUrls: schemas.arrayOf(z.string(), 'strings'),
+ proxyUrl: z.string().optional(),
+ persistStateKey: z.string().optional(),
+ signal: z.unknown().optional(),
+ timeoutMillis: schemas.anyNumber.optional(),
+ maxBufferSize: schemas.anyNumber.default(200),
+ enqueueStrategy: z.enum(EnqueueStrategy).default(EnqueueStrategy.SameHostname),
+ parseSitemapOptions: z.looseObject({}).optional(),
+ include: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
+ exclude: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
+ persistenceOptions: z.looseObject({}).optional(),
+ httpClient: schemas.httpClient.optional(),
+});
+
/** @internal */
const STATE_PERSISTENCE_KEY = 'SITEMAP_REQUEST_LOADER_STATE';
@@ -203,32 +219,16 @@ export class SitemapRequestLoader implements IRequestLoader {
/** @internal */
private constructor(options: SitemapRequestLoaderOptions) {
- const urlPatternValidator = ow.any(
- ow.string,
- ow.regExp,
- ow.object.hasKeys('glob'),
- ow.object.hasKeys('regexp'),
- );
-
- ow(
- options,
- ow.object.exactShape({
- sitemapUrls: ow.array.ofType(ow.string),
- proxyUrl: ow.optional.string,
- persistStateKey: ow.optional.string,
- signal: ow.optional.any(),
- timeoutMillis: ow.optional.number,
- maxBufferSize: ow.optional.number,
- enqueueStrategy: ow.optional.string.oneOf(Object.values(EnqueueStrategy)),
- parseSitemapOptions: ow.optional.object,
- include: ow.optional.array.ofType(urlPatternValidator),
- exclude: ow.optional.array.ofType(urlPatternValidator),
- persistenceOptions: ow.optional.object,
- httpClient: ow.optional.object,
- }),
- );
-
- const { include, exclude } = options;
+ const {
+ include,
+ exclude,
+ persistStateKey,
+ persistenceOptions,
+ proxyUrl,
+ maxBufferSize,
+ sitemapUrls,
+ enqueueStrategy,
+ } = parseArgument(options, sitemapRequestLoaderOptionsSchema, 'SitemapRequestLoaderOptions');
this.#log = serviceLocator.getLogger().child({ prefix: 'SitemapRequestLoader' });
@@ -240,15 +240,15 @@ export class SitemapRequestLoader implements IRequestLoader {
this.#urlPatternObjects.push(...constructUrlPatternObjects(include));
}
- this.#persistStateKey = options.persistStateKey;
- this.#persistenceOptions = { enable: true, ...options.persistenceOptions };
+ this.#persistStateKey = persistStateKey;
+ this.#persistenceOptions = { enable: true, ...persistenceOptions };
- this.#proxyUrl = options.proxyUrl;
- this.#enqueueStrategy = options.enqueueStrategy ?? EnqueueStrategy.SameHostname;
+ this.#proxyUrl = proxyUrl;
+ this.#enqueueStrategy = enqueueStrategy;
- this.#urlQueueStream = this.createNewStream(options.maxBufferSize ?? 200);
+ this.#urlQueueStream = this.createNewStream(maxBufferSize);
- this.#sitemapParsingProgress.pendingSitemapUrls = new Set(options.sitemapUrls);
+ this.#sitemapParsingProgress.pendingSitemapUrls = new Set(sitemapUrls);
this.#events = serviceLocator.getEventManager();
this.persistState = this.persistState.bind(this);
diff --git a/packages/core/src/storages/throttling_request_manager.ts b/packages/core/src/storages/throttling_request_manager.ts
index c3ac8a739..bc6ec3fd4 100644
--- a/packages/core/src/storages/throttling_request_manager.ts
+++ b/packages/core/src/storages/throttling_request_manager.ts
@@ -1,6 +1,6 @@
import { URL } from 'node:url';
import type { Dictionary } from '@crawlee/types';
-import ow from 'ow';
+import { z } from 'zod';
import type { Configuration } from '../configuration.js';
import { PersistentRateLimitError } from '../errors.js';
@@ -9,6 +9,7 @@ import type { CrawleeLogger } from '../log.js';
import type { Request, Source } from '../request.js';
import { serviceLocator } from '../service_locator.js';
import { normalizeHostname } from '../url.js';
+import { parseArgument, schemas } from '../validators.js';
import { drainRequestBatches } from './batched_adds.js';
import type { IRequestManager, RequestsLike } from './request_manager.js';
import type {
@@ -21,6 +22,15 @@ import { RequestQueue } from './request_queue.js';
import type { StorageIdentifier } from './storage_instance_manager.js';
import type { StorageOpenOptions } from './utils.js';
+const throttlingRequestManagerOptionsSchema = z.strictObject({
+ inner: schemas.anyObject,
+ domains: schemas.arrayOf(z.string().nonempty(), 'non-empty strings'),
+ requestManagerOpener: schemas.anyFunction.optional(),
+ baseDelaySecs: schemas.anyNumber.refine((value) => value > 0, 'Expected a number greater than 0').optional(),
+ maxDelaySecs: schemas.anyNumber.refine((value) => value > 0, 'Expected a number greater than 0').optional(),
+ maxDomainStallSecs: schemas.anyNumber.refine((value) => value > 0, 'Expected a number greater than 0').optional(),
+});
+
/**
* Opens a request manager, matching the shape of storage `open` methods such as
* {@apilink RequestQueue.open|`RequestQueue.open`}.
@@ -210,17 +220,7 @@ export class ThrottlingRequestManager<T extends IRequestManager = IRequestManage
options: ThrottlingRequestManagerOptions<T>,
private readonly config: Configuration = serviceLocator.getConfiguration(),
) {
- ow(
- options,
- ow.object.exactShape({
- inner: ow.object,
- domains: ow.array.ofType(ow.string.nonEmpty),
- requestManagerOpener: ow.optional.function,
- baseDelaySecs: ow.optional.number.positive,
- maxDelaySecs: ow.optional.number.positive,
- maxDomainStallSecs: ow.optional.number.positive,
- }),
- );
+ parseArgument(options, throttlingRequestManagerOptionsSchema, 'ThrottlingRequestManagerOptions');
this.inner = options.inner;
this.requestManagerOpener =
diff --git a/packages/core/src/storages/utils.ts b/packages/core/src/storages/utils.ts
index 58d3f3f8e..0abc1affe 100644
--- a/packages/core/src/storages/utils.ts
+++ b/packages/core/src/storages/utils.ts
@@ -1,6 +1,7 @@
import crypto from 'node:crypto';
-import type { BaseHttpClient, Dictionary, StorageBackend } from '@crawlee/types';
+import type { BaseHttpClient } from '@crawlee/http-client';
+import type { Dictionary, StorageBackend } from '@crawlee/types';
import { Configuration } from '../configuration.js';
import type { IProxyConfiguration } from '../proxy_configuration.js';
diff --git a/packages/core/src/validators.ts b/packages/core/src/validators.ts
index b00fe36f5..d012de3f9 100644
--- a/packages/core/src/validators.ts
+++ b/packages/core/src/validators.ts
@@ -1,34 +1,43 @@
-import type { Dictionary } from '@crawlee/types';
-import ow from 'ow';
+import { schemas } from '@crawlee/utils/internal';
+
+export { ArgumentValidationError, parseArgument } from '@crawlee/utils';
+export { schemas } from '@crawlee/utils/internal';
/** @internal */
export const validators = {
// Naming it browser page for future proofing with Playwright
- browserPage: (value: Dictionary) => ({
- validator: ow.isValid(value, ow.object.hasKeys('goto', 'evaluate', '$', 'on')),
- message: (label: string) => `Expected argument '${label}' to be a Puppeteer Page, got something else.`,
- }),
- proxyConfiguration: (value: Dictionary) => ({
- validator: ow.isValid(value, ow.object.hasKeys('newProxyInfo')),
- message: (label: string) =>
- `Expected argument '${label}' to implement the IProxyConfiguration interface (missing 'newProxyInfo'), got something else.`,
- }),
- requestList: (value: Dictionary) => ({
- validator: ow.isValid(value, ow.object.hasKeys('fetchNextRequest', 'persistState')),
- message: (label: string) => `Expected argument '${label}' to be a RequestList, got something else.`,
- }),
- requestQueue: (value: Dictionary) => ({
- validator: ow.isValid(value, ow.object.hasKeys('fetchNextRequest', 'addRequest')),
- message: (label: string) => `Expected argument '${label}' to be a RequestQueue, got something else.`,
- }),
- browserPool: (value: Dictionary) => ({
- validator: ow.isValid(value, ow.object.hasKeys('newPage', 'closePage', 'extractPageState', 'injectPageState')),
- message: (label: string) =>
- `Expected argument '${label}' to implement the IBrowserPool interface (missing one of 'newPage', 'closePage', 'extractPageState', 'injectPageState'), got something else.`,
- }),
- sessionPool: (value: Dictionary) => ({
- validator: ow.isValid(value, ow.object.hasKeys('getSession')),
- message: (label: string) =>
- `Expected argument '${label}' to implement the ISessionPool interface (missing 'getSession'), got something else.`,
- }),
+ browserPage: schemas.objectWithKeys(
+ ['goto', 'evaluate', '$', 'on'],
+ 'Expected a Puppeteer Page, got something else.',
+ ),
+ proxyConfiguration: schemas.objectWithKeys(
+ ['newProxyInfo'],
+ "Expected an object implementing the IProxyConfiguration interface (missing 'newProxyInfo'), got something else.",
+ ),
+ requestList: schemas.objectWithKeys(
+ ['fetchNextRequest', 'persistState'],
+ 'Expected a RequestList, got something else.',
+ ),
+ requestQueue: schemas.objectWithKeys(
+ ['fetchNextRequest', 'addRequest'],
+ 'Expected a RequestQueue, got something else.',
+ ),
+ browserPool: schemas.objectWithKeys(
+ ['newPage', 'closePage', 'extractPageState', 'injectPageState'],
+ "Expected an object implementing the IBrowserPool interface (missing one of 'newPage', 'closePage', 'extractPageState', 'injectPageState'), got something else.",
+ ),
+ sessionPool: schemas.objectWithKeys(
+ ['getSession'],
+ "Expected an object implementing the ISessionPool interface (missing 'getSession'), got something else.",
+ ),
+ requestManager: schemas.objectWithKeys(
+ ['fetchNextRequest', 'addRequest', 'addRequestsBatched'],
+ "Expected an object implementing the IRequestManager interface (missing one of 'fetchNextRequest', 'addRequest', 'addRequestsBatched'), got something else.",
+ ),
+ storageBackend: schemas.objectWithKeys(
+ ['createDatasetBackend', 'createKeyValueStoreBackend', 'createRequestQueueBackend'],
+ "Expected an object implementing the StorageBackend interface (missing one of 'createDatasetBackend', 'createKeyValueStoreBackend', 'createRequestQueueBackend'), got something else.",
+ ),
+ logger: schemas.logger,
+ httpClient: schemas.httpClient,
};
diff --git a/packages/fs-storage/package.json b/packages/fs-storage/package.json
index 79142db4c..606a7e785 100644
--- a/packages/fs-storage/package.json
+++ b/packages/fs-storage/package.json
@@ -44,6 +44,7 @@
"dependencies": {
"@crawlee/fs-storage-native": "0.1.5-beta.18",
"@crawlee/types": "workspace:*",
- "@sapphire/shapeshift": "^4.0.0"
+ "@crawlee/utils": "workspace:*",
+ "zod": "catalog:"
}
}
diff --git a/packages/fs-storage/src/file-system-storage.ts b/packages/fs-storage/src/file-system-storage.ts
index d0af8e27a..40e1cdd3a 100644
--- a/packages/fs-storage/src/file-system-storage.ts
+++ b/packages/fs-storage/src/file-system-storage.ts
@@ -3,12 +3,19 @@ import { resolve } from 'node:path';
import type * as storage from '@crawlee/types';
import type { CrawleeLogger } from '@crawlee/types';
-import { s } from '@sapphire/shapeshift';
+import { parseArgument, schemas } from '@crawlee/utils/internal';
+import { z } from 'zod';
import { DatasetBackend } from './resource-clients/dataset.js';
import { KeyValueStoreBackend } from './resource-clients/key-value-store.js';
import { RequestQueueBackend } from './resource-clients/request-queue.js';
+const fileSystemStorageOptionsSchema = z.object({
+ localDataDirectory: z.string(),
+ requestQueueAccess: z.enum(['single', 'shared']).default('single'),
+ logger: schemas.logger.optional(),
+});
+
// The native package throws at load time on platforms without a published binary (e.g.
// linux musl), and `@crawlee/core` imports this module eagerly via its service locator.
// Load it lazily so merely importing `@crawlee/fs-storage` stays safe everywhere and the
@@ -75,15 +82,15 @@ export class FileSystemStorageBackend implements storage.StorageBackend {
readonly requestQueueBackendCache: RequestQueueBackend[] = [];
constructor(options: FileSystemStorageOptions) {
- s.object({
- localDataDirectory: s.string(),
- requestQueueAccess: s.enum(['single', 'shared']).optional(),
- }).parse(options);
+ const { logger, requestQueueAccess, localDataDirectory } = parseArgument(
+ options,
+ fileSystemStorageOptionsSchema,
+ );
- this.logger = options.logger;
- this.requestQueueAccess = options.requestQueueAccess ?? 'single';
+ this.logger = logger;
+ this.requestQueueAccess = requestQueueAccess;
- this.localDataDirectory = options.localDataDirectory;
+ this.localDataDirectory = localDataDirectory;
this.datasetsDirectory = resolve(this.localDataDirectory, 'datasets');
this.keyValueStoresDirectory = resolve(this.localDataDirectory, 'key_value_stores');
this.requestQueuesDirectory = resolve(this.localDataDirectory, 'request_queues');
diff --git a/packages/fs-storage/src/resource-clients/dataset.ts b/packages/fs-storage/src/resource-clients/dataset.ts
index b6cb62a75..d52fc81af 100644
--- a/packages/fs-storage/src/resource-clients/dataset.ts
+++ b/packages/fs-storage/src/resource-clients/dataset.ts
@@ -1,6 +1,6 @@
import type * as storage from '@crawlee/types';
import type { CrawleeLogger, Dictionary } from '@crawlee/types';
-import { s } from '@sapphire/shapeshift';
+import { parseArgument, schemas } from '@crawlee/utils/internal';
import type { FileSystemDatasetClient as NativeFileSystemDatasetBackend } from '@crawlee/fs-storage-native';
@@ -91,13 +91,7 @@ export class DatasetBackend<Data extends Dictionary = Dictionary>
);
}
- const { desc, limit, offset } = s
- .object({
- desc: s.boolean().optional(),
- limit: s.number().int().optional(),
- offset: s.number().int().optional(),
- })
- .parse(options);
+ const { desc, limit, offset } = parseArgument(options, schemas.datasetListItemsOptions);
const page = await this.#nativeBackend.getData(offset ?? 0, limit, desc ?? false, false);
diff --git a/packages/fs-storage/src/resource-clients/key-value-store.ts b/packages/fs-storage/src/resource-clients/key-value-store.ts
index ca5f293dd..c129c4675 100644
--- a/packages/fs-storage/src/resource-clients/key-value-store.ts
+++ b/packages/fs-storage/src/resource-clients/key-value-store.ts
@@ -2,7 +2,8 @@ import { Readable } from 'node:stream';
import type * as storage from '@crawlee/types';
import type { CrawleeLogger } from '@crawlee/types';
-import { s } from '@sapphire/shapeshift';
+import { parseArgument, schemas } from '@crawlee/utils/internal';
+import { z } from 'zod';
import type {
FileSystemKeyValueStoreClient as NativeFileSystemKeyValueStoreBackend,
@@ -29,6 +30,22 @@ const BARE_FILE_FALLBACKS: { extension: string; contentType: string }[] = [
const ALLOWED_BARE_FILES = ['INPUT'];
+const keySchema = z.string();
+
+const inputRecordShape = z.object({
+ key: z.string().min(1),
+ value: z.union([
+ z.string(),
+ z.instanceof(Buffer),
+ z.instanceof(ArrayBuffer),
+ schemas.typedArray,
+ // A stream is an object; this only checks it is a non-null, non-array object
+ // (the stream guard in `setValue` does the real check).
+ schemas.plainObject,
+ ]),
+ contentType: z.string().min(1).optional(),
+});
+
/**
* The out-of-band ("bare") files to surface from the native `listKeys`, derived from
* {@link ALLOWED_BARE_FILES} × {@link BARE_FILE_FALLBACKS}. Each native {@link ListBareFallback}
@@ -129,13 +146,7 @@ export class KeyValueStoreBackend extends CachedIdClient implements storage.KeyV
}
async listKeys(options: storage.KeyValueStoreListKeysOptions = {}): Promise<storage.KeyValueStoreListKeysResult> {
- const { prefix, exclusiveStartKey, limit } = s
- .object({
- prefix: s.string().optional(),
- exclusiveStartKey: s.string().optional(),
- limit: s.number().int().greaterThan(0).optional(),
- })
- .parse(options);
+ const { prefix, exclusiveStartKey, limit } = parseArgument(options, schemas.keyValueStoreListKeysOptions);
// Pass the bare-file fallbacks so out-of-band value files (e.g. a hand-placed `INPUT.json`)
// are enumerated alongside tracked records, under their actual on-disk name. The native reads
@@ -174,7 +185,7 @@ export class KeyValueStoreBackend extends CachedIdClient implements storage.KeyV
* @param key The key of the record to generate the public URL for.
*/
async getPublicUrl(key: string): Promise<string | undefined> {
- s.string().parse(key);
+ parseArgument(key, keySchema);
// The native `getPublicUrl` stats the encoded path but does not probe bare-file extensions,
// so we resolve the on-disk key first (handling e.g. `INPUT` -> `INPUT.json`) and normalize
@@ -193,12 +204,12 @@ export class KeyValueStoreBackend extends CachedIdClient implements storage.KeyV
* @returns `true` if the record exists, `false` otherwise.
*/
async recordExists(key: string): Promise<boolean> {
- s.string().parse(key);
+ parseArgument(key, keySchema);
return (await this.resolveExistingKey(key)) !== undefined;
}
async getValue(key: string): Promise<storage.KeyValueStoreRecord | undefined> {
- s.string().parse(key);
+ parseArgument(key, keySchema);
const fallbacks = this.bareFallbacksFor(key);
const record = fallbacks
@@ -221,19 +232,7 @@ export class KeyValueStoreBackend extends CachedIdClient implements storage.KeyV
// serialized it: non-bytes become a `string`, everything else is a `Buffer`/typed array or a
// stream. So we only accept those shapes here — there is no JSON inference or `String(value)`
// coercion left to do.
- s.object({
- key: s.string().lengthGreaterThan(0),
- value: s.union([
- s.string(),
- s.instance(Buffer),
- s.instance(ArrayBuffer),
- s.typedArray(),
- // A stream is an object; disabling validation makes shapeshift only check it is a
- // non-null, non-array object (the stream guard below does the real check).
- s.object({}).setValidationEnabled(false),
- ]),
- contentType: s.string().lengthGreaterThan(0).optional(),
- }).parse(record);
+ parseArgument(record, inputRecordShape);
const { key, value } = record;
// The frontend resolves the content type before it reaches the backend; this backend is a plain
@@ -261,7 +260,7 @@ export class KeyValueStoreBackend extends CachedIdClient implements storage.KeyV
}
async deleteValue(key: string): Promise<void> {
- s.string().parse(key);
+ parseArgument(key, keySchema);
await this.#nativeBackend.deleteValue(key);
}
diff --git a/packages/fs-storage/src/resource-clients/request-queue.ts b/packages/fs-storage/src/resource-clients/request-queue.ts
index 5e41b51ee..afcd97ca8 100644
--- a/packages/fs-storage/src/resource-clients/request-queue.ts
+++ b/packages/fs-storage/src/resource-clients/request-queue.ts
@@ -1,11 +1,14 @@
import type * as storage from '@crawlee/types';
import type { CrawleeLogger } from '@crawlee/types';
-import { s } from '@sapphire/shapeshift';
+import { parseArgument, schemas } from '@crawlee/utils/internal';
+import { z } from 'zod';
import type { FileSystemRequestQueueClient as NativeFileSystemRequestQueueBackend } from '@crawlee/fs-storage-native';
import { CachedIdClient } from './cached-id-client.js';
+const uniqueKeySchema = z.string();
+
/**
* Convert a request (either a Crawlee `Request` instance or a plain schema object) into a plain object
* whose properties are all enumerable.
@@ -22,24 +25,6 @@ function plainifyRequest(request: unknown): Record<string, unknown> {
return JSON.parse(JSON.stringify(request)) as Record<string, unknown>;
}
-const requestShape = s
- .object({
- id: s.string(),
- url: s.string().url({ allowedProtocols: ['http:', 'https:'] }),
- uniqueKey: s.string(),
- method: s.string().optional(),
- retryCount: s.number().int().optional(),
- handledAt: s.union([s.string(), s.date().valid()]).optional(),
- })
- .passthrough();
-
-const requestShapeWithoutId = requestShape.omit(['id']);
-const batchRequestShapeWithoutId = requestShapeWithoutId.array();
-
-const requestOptionsShape = s.object({
- forefront: s.boolean().optional(),
-});
-
export interface RequestQueueBackendOptions {
/** The user-facing storage name, or `undefined` for unnamed (alias / default) storages. */
name?: string;
@@ -106,8 +91,8 @@ export class RequestQueueBackend extends CachedIdClient implements storage.Reque
requests: storage.RequestSchema[],
options: storage.RequestQueueOperationOptions = {},
): Promise<storage.BatchAddRequestsResult> {
- batchRequestShapeWithoutId.parse(requests);
- requestOptionsShape.parse(options);
+ parseArgument(requests, schemas.storageRequestBatch);
+ parseArgument(options, schemas.requestQueueOperationOptions);
const response = await this.#nativeBackend.addBatchOfRequests(
requests.map((request) => plainifyRequest(request)),
@@ -124,7 +109,7 @@ export class RequestQueueBackend extends CachedIdClient implements storage.Reque
}
async getRequest(uniqueKey: string): Promise<storage.UpdateRequestSchema | undefined> {
- s.string().parse(uniqueKey);
+ parseArgument(uniqueKey, uniqueKeySchema);
// The native client tags requests with an internal `orderNo`; it's harmless to leak, so we
// hand the request back as-is rather than copying it just to drop one undeclared property.
// The native client already returns `undefined` for a missing request, matching this contract.
@@ -136,7 +121,7 @@ export class RequestQueueBackend extends CachedIdClient implements storage.Reque
}
async markRequestAsHandled(request: storage.UpdateRequestSchema): Promise<storage.QueueOperationInfo | undefined> {
- requestShape.parse(request);
+ parseArgument(request, schemas.storageRequest);
return (await this.#nativeBackend.markRequestAsHandled(plainifyRequest(request))) ?? undefined;
}
@@ -144,8 +129,8 @@ export class RequestQueueBackend extends CachedIdClient implements storage.Reque
request: storage.UpdateRequestSchema,
options: storage.RequestQueueOperationOptions = {},
): Promise<storage.QueueOperationInfo | undefined> {
- requestShape.parse(request);
- requestOptionsShape.parse(options);
+ parseArgument(request, schemas.storageRequest);
+ parseArgument(options, schemas.requestQueueOperationOptions);
return (
(await this.#nativeBackend.reclaimRequest(plainifyRequest(request), options.forefront ?? false)) ??
undefined
diff --git a/packages/http-crawler/package.json b/packages/http-crawler/package.json
index 0f82063d8..997139c35 100644
--- a/packages/http-crawler/package.json
+++ b/packages/http-crawler/package.json
@@ -59,8 +59,8 @@
"content-type": "^1.0.5",
"iconv-lite": "^0.7.2",
"mime-types": "^3.0.1",
- "ow": "^2.0.0",
"tslib": "^2.8.1",
- "type-fest": "^4.41.0"
+ "type-fest": "^4.41.0",
+ "zod": "catalog:"
}
}
diff --git a/packages/http-crawler/src/internals/http-crawler.ts b/packages/http-crawler/src/internals/http-crawler.ts
index bb54f6600..b5ae62a6c 100644
--- a/packages/http-crawler/src/internals/http-crawler.ts
+++ b/packages/http-crawler/src/internals/http-crawler.ts
@@ -26,15 +26,21 @@ import {
Router,
SessionError,
} from '@crawlee/basic';
-import { type LoadedRequest, RequestThrottledError, getCookiesFromResponse } from '@crawlee/core';
+import {
+ type LoadedRequest,
+ RequestThrottledError,
+ getCookiesFromResponse,
+ parseArgument,
+ schemas,
+} from '@crawlee/core';
import { ResponseWithUrl } from '@crawlee/http-client';
import type { Awaitable, Dictionary, ISession } from '@crawlee/types';
import { type CheerioRoot, RETRY_CSS_SELECTORS } from '@crawlee/utils/internal';
import type { RequestLike, ResponseLike } from 'content-type';
import contentTypeParser from 'content-type';
import iconv from 'iconv-lite';
-import ow from 'ow';
import type { JsonValue } from 'type-fest';
+import { z } from 'zod';
import { addTimeoutToPromise, storage, TimeoutError, tryCancel } from '@apify/timeout';
@@ -361,17 +367,19 @@ export class HttpCrawler<
protected static override optionsShape = {
...BasicCrawler.optionsShape,
- navigationTimeoutSecs: ow.optional.number,
- ignoreTlsErrors: ow.optional.boolean,
- additionalMimeTypes: ow.optional.array.ofType(ow.string),
- suggestResponseEncoding: ow.optional.string,
- forceResponseEncoding: ow.optional.string,
- saveResponseCookies: ow.optional.boolean,
+ navigationTimeoutSecs: schemas.anyNumber.default(30),
+ ignoreTlsErrors: z.boolean().default(true),
+ additionalMimeTypes: schemas.arrayOf(z.string(), 'strings').default(() => []),
+ suggestResponseEncoding: z.string().optional(),
+ forceResponseEncoding: z.string().optional(),
+ saveResponseCookies: z.boolean().default(true),
- preNavigationHooks: ow.optional.array,
- postNavigationHooks: ow.optional.array,
+ preNavigationHooks: schemas.anyArray.default(() => []),
+ postNavigationHooks: schemas.anyArray.default(() => []),
};
+ protected static override optionsSchema = z.strictObject(HttpCrawler.optionsShape);
+
/**
* All `HttpCrawlerOptions` parameters are passed via an options object.
*/
@@ -379,22 +387,20 @@ export class HttpCrawler<
options: HttpCrawlerOptions<Context, ContextExtension, ExtendedContext> &
RequireContextPipeline<InternalHttpCrawlingContext, Context> = {} as any,
) {
- ow(options, 'HttpCrawlerOptions', ow.object.exactShape(HttpCrawler.optionsShape));
-
const {
- navigationTimeoutSecs = 30,
- ignoreTlsErrors = true,
- additionalMimeTypes = [],
+ navigationTimeoutSecs,
+ ignoreTlsErrors,
+ additionalMimeTypes,
suggestResponseEncoding,
forceResponseEncoding,
- saveResponseCookies = true,
- preNavigationHooks = [],
- postNavigationHooks = [],
+ saveResponseCookies,
+ preNavigationHooks,
+ postNavigationHooks,
// BasicCrawler
contextPipelineBuilder,
...basicCrawlerOptions
- } = options;
+ } = parseArgument(options, HttpCrawler.optionsSchema, 'HttpCrawlerOptions');
super({
...basicCrawlerOptions,
diff --git a/packages/http-crawler/src/internals/utils.ts b/packages/http-crawler/src/internals/utils.ts
index e58422041..09a28a0a4 100644
--- a/packages/http-crawler/src/internals/utils.ts
+++ b/packages/http-crawler/src/internals/utils.ts
@@ -2,10 +2,12 @@ import { extname } from 'node:path';
import { Readable } from 'node:stream';
import type { HttpRequest, HttpRequestOptions } from '@crawlee/types';
-import { applySearchParams } from '@crawlee/utils/internal';
+import { applySearchParams, parseArgument } from '@crawlee/utils/internal';
import contentTypeParser from 'content-type';
import mime from 'mime-types';
-import ow, { ObjectPredicate } from 'ow';
+import { z } from 'zod';
+
+const responseWithUrlSchema = z.looseObject({ url: z.url(), headers: z.looseObject({}) });
/**
* Converts {@apilink HttpRequestOptions} to a {@apilink HttpRequest}.
@@ -76,13 +78,7 @@ export function extractCharsetFromHtmlBytes(bytes: Buffer): string | undefined {
* @param response HTTP response object
*/
export function parseContentTypeFromResponse(response: Response): { type: string; charset: BufferEncoding } {
- ow(
- response,
- ow.object.partialShape({
- url: ow.string.url,
- headers: new ObjectPredicate<Record<string, unknown>>(),
- }),
- );
+ parseArgument(response, responseWithUrlSchema);
const { url, headers } = response;
let parsedContentType;
diff --git a/packages/jsdom-crawler/package.json b/packages/jsdom-crawler/package.json
index 98294bac4..23f611f14 100644
--- a/packages/jsdom-crawler/package.json
+++ b/packages/jsdom-crawler/package.json
@@ -55,7 +55,7 @@
"@types/jsdom": "^21.1.7",
"cheerio": "^1.0.0",
"jsdom": "^26.1.0",
- "ow": "^2.0.0",
- "tslib": "^2.8.1"
+ "tslib": "^2.8.1",
+ "zod": "catalog:"
}
}
diff --git a/packages/jsdom-crawler/src/internals/jsdom-crawler.ts b/packages/jsdom-crawler/src/internals/jsdom-crawler.ts
index 52700f8d7..ddde49b92 100644
--- a/packages/jsdom-crawler/src/internals/jsdom-crawler.ts
+++ b/packages/jsdom-crawler/src/internals/jsdom-crawler.ts
@@ -19,6 +19,7 @@ import {
enqueueLinks,
HttpCrawler,
NavigationSkippedError,
+ parseArgument,
resolveBaseUrlForEnqueueLinksFiltering,
Router,
tryAbsoluteURL,
@@ -28,7 +29,7 @@ import { type CheerioRoot } from '@crawlee/utils/internal';
import { type RobotsTxtFile, sleep } from '@crawlee/utils';
import type { DOMWindow } from 'jsdom';
import { JSDOM, ResourceLoader, VirtualConsole } from 'jsdom';
-import ow from 'ow';
+import { z } from 'zod';
import { addTimeoutToPromise } from '@apify/timeout';
@@ -201,16 +202,23 @@ export class JSDOMCrawler<
> extends HttpCrawler<JSDOMCrawlingContext, ContextExtension, ExtendedContext, Routes> {
protected static override optionsShape = {
...HttpCrawler.optionsShape,
- runScripts: ow.optional.boolean,
- hideInternalConsole: ow.optional.boolean,
+ runScripts: z.boolean().optional(),
+ hideInternalConsole: z.boolean().optional(),
};
+ protected static override optionsSchema = z.strictObject(JSDOMCrawler.optionsShape);
+
#runScripts: boolean;
#hideInternalConsole: boolean;
#virtualConsole: VirtualConsole | null = null;
constructor(options: JSDOMCrawlerOptions<ContextExtension, ExtendedContext, any, any, Routes> = {}) {
- const { runScripts = false, hideInternalConsole = false, contextPipelineBuilder, ...httpOptions } = options;
+ const {
+ runScripts = false,
+ hideInternalConsole = false,
+ contextPipelineBuilder,
+ ...httpOptions
+ } = parseArgument(options, JSDOMCrawler.optionsSchema, 'JSDOMCrawlerOptions');
super({
...httpOptions,
diff --git a/packages/linkedom-crawler/package.json b/packages/linkedom-crawler/package.json
index 427fcfe5f..bda67145a 100644
--- a/packages/linkedom-crawler/package.json
+++ b/packages/linkedom-crawler/package.json
@@ -54,7 +54,6 @@
"@crawlee/utils": "workspace:*",
"cheerio": "^1.0.0",
"linkedom": "^0.18.10",
- "ow": "^2.0.0",
"tslib": "^2.8.1"
}
}
diff --git a/packages/playwright-crawler/package.json b/packages/playwright-crawler/package.json
index 2719d113b..b1332db20 100644
--- a/packages/playwright-crawler/package.json
+++ b/packages/playwright-crawler/package.json
@@ -60,11 +60,10 @@
"jquery": "^3.7.1",
"ml-logistic-regression": "^2.0.0",
"ml-matrix": "^6.12.1",
- "ow": "^2.0.0",
"string-comparison": "^1.3.0",
"tslib": "^2.8.1",
"type-fest": "^4.0.0",
- "zod": "^4.1.0"
+ "zod": "catalog:"
},
"peerDependencies": {
"idcac-playwright": "^0.2.0",
diff --git a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts
index 9f3e177b8..866d73391 100644
--- a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts
+++ b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts
@@ -30,6 +30,7 @@ import type {
import {
createStorageTransaction,
OwnedOrInjected,
+ parseArgument,
RequestHandlerError,
resolveBaseUrlForEnqueueLinksFiltering,
Router,
@@ -39,9 +40,9 @@ import type { BatchAddRequestsResult, Dictionary, Awaitable } from '@crawlee/typ
import { type CheerioRoot, extractUrlsFromCheerio } from '@crawlee/utils/internal';
import { type Cheerio } from 'cheerio';
import type { AnyNode } from 'domhandler';
-import ow from 'ow';
import type { Page } from 'playwright';
import type { SetRequired } from 'type-fest';
+import { z } from 'zod';
import { addTimeoutToPromise } from '@apify/timeout';
@@ -353,8 +354,13 @@ export class AdaptivePlaywrightCrawler<
...rest
} = options;
- // The user's value is replaced by `false` in the `super` call below — validate it separately.
- ow(transactionalStorage, 'transactionalStorage', BasicCrawler.optionsShape.transactionalStorage);
+ // The user's value is replaced by `false` in the `super` call below — validate it separately,
+ // wrapped in an object so the error still names the field.
+ parseArgument(
+ { transactionalStorage },
+ z.object({ transactionalStorage: BasicCrawler.optionsShape.transactionalStorage }),
+ 'AdaptivePlaywrightCrawlerOptions',
+ );
// Per-attempt buffering is load-bearing here: the handler runs up to twice per request and the
// losing attempt's writes must be discardable.
diff --git a/packages/playwright-crawler/src/internals/enqueue-links/click-elements.ts b/packages/playwright-crawler/src/internals/enqueue-links/click-elements.ts
index e2735c5e7..433a93147 100644
--- a/packages/playwright-crawler/src/internals/enqueue-links/click-elements.ts
+++ b/packages/playwright-crawler/src/internals/enqueue-links/click-elements.ts
@@ -13,18 +13,38 @@ import {
constructUrlPatternObjects,
createRequestOptions,
filterRequestOptionsByPatterns,
+ parseArgument,
+ urlPatternSchema,
Request as CrawleeRequest,
+ schemas,
serviceLocator,
} from '@crawlee/browser';
import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
-import ow from 'ow';
import type { Frame, Page, Request, Route } from 'playwright';
+import { z } from 'zod';
const STARTING_Z_INDEX = 2147400000;
const getLog = () => serviceLocator.getChildLog('Playwright Click Elements');
type ClickOptions = Parameters<Page['click']>[1];
+const enqueueLinksByClickingElementsOptionsSchema = z.strictObject({
+ page: schemas.objectWithKeys(['goto', 'evaluate']),
+ requestManager: schemas.objectWithKeys(['fetchNextRequest', 'addRequestsBatched']),
+ selector: z.string(),
+ userData: schemas.anyObject.optional(),
+ clickOptions: schemas.anyObject.optional(),
+ include: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
+ exclude: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
+ transformRequestFunction: schemas.anyFunction.optional(),
+ waitForPageIdleSecs: schemas.anyNumber.default(1),
+ maxWaitForPageIdleSecs: schemas.anyNumber.default(5),
+ label: z.string().optional(),
+ forefront: z.boolean().optional(),
+ skipNavigation: z.boolean().optional(),
+ onSkippedRequest: schemas.anyFunction.optional(),
+});
+
export interface EnqueueLinksByClickingElementsOptions {
/**
* Playwright [`Page`](https://playwright.dev/docs/api/class-page) object.
@@ -195,26 +215,10 @@ export interface EnqueueLinksByClickingElementsOptions {
export async function enqueueLinksByClickingElements(
options: EnqueueLinksByClickingElementsOptions,
): Promise<BatchAddRequestsResult> {
- const urlPatternValidator = ow.any(ow.string, ow.regExp, ow.object.hasKeys('glob'), ow.object.hasKeys('regexp'));
-
- ow(
+ const parsedOptions = parseArgument(
options,
- ow.object.exactShape({
- page: ow.object.hasKeys('goto', 'evaluate'),
- requestManager: ow.object.hasKeys('fetchNextRequest', 'addRequestsBatched'),
- selector: ow.string,
- userData: ow.optional.object,
- clickOptions: ow.optional.object,
- include: ow.optional.array.ofType(urlPatternValidator),
- exclude: ow.optional.array.ofType(urlPatternValidator),
- transformRequestFunction: ow.optional.function,
- waitForPageIdleSecs: ow.optional.number,
- maxWaitForPageIdleSecs: ow.optional.number,
- label: ow.optional.string,
- forefront: ow.optional.boolean,
- skipNavigation: ow.optional.boolean,
- onSkippedRequest: ow.optional.function,
- }),
+ enqueueLinksByClickingElementsOptionsSchema,
+ 'EnqueueLinksByClickingElementsOptions',
);
const {
@@ -225,11 +229,11 @@ export async function enqueueLinksByClickingElements(
include,
exclude,
transformRequestFunction,
- waitForPageIdleSecs = 1,
- maxWaitForPageIdleSecs = 5,
+ waitForPageIdleSecs,
+ maxWaitForPageIdleSecs,
forefront,
onSkippedRequest,
- } = options;
+ } = parsedOptions;
const waitForPageIdleMillis = waitForPageIdleSecs * 1000;
const maxWaitForPageIdleMillis = maxWaitForPageIdleSecs * 1000;
@@ -244,7 +248,7 @@ export async function enqueueLinksByClickingElements(
maxWaitForPageIdleMillis,
clickOptions,
});
- const requestOptions = createRequestOptions(interceptedRequests, options);
+ const requestOptions = createRequestOptions(interceptedRequests, parsedOptions);
const skippedByFilters: string[] = [];
let filteredOptions = filterRequestOptionsByPatterns(
requestOptions,
diff --git a/packages/playwright-crawler/src/internals/playwright-crawler.ts b/packages/playwright-crawler/src/internals/playwright-crawler.ts
index cacc5bad2..d7b83be57 100644
--- a/packages/playwright-crawler/src/internals/playwright-crawler.ts
+++ b/packages/playwright-crawler/src/internals/playwright-crawler.ts
@@ -9,11 +9,11 @@ import type {
RouteSchemas,
RoutesFromSchemas,
} from '@crawlee/browser';
-import { BrowserCrawler, RequestState, Router, serviceLocator } from '@crawlee/browser';
+import { BrowserCrawler, parseArgument, RequestState, Router, schemas, serviceLocator } from '@crawlee/browser';
import type { BrowserPoolOptions, PlaywrightPlugin } from '@crawlee/browser-pool';
import type { Dictionary } from '@crawlee/types';
-import ow from 'ow';
import type { Download, LaunchOptions, Page, Response } from 'playwright';
+import { z } from 'zod';
import type { EnqueueLinksByClickingElementsOptions } from './enqueue-links/click-elements.js';
import type { PlaywrightLaunchContext } from './playwright-launcher.js';
@@ -211,22 +211,22 @@ export class PlaywrightCrawler<
> {
protected static override optionsShape = {
...BrowserCrawler.optionsShape,
- browserPoolOptions: ow.optional.object,
- launcher: ow.optional.object,
- ignoreIframes: ow.optional.boolean,
- ignoreShadowRoots: ow.optional.boolean,
+ browserPoolOptions: schemas.anyObject.optional(),
+ launcher: schemas.anyObject.optional(),
};
+ protected static override optionsSchema = z.strictObject(PlaywrightCrawler.optionsShape);
+
/**
* All `PlaywrightCrawler` parameters are passed via an options object.
*/
constructor(options: PlaywrightCrawlerOptions<ContextExtension, ExtendedContext, Routes> = {}) {
- ow(options, 'PlaywrightCrawlerOptions', ow.object.exactShape(PlaywrightCrawler.optionsShape));
+ const parsedOptions = parseArgument(options, PlaywrightCrawler.optionsSchema, 'PlaywrightCrawlerOptions');
- const { launchContext = {}, headless, contextPipelineBuilder, ...browserCrawlerOptions } = options;
+ const { launchContext, headless, contextPipelineBuilder, ...browserCrawlerOptions } = parsedOptions;
const browserPoolOptions = {
- ...options.browserPoolOptions,
+ ...parsedOptions.browserPoolOptions,
} as BrowserPoolOptions;
if (launchContext.proxyUrl) {
@@ -247,7 +247,7 @@ export class PlaywrightCrawler<
launchContext.launchOptions.headless = headless as boolean;
}
- const playwrightLauncher = new PlaywrightLauncher(launchContext, options.configuration);
+ const playwrightLauncher = new PlaywrightLauncher(launchContext, parsedOptions.configuration);
browserPoolOptions.browserPlugins = [playwrightLauncher.createBrowserPlugin()];
diff --git a/packages/playwright-crawler/src/internals/playwright-launcher.ts b/packages/playwright-crawler/src/internals/playwright-launcher.ts
index 92c91aae4..cbb279ded 100644
--- a/packages/playwright-crawler/src/internals/playwright-launcher.ts
+++ b/packages/playwright-crawler/src/internals/playwright-launcher.ts
@@ -1,8 +1,8 @@
import type { BrowserLaunchContext } from '@crawlee/browser';
-import { BrowserLauncher, Configuration } from '@crawlee/browser';
+import { BrowserLauncher, Configuration, parseArgument, schemas } from '@crawlee/browser';
import { PlaywrightPlugin } from '@crawlee/browser-pool';
-import ow from 'ow';
import type { Browser, BrowserType, LaunchOptions } from 'playwright';
+import { z } from 'zod';
/**
* Apify extends the launch options of Playwright.
@@ -79,10 +79,13 @@ export interface PlaywrightLaunchContext extends BrowserLaunchContext<LaunchOpti
export class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin> {
protected static override optionsShape = {
...BrowserLauncher.optionsShape,
- launcher: ow.optional.object,
- launchContextOptions: ow.optional.object,
+ // Passthrough schemas — the launcher module object must keep its prototype through parsing.
+ launcher: schemas.anyObject.optional(),
+ launchContextOptions: schemas.anyObject.optional(),
};
+ protected static override optionsSchema = z.strictObject(PlaywrightLauncher.optionsShape);
+
/**
* All `PlaywrightLauncher` parameters are passed via this launchContext object.
*/
@@ -90,23 +93,23 @@ export class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin> {
launchContext: PlaywrightLaunchContext = {},
override readonly configuration = Configuration.getGlobalConfiguration(),
) {
- ow(launchContext, 'PlaywrightLauncherOptions', ow.object.exactShape(PlaywrightLauncher.optionsShape));
+ const parsedContext = parseArgument(launchContext, PlaywrightLauncher.optionsSchema, 'PlaywrightLaunchContext');
const {
launcher = BrowserLauncher.requireLauncherOrThrow<typeof import('playwright')>(
'playwright',
'apify/actor-node-playwright-*',
).chromium,
- } = launchContext;
+ } = parsedContext;
- const { launchOptions = {}, ...rest } = launchContext;
+ const { launchOptions = {}, ...rest } = parsedContext;
super(
{
...rest,
launchOptions: {
...launchOptions,
- executablePath: getDefaultExecutablePath(launchContext, configuration),
+ executablePath: getDefaultExecutablePath(parsedContext, configuration),
},
launcher,
},
diff --git a/packages/playwright-crawler/src/internals/utils/playwright-utils.ts b/packages/playwright-crawler/src/internals/utils/playwright-utils.ts
index 9e80d3ab1..5da70f3c2 100644
--- a/packages/playwright-crawler/src/internals/utils/playwright-utils.ts
+++ b/packages/playwright-crawler/src/internals/utils/playwright-utils.ts
@@ -22,12 +22,21 @@ import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import vm from 'node:vm';
-import { Configuration, KeyValueStore, type Request, serviceLocator, SessionError, validators } from '@crawlee/browser';
+import {
+ Configuration,
+ KeyValueStore,
+ parseArgument,
+ type Request,
+ schemas,
+ serviceLocator,
+ SessionError,
+ validators,
+} from '@crawlee/browser';
import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
import { type CheerioRoot } from '@crawlee/utils/internal';
import { expandShadowRoots, sleep } from '@crawlee/utils';
-import ow from 'ow';
import type { Download, Page, Response, Route } from 'playwright';
+import { z } from 'zod';
import { LruCache } from '@apify/datastructures';
@@ -43,6 +52,37 @@ const jqueryPath = require.resolve('jquery');
const MAX_INJECT_FILE_CACHE_SIZE = 10;
const DEFAULT_BLOCK_REQUEST_URL_PATTERNS = ['.css', '.jpg', '.jpeg', '.png', '.svg', '.gif', '.woff', '.pdf', '.zip'];
+const filePathSchema = z.string();
+const injectFileOptionsSchema = z.strictObject({
+ surviveNavigations: z.boolean().optional(),
+});
+const gotoExtendedRequestSchema = z.looseObject({
+ url: z.url(),
+ method: z.string().optional(),
+ headers: schemas.anyObject.optional(),
+ payload: z.union([z.string(), z.instanceof(Uint8Array)]).optional(),
+});
+const blockRequestsOptionsSchema = z.strictObject({
+ urlPatterns: schemas.arrayOf(z.string(), 'strings').default(DEFAULT_BLOCK_REQUEST_URL_PATTERNS),
+ extraUrlPatterns: schemas.arrayOf(z.string(), 'strings').default(() => []),
+});
+const infiniteScrollOptionsSchema = z.strictObject({
+ timeoutSecs: schemas.anyNumber.default(0),
+ maxScrollHeight: schemas.anyNumber.default(0),
+ waitForSecs: schemas.anyNumber.default(4),
+ scrollDownAndUp: z.boolean().default(false),
+ buttonSelector: z.string().optional(),
+ stopScrollCallback: schemas.anyFunction.optional(),
+});
+const saveSnapshotOptionsSchema = z.strictObject({
+ key: z.string().min(1).default('SNAPSHOT'),
+ screenshotQuality: schemas.anyNumber.default(50),
+ saveScreenshot: z.boolean().default(true),
+ saveHtml: z.boolean().default(true),
+ keyValueStoreName: z.string().optional(),
+ configuration: schemas.anyObject.optional(),
+});
+
export interface InjectFileOptions {
/**
* Enables the injected script to survive page navigations and reloads without need to be re-injected manually.
@@ -84,14 +124,9 @@ const injectedFilesCache = new LruCache({ maxLength: MAX_INJECT_FILE_CACHE_SIZE
* @param [options]
*/
export async function injectFile(page: Page, filePath: string, options: InjectFileOptions = {}): Promise<unknown> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(filePath, ow.string);
- ow(
- options,
- ow.object.exactShape({
- surviveNavigations: ow.optional.boolean,
- }),
- );
+ parseArgument(page, validators.browserPage);
+ parseArgument(filePath, filePathSchema);
+ const { surviveNavigations } = parseArgument(options, injectFileOptionsSchema);
let contents = injectedFilesCache.get(filePath);
if (!contents) {
@@ -100,7 +135,7 @@ export async function injectFile(page: Page, filePath: string, options: InjectFi
}
const evalP = page.evaluate(contents);
- if (options.surviveNavigations) {
+ if (surviveNavigations) {
page.on('framenavigated', async () =>
page
.evaluate(contents)
@@ -138,7 +173,7 @@ export async function injectFile(page: Page, filePath: string, options: InjectFi
* @param [options.surviveNavigations] Opt-out option to disable the JQuery reinjection after navigation.
*/
export async function injectJQuery(page: Page, options?: { surviveNavigations?: boolean }): Promise<unknown> {
- ow(page, ow.object.validate(validators.browserPage));
+ parseArgument(page, validators.browserPage);
return injectFile(page, jqueryPath, { surviveNavigations: options?.surviveNavigations ?? true });
}
@@ -182,17 +217,9 @@ export async function gotoExtended(
request: Request,
gotoOptions: DirectNavigationOptions = {},
): Promise<Response | null> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(
- request,
- ow.object.partialShape({
- url: ow.string.url,
- method: ow.optional.string,
- headers: ow.optional.object,
- payload: ow.optional.any(ow.string, ow.uint8Array),
- }),
- );
- ow(gotoOptions, ow.object);
+ parseArgument(page, validators.browserPage);
+ parseArgument(request, gotoExtendedRequestSchema);
+ parseArgument(gotoOptions, schemas.anyObject);
const { url, method, headers, payload } = request;
const isEmpty = (o?: object) => !o || Object.keys(o).length === 0;
@@ -282,16 +309,8 @@ export async function gotoExtended(
* @param [options]
*/
export async function blockRequests(page: Page, options: BlockRequestsOptions = {}): Promise<void> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(
- options,
- ow.object.exactShape({
- urlPatterns: ow.optional.array.ofType(ow.string),
- extraUrlPatterns: ow.optional.array.ofType(ow.string),
- }),
- );
-
- const { urlPatterns = DEFAULT_BLOCK_REQUEST_URL_PATTERNS, extraUrlPatterns = [] } = options;
+ parseArgument(page, validators.browserPage);
+ const { urlPatterns, extraUrlPatterns } = parseArgument(options, blockRequestsOptionsSchema);
const patternsToBlock = [...urlPatterns, ...extraUrlPatterns];
@@ -397,27 +416,9 @@ export interface InfiniteScrollOptions {
* @param [options]
*/
export async function infiniteScroll(page: Page, options: InfiniteScrollOptions = {}): Promise<void> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(
- options,
- ow.object.exactShape({
- timeoutSecs: ow.optional.number,
- maxScrollHeight: ow.optional.number,
- waitForSecs: ow.optional.number,
- scrollDownAndUp: ow.optional.boolean,
- buttonSelector: ow.optional.string,
- stopScrollCallback: ow.optional.function,
- }),
- );
-
- const {
- timeoutSecs = 0,
- maxScrollHeight = 0,
- waitForSecs = 4,
- scrollDownAndUp = false,
- buttonSelector,
- stopScrollCallback,
- } = options;
+ parseArgument(page, validators.browserPage);
+ const { timeoutSecs, maxScrollHeight, waitForSecs, scrollDownAndUp, buttonSelector, stopScrollCallback } =
+ parseArgument(options, infiniteScrollOptionsSchema);
let finished;
const startTime = Date.now();
@@ -540,28 +541,12 @@ export interface SaveSnapshotOptions {
* @param [options]
*/
export async function saveSnapshot(page: Page, options: SaveSnapshotOptions = {}): Promise<void> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(
+ parseArgument(page, validators.browserPage);
+ const { key, screenshotQuality, saveScreenshot, saveHtml, keyValueStoreName, configuration } = parseArgument(
options,
- ow.object.exactShape({
- key: ow.optional.string.nonEmpty,
- screenshotQuality: ow.optional.number,
- saveScreenshot: ow.optional.boolean,
- saveHtml: ow.optional.boolean,
- keyValueStoreName: ow.optional.string,
- configuration: ow.optional.object,
- }),
+ saveSnapshotOptionsSchema,
);
- const {
- key = 'SNAPSHOT',
- screenshotQuality = 50,
- saveScreenshot = true,
- saveHtml = true,
- keyValueStoreName,
- configuration,
- } = options;
-
try {
const store = await KeyValueStore.open(keyValueStoreName ? { name: keyValueStoreName } : null, {
configuration: configuration ?? Configuration.getGlobalConfiguration(),
@@ -605,7 +590,7 @@ export async function parseWithCheerio(
ignoreShadowRoots = false,
ignoreIframes = false,
): Promise<CheerioRoot> {
- ow(page, ow.object.validate(validators.browserPage));
+ parseArgument(page, validators.browserPage);
const html = ignoreShadowRoots
? null
@@ -678,7 +663,7 @@ ${error.message}
}
export async function closeCookieModals(page: Page): Promise<void> {
- ow(page, ow.object.validate(validators.browserPage));
+ parseArgument(page, validators.browserPage);
const idcac = await getIdcacPlaywright();
if (idcac?.getInjectableScript()) {
diff --git a/packages/puppeteer-crawler/package.json b/packages/puppeteer-crawler/package.json
index 35881016f..f0be0461a 100644
--- a/packages/puppeteer-crawler/package.json
+++ b/packages/puppeteer-crawler/package.json
@@ -56,8 +56,8 @@
"cheerio": "^1.0.0",
"devtools-protocol": "*",
"jquery": "^3.7.1",
- "ow": "^2.0.0",
- "tslib": "^2.8.1"
+ "tslib": "^2.8.1",
+ "zod": "catalog:"
},
"peerDependencies": {
"idcac-playwright": "^0.2.0",
diff --git a/packages/puppeteer-crawler/src/internals/enqueue-links/click-elements.ts b/packages/puppeteer-crawler/src/internals/enqueue-links/click-elements.ts
index 9d58cb99c..4442e621f 100644
--- a/packages/puppeteer-crawler/src/internals/enqueue-links/click-elements.ts
+++ b/packages/puppeteer-crawler/src/internals/enqueue-links/click-elements.ts
@@ -13,19 +13,39 @@ import {
constructUrlPatternObjects,
createRequestOptions,
filterRequestOptionsByPatterns,
+ parseArgument,
+ urlPatternSchema,
Request,
+ schemas,
serviceLocator,
} from '@crawlee/browser';
import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
-import ow from 'ow';
// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { ClickOptions, Frame, HTTPRequest as PuppeteerRequest, Page, Target } from 'puppeteer';
+import { z } from 'zod';
import { addInterceptRequestHandler, removeInterceptRequestHandler } from '../utils/puppeteer_request_interception.js';
const STARTING_Z_INDEX = 2147400000;
const getLog = () => serviceLocator.getChildLog('Puppeteer Click Elements');
+const enqueueLinksByClickingElementsOptionsSchema = z.strictObject({
+ page: schemas.objectWithKeys(['goto', 'evaluate']),
+ requestManager: schemas.objectWithKeys(['fetchNextRequest', 'addRequestsBatched']),
+ selector: z.string(),
+ userData: schemas.anyObject.optional(),
+ clickOptions: schemas.anyObject.optional(),
+ include: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
+ exclude: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
+ transformRequestFunction: schemas.anyFunction.optional(),
+ waitForPageIdleSecs: schemas.anyNumber.default(1),
+ maxWaitForPageIdleSecs: schemas.anyNumber.default(5),
+ label: z.string().optional(),
+ forefront: z.boolean().optional(),
+ skipNavigation: z.boolean().optional(),
+ onSkippedRequest: schemas.anyFunction.optional(),
+});
+
export interface EnqueueLinksByClickingElementsOptions {
/**
* Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
@@ -196,26 +216,10 @@ export interface EnqueueLinksByClickingElementsOptions {
export async function enqueueLinksByClickingElements(
options: EnqueueLinksByClickingElementsOptions,
): Promise<BatchAddRequestsResult> {
- const urlPatternValidator = ow.any(ow.string, ow.regExp, ow.object.hasKeys('glob'), ow.object.hasKeys('regexp'));
-
- ow(
+ const parsedOptions = parseArgument(
options,
- ow.object.exactShape({
- page: ow.object.hasKeys('goto', 'evaluate'),
- requestManager: ow.object.hasKeys('fetchNextRequest', 'addRequestsBatched'),
- selector: ow.string,
- userData: ow.optional.object,
- clickOptions: ow.optional.object,
- include: ow.optional.array.ofType(urlPatternValidator),
- exclude: ow.optional.array.ofType(urlPatternValidator),
- transformRequestFunction: ow.optional.function,
- waitForPageIdleSecs: ow.optional.number,
- maxWaitForPageIdleSecs: ow.optional.number,
- label: ow.optional.string,
- forefront: ow.optional.boolean,
- skipNavigation: ow.optional.boolean,
- onSkippedRequest: ow.optional.function,
- }),
+ enqueueLinksByClickingElementsOptionsSchema,
+ 'EnqueueLinksByClickingElementsOptions',
);
const {
@@ -226,11 +230,11 @@ export async function enqueueLinksByClickingElements(
include,
exclude,
transformRequestFunction,
- waitForPageIdleSecs = 1,
- maxWaitForPageIdleSecs = 5,
+ waitForPageIdleSecs,
+ maxWaitForPageIdleSecs,
forefront,
onSkippedRequest,
- } = options;
+ } = parsedOptions;
const waitForPageIdleMillis = waitForPageIdleSecs * 1000;
const maxWaitForPageIdleMillis = maxWaitForPageIdleSecs * 1000;
@@ -245,7 +249,7 @@ export async function enqueueLinksByClickingElements(
maxWaitForPageIdleMillis,
clickOptions,
});
- const requestOptions = createRequestOptions(interceptedRequests, options);
+ const requestOptions = createRequestOptions(interceptedRequests, parsedOptions);
const skippedByFilters: string[] = [];
let filteredOptions = filterRequestOptionsByPatterns(
requestOptions,
diff --git a/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts b/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts
index 45a898c58..fe8f3ff73 100644
--- a/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts
+++ b/packages/puppeteer-crawler/src/internals/puppeteer-crawler.ts
@@ -10,11 +10,11 @@ import type {
} from '@crawlee/browser';
import { BrowserCrawler, RequestState, Router } from '@crawlee/browser';
import type { BrowserPoolOptions, PuppeteerPlugin } from '@crawlee/browser-pool';
-import { serviceLocator } from '@crawlee/core';
+import { parseArgument, schemas, serviceLocator } from '@crawlee/core';
import type { Dictionary } from '@crawlee/types';
-import ow from 'ow';
// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { HTTPResponse, LaunchOptions, Page } from 'puppeteer';
+import { z } from 'zod';
import type { EnqueueLinksByClickingElementsOptions } from './enqueue-links/click-elements.js';
import type { PuppeteerLaunchContext } from './puppeteer-launcher.js';
@@ -188,25 +188,22 @@ export class PuppeteerCrawler<
> {
protected static override optionsShape = {
...BrowserCrawler.optionsShape,
- browserPoolOptions: ow.optional.object,
+ browserPoolOptions: schemas.anyObject.optional(),
};
+ protected static override optionsSchema = z.strictObject(PuppeteerCrawler.optionsShape);
+
/**
* All `PuppeteerCrawler` parameters are passed via an options object.
*/
constructor(options: PuppeteerCrawlerOptions<ContextExtension, ExtendedContext, Routes> = {}) {
- ow(options, 'PuppeteerCrawlerOptions', ow.object.exactShape(PuppeteerCrawler.optionsShape));
+ const parsedOptions = parseArgument(options, PuppeteerCrawler.optionsSchema, 'PuppeteerCrawlerOptions');
- const {
- launchContext = {},
- headless,
- proxyConfiguration,
- contextPipelineBuilder,
- ...browserCrawlerOptions
- } = options;
+ const { launchContext, headless, proxyConfiguration, contextPipelineBuilder, ...browserCrawlerOptions } =
+ parsedOptions;
const browserPoolOptions = {
- ...options.browserPoolOptions,
+ ...parsedOptions.browserPoolOptions,
} as BrowserPoolOptions;
if (launchContext.proxyUrl) {
@@ -227,7 +224,7 @@ export class PuppeteerCrawler<
launchContext.launchOptions.headless = headless as boolean;
}
- const puppeteerLauncher = new PuppeteerLauncher(launchContext, options.configuration);
+ const puppeteerLauncher = new PuppeteerLauncher(launchContext, parsedOptions.configuration);
browserPoolOptions.browserPlugins = [puppeteerLauncher.createBrowserPlugin()];
diff --git a/packages/puppeteer-crawler/src/internals/puppeteer-launcher.ts b/packages/puppeteer-crawler/src/internals/puppeteer-launcher.ts
index ac36912b5..4e1c7e874 100644
--- a/packages/puppeteer-crawler/src/internals/puppeteer-launcher.ts
+++ b/packages/puppeteer-crawler/src/internals/puppeteer-launcher.ts
@@ -1,9 +1,9 @@
import type { BrowserLaunchContext } from '@crawlee/browser';
-import { BrowserLauncher, Configuration } from '@crawlee/browser';
+import { BrowserLauncher, Configuration, parseArgument, schemas } from '@crawlee/browser';
import { PuppeteerPlugin } from '@crawlee/browser-pool';
-import ow from 'ow';
// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { Browser } from 'puppeteer';
+import { z } from 'zod';
/**
* Apify extends the launch options of Puppeteer.
@@ -75,9 +75,11 @@ export interface PuppeteerLaunchContext extends BrowserLaunchContext<PuppeteerPl
export class PuppeteerLauncher extends BrowserLauncher<PuppeteerPlugin, unknown> {
protected static override optionsShape = {
...BrowserLauncher.optionsShape,
- launcher: ow.optional.object,
+ launcher: schemas.anyObject.optional(),
};
+ protected static override optionsSchema = z.strictObject(PuppeteerLauncher.optionsShape);
+
/**
* All `PuppeteerLauncher` parameters are passed via an launchContext object.
*/
@@ -85,18 +87,16 @@ export class PuppeteerLauncher extends BrowserLauncher<PuppeteerPlugin, unknown>
launchContext: PuppeteerLaunchContext = {},
override readonly configuration = Configuration.getGlobalConfiguration(),
) {
- ow(launchContext, 'PuppeteerLauncher', ow.object.exactShape(PuppeteerLauncher.optionsShape));
-
const {
launcher = BrowserLauncher.requireLauncherOrThrow('puppeteer', 'apify/actor-node-puppeteer-chrome'),
...browserLauncherOptions
- } = launchContext;
+ } = parseArgument(launchContext, PuppeteerLauncher.optionsSchema, 'PuppeteerLaunchContext');
super(
{
...browserLauncherOptions,
launcher,
- },
+ } as BrowserLaunchContext<Partial<Parameters<PuppeteerPlugin['launch']>[0]>, unknown>,
configuration,
);
diff --git a/packages/puppeteer-crawler/src/internals/utils/puppeteer_request_interception.ts b/packages/puppeteer-crawler/src/internals/utils/puppeteer_request_interception.ts
index 37b6ae899..1d3b6a064 100644
--- a/packages/puppeteer-crawler/src/internals/utils/puppeteer_request_interception.ts
+++ b/packages/puppeteer-crawler/src/internals/utils/puppeteer_request_interception.ts
@@ -1,13 +1,14 @@
import { EventEmitter } from 'node:events';
-import { serviceLocator } from '@crawlee/browser';
+import { parseArgument, schemas, serviceLocator } from '@crawlee/browser';
import type { Dictionary } from '@crawlee/types';
-import ow from 'ow';
// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { HTTPRequest, HTTPRequest as PuppeteerRequest, Page } from 'puppeteer';
export type InterceptHandler = (request: PuppeteerRequest) => unknown;
+const pageSchema = schemas.objectWithKeys(['goto', 'evaluate']);
+
// We use weak maps here so that the content gets discarded after page gets closed.
const pageInterceptRequestHandlersMap: WeakMap<Page, InterceptHandler[]> = new WeakMap(); // Maps page to an array of request interception handlers.
const pageInterceptRequestMasterHandlerMap = new WeakMap(); // Maps page to master request interception handler.
@@ -158,8 +159,8 @@ async function handleRequest(request: PuppeteerRequest, interceptRequestHandlers
* @param handler Request interception handler.
*/
export async function addInterceptRequestHandler(page: Page, handler: InterceptHandler): Promise<void> {
- ow(page, ow.object.hasKeys('goto', 'evaluate'));
- ow(handler, ow.function);
+ parseArgument(page, pageSchema);
+ parseArgument(handler, schemas.anyFunction);
if (!pageInterceptRequestHandlersMap.has(page)) {
pageInterceptRequestHandlersMap.set(page, []);
@@ -201,8 +202,8 @@ export async function addInterceptRequestHandler(page: Page, handler: InterceptH
* @param handler Request interception handler.
*/
export async function removeInterceptRequestHandler(page: Page, handler: InterceptHandler): Promise<void> {
- ow(page, ow.object.hasKeys('goto', 'evaluate'));
- ow(handler, ow.function);
+ parseArgument(page, pageSchema);
+ parseArgument(handler, schemas.anyFunction);
const handlersArray = pageInterceptRequestHandlersMap.get(page)!.filter((item) => item !== handler);
diff --git a/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts b/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts
index 1a68cebdb..753bac4be 100644
--- a/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts
+++ b/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts
@@ -23,14 +23,14 @@ import { createRequire } from 'node:module';
import vm from 'node:vm';
import type { Request } from '@crawlee/browser';
-import { Configuration, KeyValueStore, serviceLocator, validators } from '@crawlee/browser';
+import { Configuration, KeyValueStore, parseArgument, schemas, serviceLocator, validators } from '@crawlee/browser';
import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
import { type CheerioRoot } from '@crawlee/utils/internal';
import { expandShadowRoots, sleep } from '@crawlee/utils';
import type { ProtocolMapping } from 'devtools-protocol/types/protocol-mapping.js';
-import ow from 'ow';
// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { HTTPRequest as PuppeteerRequest, HTTPResponse, Page, ResponseForRequest } from 'puppeteer';
+import { z } from 'zod';
import { LruCache } from '@apify/datastructures';
@@ -45,6 +45,38 @@ const jqueryPath = require.resolve('jquery');
const MAX_INJECT_FILE_CACHE_SIZE = 10;
const DEFAULT_BLOCK_REQUEST_URL_PATTERNS = ['.css', '.jpg', '.jpeg', '.png', '.svg', '.gif', '.woff', '.pdf', '.zip'];
+const filePathSchema = z.string();
+const injectFileOptionsSchema = z.strictObject({
+ surviveNavigations: z.boolean().optional(),
+});
+const responseUrlRulesSchema = schemas.arrayOf(z.union([z.string(), z.instanceof(RegExp)]), 'strings or RegExps');
+const gotoExtendedRequestSchema = z.looseObject({
+ url: z.url(),
+ method: z.string().optional(),
+ headers: schemas.anyObject.optional(),
+ payload: z.union([z.string(), z.instanceof(Uint8Array)]).optional(),
+});
+const blockRequestsOptionsSchema = z.strictObject({
+ urlPatterns: schemas.arrayOf(z.string(), 'strings').default(DEFAULT_BLOCK_REQUEST_URL_PATTERNS),
+ extraUrlPatterns: schemas.arrayOf(z.string(), 'strings').default(() => []),
+});
+const infiniteScrollOptionsSchema = z.strictObject({
+ timeoutSecs: schemas.anyNumber.default(0),
+ maxScrollHeight: schemas.anyNumber.default(0),
+ waitForSecs: schemas.anyNumber.default(4),
+ scrollDownAndUp: z.boolean().default(false),
+ buttonSelector: z.string().optional(),
+ stopScrollCallback: schemas.anyFunction.optional(),
+});
+const saveSnapshotOptionsSchema = z.strictObject({
+ key: z.string().min(1).default('SNAPSHOT'),
+ screenshotQuality: schemas.anyNumber.default(50),
+ saveScreenshot: z.boolean().default(true),
+ saveHtml: z.boolean().default(true),
+ keyValueStoreName: z.string().optional(),
+ configuration: schemas.anyObject.optional(),
+});
+
const getLog = () => serviceLocator.getChildLog('Puppeteer Utils');
export interface DirectNavigationOptions {
@@ -120,14 +152,9 @@ const injectedFilesCache = new LruCache({ maxLength: MAX_INJECT_FILE_CACHE_SIZE
* @param [options]
*/
export async function injectFile(page: Page, filePath: string, options: InjectFileOptions = {}): Promise<unknown> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(filePath, ow.string);
- ow(
- options,
- ow.object.exactShape({
- surviveNavigations: ow.optional.boolean,
- }),
- );
+ parseArgument(page, validators.browserPage);
+ parseArgument(filePath, filePathSchema);
+ const { surviveNavigations } = parseArgument(options, injectFileOptionsSchema);
let contents = injectedFilesCache.get(filePath);
if (!contents) {
@@ -135,7 +162,7 @@ export async function injectFile(page: Page, filePath: string, options: InjectFi
injectedFilesCache.add(filePath, contents);
}
const evalP = page.evaluate(contents);
- if (options.surviveNavigations) {
+ if (surviveNavigations) {
page.on('framenavigated', async () =>
page
.evaluate(contents)
@@ -173,7 +200,7 @@ export async function injectFile(page: Page, filePath: string, options: InjectFi
* @param [options.surviveNavigations] Opt-out option to disable the JQuery reinjection after navigation.
*/
export async function injectJQuery(page: Page, options?: { surviveNavigations?: boolean }): Promise<unknown> {
- ow(page, ow.object.validate(validators.browserPage));
+ parseArgument(page, validators.browserPage);
return injectFile(page, jqueryPath, { surviveNavigations: options?.surviveNavigations ?? true });
}
@@ -194,7 +221,7 @@ export async function parseWithCheerio(
ignoreShadowRoots = false,
ignoreIframes = false,
): Promise<CheerioRoot> {
- ow(page, ow.object.validate(validators.browserPage));
+ parseArgument(page, validators.browserPage);
if (page.frames().length > 1 && !ignoreIframes) {
const frames = await page.$$('iframe');
@@ -282,16 +309,8 @@ export async function parseWithCheerio(
* @param [options]
*/
export async function blockRequests(page: Page, options: BlockRequestsOptions = {}): Promise<void> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(
- options,
- ow.object.exactShape({
- urlPatterns: ow.optional.array.ofType(ow.string),
- extraUrlPatterns: ow.optional.array.ofType(ow.string),
- }),
- );
-
- const { urlPatterns = DEFAULT_BLOCK_REQUEST_URL_PATTERNS, extraUrlPatterns = [] } = options;
+ parseArgument(page, validators.browserPage);
+ const { urlPatterns, extraUrlPatterns } = parseArgument(options, blockRequestsOptionsSchema);
const patternsToBlock = [...urlPatterns, ...extraUrlPatterns];
@@ -368,9 +387,9 @@ export async function cacheResponses(
cache: Dictionary<Partial<ResponseForRequest>>,
responseUrlRules: (string | RegExp)[],
): Promise<void> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(cache, ow.object);
- ow(responseUrlRules, ow.array.ofType(ow.any(ow.string, ow.regExp)));
+ parseArgument(page, validators.browserPage);
+ parseArgument(cache, schemas.anyObject);
+ parseArgument(responseUrlRules, responseUrlRulesSchema);
serviceLocator
.getLogger()
@@ -476,17 +495,9 @@ export async function gotoExtended(
request: Request,
gotoOptions: DirectNavigationOptions = {},
): Promise<HTTPResponse | null> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(
- request,
- ow.object.partialShape({
- url: ow.string.url,
- method: ow.optional.string,
- headers: ow.optional.object,
- payload: ow.optional.any(ow.string, ow.uint8Array),
- }),
- );
- ow(gotoOptions, ow.object);
+ parseArgument(page, validators.browserPage);
+ parseArgument(request, gotoExtendedRequestSchema);
+ parseArgument(gotoOptions, schemas.anyObject);
gotoOptions = { ...gotoOptions };
@@ -588,27 +599,9 @@ export interface InfiniteScrollOptions {
* @param [options]
*/
export async function infiniteScroll(page: Page, options: InfiniteScrollOptions = {}): Promise<void> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(
- options,
- ow.object.exactShape({
- timeoutSecs: ow.optional.number,
- maxScrollHeight: ow.optional.number,
- waitForSecs: ow.optional.number,
- scrollDownAndUp: ow.optional.boolean,
- buttonSelector: ow.optional.string,
- stopScrollCallback: ow.optional.function,
- }),
- );
-
- const {
- timeoutSecs = 0,
- maxScrollHeight = 0,
- waitForSecs = 4,
- scrollDownAndUp = false,
- buttonSelector,
- stopScrollCallback,
- } = options;
+ parseArgument(page, validators.browserPage);
+ const { timeoutSecs, maxScrollHeight, waitForSecs, scrollDownAndUp, buttonSelector, stopScrollCallback } =
+ parseArgument(options, infiniteScrollOptionsSchema);
let finished;
const startTime = Date.now();
@@ -753,28 +746,12 @@ export interface SaveSnapshotOptions {
* @param [options]
*/
export async function saveSnapshot(page: Page, options: SaveSnapshotOptions = {}): Promise<void> {
- ow(page, ow.object.validate(validators.browserPage));
- ow(
+ parseArgument(page, validators.browserPage);
+ const { key, screenshotQuality, saveScreenshot, saveHtml, keyValueStoreName, configuration } = parseArgument(
options,
- ow.object.exactShape({
- key: ow.optional.string.nonEmpty,
- screenshotQuality: ow.optional.number,
- saveScreenshot: ow.optional.boolean,
- saveHtml: ow.optional.boolean,
- keyValueStoreName: ow.optional.string,
- configuration: ow.optional.object,
- }),
+ saveSnapshotOptionsSchema,
);
- const {
- key = 'SNAPSHOT',
- screenshotQuality = 50,
- saveScreenshot = true,
- saveHtml = true,
- keyValueStoreName,
- configuration,
- } = options;
-
try {
const store = await KeyValueStore.open(keyValueStoreName ? { name: keyValueStoreName } : null, {
configuration: configuration ?? Configuration.getGlobalConfiguration(),
@@ -823,7 +800,7 @@ ${error.message}
}
export async function closeCookieModals(page: Page): Promise<void> {
- ow(page, ow.object.validate(validators.browserPage));
+ parseArgument(page, validators.browserPage);
const idcac = await getIdcacPlaywright();
if (idcac?.getInjectableScript()) {
diff --git a/packages/stagehand-crawler/package.json b/packages/stagehand-crawler/package.json
index f8d18bbed..b7c88c92c 100644
--- a/packages/stagehand-crawler/package.json
+++ b/packages/stagehand-crawler/package.json
@@ -62,13 +62,12 @@
"@crawlee/core": "workspace:*",
"@crawlee/types": "workspace:*",
"@crawlee/utils": "workspace:*",
- "ow": "^2.0.0",
- "tslib": "^2.8.1"
+ "tslib": "^2.8.1",
+ "zod": "catalog:"
},
"peerDependencies": {
"@browserbasehq/stagehand": "^3.0.0",
- "playwright": "*",
- "zod": "^3.0.0 || ^4.0.0"
+ "playwright": "*"
},
"peerDependenciesMeta": {
"@browserbasehq/stagehand": {
@@ -76,14 +75,10 @@
},
"playwright": {
"optional": true
- },
- "zod": {
- "optional": true
}
},
"devDependencies": {
"@browserbasehq/stagehand": "3.0.7",
- "playwright": "^1.60.0",
- "zod": "^4.3.5"
+ "playwright": "^1.60.0"
}
}
diff --git a/packages/stagehand-crawler/src/internals/stagehand-crawler.ts b/packages/stagehand-crawler/src/internals/stagehand-crawler.ts
index 7b9117f7f..560898f09 100644
--- a/packages/stagehand-crawler/src/internals/stagehand-crawler.ts
+++ b/packages/stagehand-crawler/src/internals/stagehand-crawler.ts
@@ -25,12 +25,11 @@ import type {
RouteSchemas,
RoutesFromSchemas,
} from '@crawlee/browser';
-import { BrowserCrawler, Router } from '@crawlee/browser';
+import { BrowserCrawler, parseArgument, Router, schemas } from '@crawlee/browser';
import type { BrowserPoolOptions } from '@crawlee/browser-pool';
import type { Dictionary } from '@crawlee/types';
-import ow from 'ow';
import type { LaunchOptions, Page, Response } from 'playwright';
-import type { z } from 'zod';
+import { z } from 'zod';
import type { StagehandController } from './stagehand-controller';
import type { StagehandLaunchContext } from './stagehand-launcher';
@@ -408,22 +407,29 @@ export class StagehandCrawler<
> {
protected static override optionsShape = {
...BrowserCrawler.optionsShape,
- stagehandOptions: ow.optional.object,
- browserPoolOptions: ow.optional.object,
+ stagehandOptions: schemas.anyObject.optional(),
+ browserPoolOptions: schemas.anyObject.optional(),
};
+ protected static override optionsSchema = z.strictObject(StagehandCrawler.optionsShape);
+
/**
* Creates a new instance of StagehandCrawler.
*
* @param options - Crawler configuration options
*/
constructor(options: StagehandCrawlerOptions<ContextExtension, ExtendedContext, Routes> = {}) {
- ow(options, 'StagehandCrawlerOptions', ow.object.exactShape(StagehandCrawler.optionsShape));
+ const parsedOptions = parseArgument(options, StagehandCrawler.optionsSchema, 'StagehandCrawlerOptions');
- const { stagehandOptions = {}, launchContext = {}, contextPipelineBuilder, ...browserCrawlerOptions } = options;
+ const {
+ stagehandOptions = {},
+ launchContext,
+ contextPipelineBuilder,
+ ...browserCrawlerOptions
+ } = parsedOptions;
const browserPoolOptions = {
- ...options.browserPoolOptions,
+ ...parsedOptions.browserPoolOptions,
} as BrowserPoolOptions;
// Create launcher with Stagehand plugin
diff --git a/packages/stagehand-crawler/src/internals/stagehand-launcher.ts b/packages/stagehand-crawler/src/internals/stagehand-launcher.ts
index efae47f76..b54149f92 100644
--- a/packages/stagehand-crawler/src/internals/stagehand-launcher.ts
+++ b/packages/stagehand-crawler/src/internals/stagehand-launcher.ts
@@ -1,7 +1,7 @@
import type { BrowserLaunchContext } from '@crawlee/browser';
-import { BrowserLauncher, Configuration } from '@crawlee/browser';
-import ow from 'ow';
+import { BrowserLauncher, Configuration, parseArgument, schemas } from '@crawlee/browser';
import type { BrowserType, LaunchOptions } from 'playwright';
+import { z } from 'zod';
import type { StagehandOptions } from './stagehand-crawler';
import { StagehandPlugin } from './stagehand-plugin';
@@ -65,11 +65,14 @@ export interface StagehandLaunchContext extends BrowserLaunchContext<LaunchOptio
export class StagehandLauncher extends BrowserLauncher<StagehandPlugin> {
protected static override optionsShape = {
...BrowserLauncher.optionsShape,
- launcher: ow.optional.object,
- launchContextOptions: ow.optional.object,
- stagehandOptions: ow.optional.object,
+ // Passthrough schemas — the launcher module object must keep its prototype through parsing.
+ launcher: schemas.anyObject.optional(),
+ launchContextOptions: schemas.anyObject.optional(),
+ stagehandOptions: schemas.anyObject.optional(),
};
+ protected static override optionsSchema = z.strictObject(StagehandLauncher.optionsShape);
+
readonly #stagehandOptions: StagehandOptions;
/**
@@ -79,7 +82,7 @@ export class StagehandLauncher extends BrowserLauncher<StagehandPlugin> {
launchContext: StagehandLaunchContext = {},
override readonly configuration = Configuration.getGlobalConfiguration(),
) {
- ow(launchContext, 'StagehandLaunchContext', ow.object.exactShape(StagehandLauncher.optionsShape));
+ const parsedContext = parseArgument(launchContext, StagehandLauncher.optionsSchema, 'StagehandLaunchContext');
const {
launcher = BrowserLauncher.requireLauncherOrThrow<typeof import('playwright')>(
@@ -87,9 +90,9 @@ export class StagehandLauncher extends BrowserLauncher<StagehandPlugin> {
'apify/actor-node-playwright-*',
).chromium,
stagehandOptions = {},
- } = launchContext;
+ } = parsedContext;
- const { launchOptions = {}, ...rest } = launchContext;
+ const { launchOptions = {}, ...rest } = parsedContext;
// Call super first before initializing properties
super(
@@ -97,7 +100,7 @@ export class StagehandLauncher extends BrowserLauncher<StagehandPlugin> {
...rest,
launchOptions: {
...launchOptions,
- executablePath: getDefaultExecutablePath(launchContext, configuration),
+ executablePath: getDefaultExecutablePath(parsedContext, configuration),
},
launcher,
},
diff --git a/packages/utils/package.json b/packages/utils/package.json
index a5be83c05..1b0e96b11 100644
--- a/packages/utils/package.json
+++ b/packages/utils/package.json
@@ -49,10 +49,10 @@
"cheerio": "^1.0.0",
"domhandler": "^5.0.3",
"file-type": "^21.0.0",
- "ow": "^2.0.0",
"robots-parser": "^3.0.1",
"sax": "^1.4.1",
"tslib": "^2.8.1",
- "whatwg-mimetype": "^4.0.0"
+ "whatwg-mimetype": "^4.0.0",
+ "zod": "catalog:"
}
}
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 081f3a772..0a81aadf9 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -7,3 +7,4 @@ export * as social from './internals/social.js';
export * from './internals/open_graph_parser.js';
export * from './internals/robots.js';
export * from './internals/sitemap.js';
+export * from './internals/validation.js';
diff --git a/packages/utils/src/internal.ts b/packages/utils/src/internal.ts
index fa51c0dca..91cc0cbc2 100644
--- a/packages/utils/src/internal.ts
+++ b/packages/utils/src/internal.ts
@@ -5,3 +5,5 @@ export { tryAbsoluteURL } from './internals/extract-urls.js';
export { URL_NO_COMMAS_REGEX, URL_WITH_COMMAS_REGEX } from './internals/general.js';
export * from './internals/iterables.js';
export * from './internals/url.js';
+export * from './internals/validation.js';
+export * as schemas from './internals/schemas.js';
diff --git a/packages/utils/src/internals/extract-urls.ts b/packages/utils/src/internals/extract-urls.ts
index f363cbf8a..6a47cfeb6 100644
--- a/packages/utils/src/internals/extract-urls.ts
+++ b/packages/utils/src/internals/extract-urls.ts
@@ -1,8 +1,23 @@
import { FetchHttpClient } from '@crawlee/http-client';
-import type { BaseHttpClient } from '@crawlee/types';
-import ow from 'ow';
+import type { BaseHttpClient } from '@crawlee/http-client';
+import { z } from 'zod';
import { URL_NO_COMMAS_REGEX } from './general.js';
+import { httpClient as httpClientSchema } from './schemas.js';
+import { parseArgument } from './validation.js';
+
+const downloadListOfUrlsOptionsSchema = z.strictObject({
+ url: z.url(),
+ encoding: z.string().default('utf8'),
+ urlRegExp: z.instanceof(RegExp).default(URL_NO_COMMAS_REGEX),
+ proxyUrl: z.string().optional(),
+ httpClient: httpClientSchema.default(() => new FetchHttpClient()),
+});
+
+const extractUrlsOptionsSchema = z.strictObject({
+ string: z.string(),
+ urlRegExp: z.instanceof(RegExp).default(URL_NO_COMMAS_REGEX),
+});
export interface DownloadListOfUrlsOptions {
/**
@@ -37,23 +52,7 @@ export interface DownloadListOfUrlsOptions {
* Optionally, custom regular expression and encoding may be provided.
*/
export async function downloadListOfUrls(options: DownloadListOfUrlsOptions): Promise<string[]> {
- ow(
- options as any,
- ow.object.exactShape({
- url: ow.string.url,
- encoding: ow.optional.string,
- urlRegExp: ow.optional.regExp,
- proxyUrl: ow.optional.string,
- httpClient: ow.optional.object,
- }),
- );
- const {
- url,
- encoding = 'utf8',
- urlRegExp = URL_NO_COMMAS_REGEX,
- proxyUrl,
- httpClient = new FetchHttpClient(),
- } = options;
+ const { url, encoding, urlRegExp, proxyUrl, httpClient } = parseArgument(options, downloadListOfUrlsOptionsSchema);
// Try to detect wrong urls and fix them. Currently, detects only sharing url instead of csv download one.
const match = /^(https:\/\/docs\.google\.com\/spreadsheets\/d\/(?:\w|-)+)\/?/.exec(url);
@@ -89,16 +88,9 @@ export interface ExtractUrlsOptions {
* Collects all URLs in an arbitrary string to an array, optionally using a custom regular expression.
*/
export function extractUrls(options: ExtractUrlsOptions): string[] {
- ow(
- options as any,
- ow.object.exactShape({
- string: ow.string,
- urlRegExp: ow.optional.regExp,
- }),
- );
- const lines = options.string.split('\n');
+ const { string, urlRegExp } = parseArgument(options, extractUrlsOptionsSchema);
+ const lines = string.split('\n');
const result: string[] = [];
- const urlRegExp = options.urlRegExp ?? URL_NO_COMMAS_REGEX;
for (const line of lines) {
result.push(...(line.match(urlRegExp) ?? []));
diff --git a/packages/utils/src/internals/robots.ts b/packages/utils/src/internals/robots.ts
index 92b1528c7..2e47b492f 100644
--- a/packages/utils/src/internals/robots.ts
+++ b/packages/utils/src/internals/robots.ts
@@ -1,5 +1,6 @@
import { FetchHttpClient } from '@crawlee/http-client';
-import type { BaseHttpClient, CrawleeLogger } from '@crawlee/types';
+import type { BaseHttpClient } from '@crawlee/http-client';
+import type { CrawleeLogger } from '@crawlee/types';
import type { Robot } from 'robots-parser';
import robotsParser from 'robots-parser';
diff --git a/packages/utils/src/internals/schemas.ts b/packages/utils/src/internals/schemas.ts
new file mode 100644
index 000000000..3f8ea71e1
--- /dev/null
+++ b/packages/utils/src/internals/schemas.ts
@@ -0,0 +1,149 @@
+import { BaseHttpClient } from '@crawlee/http-client';
+import type { Dictionary } from '@crawlee/types';
+import { z } from 'zod';
+
+/**
+ * Accepts any object (including arrays and functions).
+ * @internal
+ */
+export const anyObject = z.custom<Dictionary>(
+ (value) => (typeof value === 'object' && value !== null) || typeof value === 'function',
+ { message: 'Invalid input: expected object' },
+);
+
+/**
+ * Accepts any array without validating its items (cheap for huge arrays).
+ * @internal
+ */
+export const anyArray = z.custom<unknown[]>(Array.isArray, { message: 'Invalid input: expected array' });
+
+/**
+ * Accepts any function.
+ * @internal
+ */
+export const anyFunction = z.custom<(...args: any[]) => unknown>((value) => typeof value === 'function', {
+ message: 'Invalid input: expected function',
+});
+
+/**
+ * Mirrors `ow.number`: `Infinity` is a valid number, `NaN` is not.
+ * @internal
+ */
+export const anyNumber = z.custom<number>((value) => typeof value === 'number' && !Number.isNaN(value), {
+ message: 'Invalid input: expected number',
+});
+
+/**
+ * Accepts any object (including functions) that has all the given keys, own or inherited.
+ * @internal
+ */
+export function objectWithKeys(keys: string[], message?: string): z.ZodType<Dictionary> {
+ return z.custom<Dictionary>(
+ (value) =>
+ ((typeof value === 'object' && value !== null) || typeof value === 'function') &&
+ keys.every((key) => key in value),
+ {
+ message:
+ message ?? `Invalid input: expected an object with keys ${keys.map((key) => `'${key}'`).join(', ')}`,
+ },
+ );
+}
+
+/**
+ * Accepts only instances of {@link BaseHttpClient} (all Crawlee HTTP clients extend it).
+ * @internal
+ */
+export const httpClient = z.instanceof(BaseHttpClient);
+
+/**
+ * Accepts any object implementing the CrawleeLogger interface.
+ * @internal
+ */
+export const logger = objectWithKeys(
+ ['child', 'info', 'error', 'warning'],
+ "Expected an object implementing the CrawleeLogger interface (missing one of 'child', 'info', 'error', 'warning'), got something else.",
+);
+
+/**
+ * Accepts any typed array (`Uint8Array`, `Float64Array`, ...), but not a `DataView`.
+ * @internal
+ */
+export const typedArray = z.custom<NodeJS.TypedArray>(
+ (value) => ArrayBuffer.isView(value) && !(value instanceof DataView),
+ { message: 'Invalid input: expected a typed array' },
+);
+
+/**
+ * Accepts any non-null, non-array object.
+ * @internal
+ */
+export const plainObject = z.custom<Record<string, unknown>>(
+ (value) => typeof value === 'object' && value !== null && !Array.isArray(value),
+ { message: 'Invalid input: expected an object' },
+);
+
+/**
+ * Shape of a request stored in a request queue.
+ * @internal
+ */
+export const storageRequest = z.looseObject({
+ id: z.string(),
+ url: z.url({ protocol: /^https?$/ }),
+ uniqueKey: z.string(),
+ method: z.string().optional(),
+ retryCount: z.number().int().optional(),
+ handledAt: z.union([z.string(), z.date()]).optional(),
+});
+
+/**
+ * {@link storageRequest} before an id is assigned.
+ * @internal
+ */
+export const storageRequestWithoutId = storageRequest.omit({ id: true });
+
+/**
+ * `z.array(item)` whose top-level type error names the element type — ``expected an array of numbers`` —
+ * instead of zod's bare `expected array`. Element failures keep zod's per-index messages, and `elements`
+ * is a human-readable plural (`'numbers'`, `'URL patterns'`), since element types cannot be introspected.
+ * @internal
+ */
+export function arrayOf<TItem extends z.ZodType>(item: TItem, elements: string): z.ZodArray<TItem> {
+ return z.array(item, {
+ error: (issue) =>
+ issue.code === 'invalid_type' ? `Invalid input: expected an array of ${elements}` : undefined,
+ });
+}
+
+/**
+ * Batch of {@link storageRequestWithoutId}.
+ * @internal
+ */
+export const storageRequestBatch = arrayOf(storageRequestWithoutId, 'requests');
+
+/**
+ * Options of request queue add/update operations.
+ * @internal
+ */
+export const requestQueueOperationOptions = z.object({
+ forefront: z.boolean().optional(),
+});
+
+/**
+ * Options of key-value store `listKeys`.
+ * @internal
+ */
+export const keyValueStoreListKeysOptions = z.object({
+ prefix: z.string().optional(),
+ exclusiveStartKey: z.string().optional(),
+ limit: z.number().int().gt(0).optional(),
+});
+
+/**
+ * Options of dataset item listing.
+ * @internal
+ */
+export const datasetListItemsOptions = z.object({
+ desc: z.boolean().optional(),
+ limit: z.number().int().optional(),
+ offset: z.number().int().optional(),
+});
diff --git a/packages/utils/src/internals/sitemap.ts b/packages/utils/src/internals/sitemap.ts
index 3b380bae9..b63349470 100644
--- a/packages/utils/src/internals/sitemap.ts
+++ b/packages/utils/src/internals/sitemap.ts
@@ -5,7 +5,8 @@ import { StringDecoder } from 'node:string_decoder';
import { createGunzip } from 'node:zlib';
import { FetchHttpClient } from '@crawlee/http-client';
-import type { BaseHttpClient, CrawleeLogger } from '@crawlee/types';
+import type { BaseHttpClient } from '@crawlee/http-client';
+import type { CrawleeLogger } from '@crawlee/types';
// Imported as a type only so `sax` (a fairly heavy parser) isn't loaded eagerly with @crawlee/utils.
import type * as sax from 'sax';
import MIMEType from 'whatwg-mimetype';
diff --git a/packages/utils/src/internals/validation.ts b/packages/utils/src/internals/validation.ts
new file mode 100644
index 000000000..308be4d5d
--- /dev/null
+++ b/packages/utils/src/internals/validation.ts
@@ -0,0 +1,151 @@
+import type { z } from 'zod';
+
+/** Formats a zod issue path like `groups[0]` or `countryCode`. */
+function formatIssuePath(path: readonly PropertyKey[]): string {
+ let out = '';
+ for (const key of path) {
+ if (typeof key === 'number') out += `[${key}]`;
+ else out += out ? `.${String(key)}` : String(key);
+ }
+ return out;
+}
+
+/** Reads the value at `path` from the validated input, to include in the error. */
+function valueAtPath(root: unknown, path: readonly PropertyKey[]): unknown {
+ let current = root;
+ for (const key of path) {
+ if (current === null || typeof current !== 'object') return undefined;
+ current = (current as Record<PropertyKey, unknown>)[key];
+ }
+ return current;
+}
+
+/** Names the runtime type of `value` the way zod's own messages do (`null`, `array`, `string`, …). */
+function describeType(value: unknown): string {
+ if (value === null) return 'null';
+ if (Array.isArray(value)) return 'array';
+ return typeof value;
+}
+
+/** The bare custom-schema messages that stop at the expected type, e.g. `Invalid input: expected number`. */
+const BARE_EXPECTED_TYPE_MESSAGE =
+ /^Invalid input: expected (an array of .+|a typed array|an object|object|array|function|number|string|boolean)$/;
+
+/** Longest received string rendered in an error; the rest is elided. */
+const MAX_RENDERED_STRING_LENGTH = 200;
+
+/** Renders a primitive received value for an error; skips objects/Dates (noisy). */
+function describeReceived(value: unknown): string | undefined {
+ switch (typeof value) {
+ case 'string':
+ // An empty string would render as bare backticks — make it visible.
+ if (value === '') return "''";
+ return value.length > MAX_RENDERED_STRING_LENGTH
+ ? `${value.slice(0, MAX_RENDERED_STRING_LENGTH)}… (${value.length - MAX_RENDERED_STRING_LENGTH} more characters)`
+ : value;
+ case 'number':
+ case 'boolean':
+ case 'bigint':
+ return String(value);
+ default:
+ return undefined;
+ }
+}
+
+/** Renders the received side of a sentence: ``received the string `abc` ``, `received NaN`, `received array`. */
+function describeReceivedClause(value: unknown): string {
+ if (typeof value === 'number' && Number.isNaN(value)) return 'received NaN';
+ if (value === '') return 'received an empty string';
+ const rendered = describeReceived(value);
+ return rendered === undefined
+ ? `received ${describeType(value)}`
+ : `received the ${describeType(value)} \`${rendered}\``;
+}
+
+/** Renders one issue as a line each; a union expands into a line per failed arm. */
+function formatIssue(issue: z.ZodError['issues'][number], root: unknown, basePath: readonly PropertyKey[]): string[] {
+ const path = [...basePath, ...issue.path];
+ // A union's own message is a bare "Invalid input" — the useful part is in `errors`,
+ // whose paths are relative to the union, hence passing `path` down as the base.
+ if (issue.code === 'invalid_union') {
+ return issue.errors.flatMap((arm) => arm.flatMap((nested) => formatIssue(nested, root, path)));
+ }
+
+ const location = path.length ? ` at \`${formatIssuePath(path)}\`` : '';
+ const value = valueAtPath(root, path);
+ const rendered = describeReceived(value);
+
+ // ow named the received type ("expected `number` but received type `string`"). The received value is
+ // folded into that clause (``received the string `3` ``) rather than dangling after the location: our
+ // custom schemas stop at the expected type, so the clause is appended; zod's built-in messages already
+ // end with `, received <type>`, so that tail is replaced with the enriched one.
+ let { message } = issue;
+ let got = '';
+ const bareExpected = BARE_EXPECTED_TYPE_MESSAGE.exec(message);
+ const zodReceived = /, received (\S+)$/.exec(message);
+ // `arrayOf` messages name the element type — their expected runtime type is `array`.
+ const expectedType = bareExpected?.[1].startsWith('an array of') ? 'array' : bareExpected?.[1];
+ if (bareExpected && expectedType !== (Number.isNaN(value as number) ? 'NaN' : describeType(value))) {
+ message += `, ${describeReceivedClause(value)}`;
+ } else if (zodReceived && zodReceived[1] === describeType(value) && rendered !== undefined) {
+ message = `${message.slice(0, zodReceived.index)}, ${describeReceivedClause(value)}`;
+ } else if (rendered !== undefined && !message.endsWith(`received ${rendered}`)) {
+ // Messages that never name a received type (regex, min/max, enums) keep the plain value suffix.
+ got = `, got \`${rendered}\``;
+ }
+
+ return [`${message}${location}${got}`];
+}
+
+/**
+ * Formats a `ZodError` as a plain, human-readable message that names the
+ * offending field *and* the value it received (e.g. ``must match pattern
+ * /^[A-Z]{2}$/ at `countryCode`, got `CZE` ``) — closer to the old `ow` errors
+ * than zod's default, which omits the received value.
+ */
+function formatZodError(error: z.ZodError, root: unknown, label?: string): string {
+ const lines = error.issues.flatMap((issue) => formatIssue(issue, root, []));
+ // The label names the validated interface, the way ow's errors ended with "in object `X`".
+ return (label ? lines.map((line) => `${line} in \`${label}\``) : lines).join('\n');
+}
+
+/**
+ * Thrown when an argument fails schema validation.
+ *
+ * Its `message` is a human-readable sentence naming the offending field and the
+ * value it received (rather than a raw JSON dump). The structured
+ * {@link https://zod.dev | zod} issues are available on `issues`, and the
+ * original `ZodError` on `cause`, for programmatic inspection.
+ */
+export class ArgumentValidationError extends Error {
+ /** Structured issues from the underlying schema check. */
+ readonly issues: z.ZodError['issues'];
+
+ /** The raw zod error that triggered this. */
+ override readonly cause: z.ZodError;
+
+ constructor(error: z.ZodError, value: unknown, label?: string) {
+ super(formatZodError(error, value, label), { cause: error });
+ this.name = 'ArgumentValidationError';
+ this.issues = error.issues;
+ this.cause = error;
+ }
+}
+
+/**
+ * Parses `value` with `schema`, returning the typed result (with schema defaults applied).
+ * Throws {@link ArgumentValidationError} on failure.
+ *
+ * The optional `label` names the interface being validated and is appended to every error line
+ * (e.g. ``… at `maxRequestRetries` in `BasicCrawlerOptions` ``).
+ * @internal
+ */
+export function parseArgument<TValue, TSchema extends z.ZodType>(
+ value: TValue,
+ schema: TSchema,
+ label?: string,
+): TValue & z.output<TSchema> {
+ const result = schema.safeParse(value);
+ if (!result.success) throw new ArgumentValidationError(result.error, value, label);
+ return result.data as TValue & z.output<TSchema>;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c07c9e452..cea73cdf8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -4,6 +4,12 @@ settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
+catalogs:
+ default:
+ zod:
+ specifier: ^4.4.3
+ version: 4.4.3
+
overrides:
playwright-core: 1.61.1
'@browserbasehq/stagehand': 3.0.7
@@ -248,8 +254,8 @@ importers:
specifier: ^4.1.0-beta.6
zod:
- specifier: ^4.0.0
- version: 4.3.6
+ specifier: 'catalog:'
+ version: 4.4.3
docs:
dependencies:
@@ -326,9 +332,6 @@ importers:
csv-stringify:
specifier: ^6.5.2
version: 6.7.0
- ow:
- specifier: ^2.0.0
- version: 2.0.0
tldts:
specifier: ^7.0.6
version: 7.0.28
@@ -338,6 +341,9 @@ importers:
type-fest:
specifier: ^4.41.0
version: 4.41.0
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
optionalDependencies:
'@crawlee/impit-client':
specifier: workspace:^
@@ -360,9 +366,6 @@ importers:
'@crawlee/utils':
specifier: workspace:*
version: link:../utils
- ow:
- specifier: ^2.0.0
- version: 2.0.0
playwright:
specifier: '*'
version: 1.61.1
@@ -375,6 +378,9 @@ importers:
type-fest:
specifier: ^4.41.0
version: 4.41.0
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
packages/browser-pool:
dependencies:
@@ -399,9 +405,6 @@ importers:
nanoid:
specifier: ^5.1.5
version: 5.1.9
- ow:
- specifier: ^2.0.0
- version: 2.0.0
p-limit:
specifier: ^6.2.0
version: 6.2.0
@@ -423,6 +426,9 @@ importers:
tslib:
specifier: ^2.8.1
version: 2.8.1
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
packages/cheerio-crawler:
dependencies:
@@ -483,6 +489,9 @@ importers:
'@crawlee/fs-storage':
specifier: workspace:*
version: link:../fs-storage
+ '@crawlee/http-client':
+ specifier: workspace:*
+ version: link:../http-client
'@crawlee/types':
specifier: workspace:*
version: link:../types
@@ -492,9 +501,6 @@ importers:
'@sapphire/async-queue':
specifier: ^1.5.5
version: 1.5.5
- '@sapphire/shapeshift':
- specifier: ^4.0.0
- version: 4.0.0
'@vladfrangu/async_event_emitter':
specifier: ^2.4.6
version: 2.4.7
@@ -513,9 +519,6 @@ importers:
minimatch:
specifier: ^9.0.0
version: 9.0.9
- ow:
- specifier: ^2.0.0
- version: 2.0.0
stream-json:
specifier: ^1.9.1
version: 1.9.1
@@ -532,8 +535,8 @@ importers:
specifier: ^4.41.0
version: 4.41.0
zod:
- specifier: ^4.1.0
- version: 4.3.6
+ specifier: 'catalog:'
+ version: 4.4.3
packages/crawlee:
dependencies:
@@ -603,9 +606,12 @@ importers:
'@crawlee/types':
specifier: workspace:*
version: link:../types
- '@sapphire/shapeshift':
- specifier: ^4.0.0
- version: 4.0.0
+ '@crawlee/utils':
+ specifier: workspace:*
+ version: link:../utils
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
packages/got-scraping-client:
dependencies:
@@ -663,15 +669,15 @@ importers:
mime-types:
specifier: ^3.0.1
version: 3.0.2
- ow:
- specifier: ^2.0.0
- version: 2.0.0
tslib:
specifier: ^2.8.1
version: 2.8.1
type-fest:
specifier: ^4.41.0
version: 4.41.0
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
packages/impit-client:
dependencies:
@@ -717,12 +723,12 @@ importers:
jsdom:
specifier: ^26.1.0
version: 26.1.0([email protected])
- ow:
- specifier: ^2.0.0
- version: 2.0.0
tslib:
specifier: ^2.8.1
version: 2.8.1
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
packages/linkedom-crawler:
dependencies:
@@ -747,9 +753,6 @@ importers:
linkedom:
specifier: ^0.18.10
version: 0.18.12
- ow:
- specifier: ^2.0.0
- version: 2.0.0
tslib:
specifier: ^2.8.1
version: 2.8.1
@@ -798,9 +801,6 @@ importers:
ml-matrix:
specifier: ^6.12.1
version: 6.12.1
- ow:
- specifier: ^2.0.0
- version: 2.0.0
playwright:
specifier: '*'
version: 1.61.1
@@ -814,8 +814,8 @@ importers:
specifier: ^4.0.0
version: 4.41.0
zod:
- specifier: ^4.1.0
- version: 4.3.6
+ specifier: 'catalog:'
+ version: 4.4.3
packages/puppeteer-crawler:
dependencies:
@@ -849,15 +849,15 @@ importers:
jquery:
specifier: ^3.7.1
version: 3.7.1
- ow:
- specifier: ^2.0.0
- version: 2.0.0
puppeteer:
specifier: '*'
version: 25.3.0([email protected])
tslib:
specifier: ^2.8.1
version: 2.8.1
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
packages/stagehand-crawler:
dependencies:
@@ -879,22 +879,19 @@ importers:
'@crawlee/utils':
specifier: workspace:*
version: link:../utils
- ow:
- specifier: ^2.0.0
- version: 2.0.0
tslib:
specifier: ^2.8.1
version: 2.8.1
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
devDependencies:
'@browserbasehq/stagehand':
specifier: 3.0.7
playwright:
specifier: ^1.60.0
version: 1.61.1
- zod:
- specifier: ^4.3.5
- version: 4.3.6
packages/templates:
dependencies:
@@ -931,9 +928,6 @@ importers:
file-type:
specifier: ^21.0.0
version: 21.3.4
- ow:
- specifier: ^2.0.0
- version: 2.0.0
robots-parser:
specifier: ^3.0.1
version: 3.0.1
@@ -946,6 +940,9 @@ importers:
whatwg-mimetype:
specifier: ^4.0.0
version: 4.0.0
+ zod:
+ specifier: 'catalog:'
+ version: 4.4.3
website:
dependencies:
@@ -4053,10 +4050,6 @@ packages:
resolution: {integrity: sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==}
engines: {node: '>=v14.0.0', npm: '>=7.0.0'}
- '@sapphire/[email protected]':
- resolution: {integrity: sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==}
- engines: {node: '>=v16'}
-
'@sec-ant/[email protected]':
resolution: {integrity: sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==}
@@ -12613,6 +12606,9 @@ packages:
resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}
+ resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
+
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
@@ -12630,123 +12626,123 @@ snapshots:
section-matter: 1.0.0
strip-bom-string: 1.0.0
dependencies:
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
- '@ai-sdk/openai': 2.0.102([email protected])
+ '@ai-sdk/openai': 2.0.102([email protected])
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
- '@ai-sdk/openai-compatible': 1.0.35([email protected])
+ '@ai-sdk/openai-compatible': 1.0.35([email protected])
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
'@vercel/oidc': 3.1.0
- zod: 4.3.6
+ zod: 4.4.3
dependencies:
- '@ai-sdk/anthropic': 2.0.74([email protected])
- '@ai-sdk/google': 2.0.68([email protected])
- '@ai-sdk/openai-compatible': 1.0.35([email protected])
+ '@ai-sdk/anthropic': 2.0.74([email protected])
+ '@ai-sdk/google': 2.0.68([email protected])
+ '@ai-sdk/openai-compatible': 1.0.35([email protected])
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
google-auth-library: 10.6.2
- zod: 4.3.6
+ zod: 4.4.3
transitivePeerDependencies:
- supports-color
optional: true
dependencies:
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
'@ai-sdk/provider': 2.0.1
'@standard-schema/spec': 1.1.0
eventsource-parser: 3.0.6
- zod: 4.3.6
+ zod: 4.4.3
'@ai-sdk/[email protected]':
dependencies:
json-schema: 0.4.0
dependencies:
- '@ai-sdk/openai-compatible': 1.0.35([email protected])
+ '@ai-sdk/openai-compatible': 1.0.35([email protected])
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
dependencies:
- '@ai-sdk/openai-compatible': 1.0.35([email protected])
+ '@ai-sdk/openai-compatible': 1.0.35([email protected])
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
'@algolia/[email protected]':
@@ -13740,43 +13736,43 @@ snapshots:
transitivePeerDependencies:
- encoding
dependencies:
'@ai-sdk/provider': 2.0.1
'@anthropic-ai/sdk': 0.39.0([email protected])
'@browserbasehq/sdk': 2.10.0([email protected])
- '@google/genai': 1.50.0(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])
- '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
- ai: 5.0.173([email protected])
+ '@google/genai': 1.50.0(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])
+ '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
+ ai: 5.0.173([email protected])
deepmerge: 4.3.1
devtools-protocol: 0.0.1464554
dotenv: 16.4.7
fetch-cookie: 3.2.0
pino: 9.14.0
pino-pretty: 13.1.3
uuid: 11.1.0
ws: 8.21.1([email protected])
- zod: 4.3.6
- zod-to-json-schema: 3.25.2([email protected])
+ zod: 4.4.3
+ zod-to-json-schema: 3.25.2([email protected])
optionalDependencies:
- '@ai-sdk/anthropic': 2.0.74([email protected])
- '@ai-sdk/azure': 2.0.104([email protected])
- '@ai-sdk/cerebras': 1.0.40([email protected])
- '@ai-sdk/deepseek': 1.0.36([email protected])
- '@ai-sdk/google': 2.0.68([email protected])
- '@ai-sdk/google-vertex': 3.0.128([email protected])
- '@ai-sdk/groq': 2.0.37([email protected])
- '@ai-sdk/mistral': 2.0.30([email protected])
- '@ai-sdk/openai': 2.0.102([email protected])
- '@ai-sdk/perplexity': 2.0.27([email protected])
- '@ai-sdk/togetherai': 1.0.38([email protected])
- '@ai-sdk/xai': 2.0.67([email protected])
+ '@ai-sdk/anthropic': 2.0.74([email protected])
+ '@ai-sdk/azure': 2.0.104([email protected])
+ '@ai-sdk/cerebras': 1.0.40([email protected])
+ '@ai-sdk/deepseek': 1.0.36([email protected])
+ '@ai-sdk/google': 2.0.68([email protected])
+ '@ai-sdk/google-vertex': 3.0.128([email protected])
+ '@ai-sdk/groq': 2.0.37([email protected])
+ '@ai-sdk/mistral': 2.0.30([email protected])
+ '@ai-sdk/openai': 2.0.102([email protected])
+ '@ai-sdk/perplexity': 2.0.27([email protected])
+ '@ai-sdk/togetherai': 1.0.38([email protected])
+ '@ai-sdk/xai': 2.0.67([email protected])
bufferutil: 4.1.0
chrome-launcher: 1.2.1
- ollama-ai-provider-v2: 1.5.5([email protected])
+ ollama-ai-provider-v2: 1.5.5([email protected])
patchright-core: 1.59.4
playwright: 1.61.1
playwright-core: 1.61.1
@@ -15250,14 +15246,14 @@ snapshots:
react: 19.2.5
react-dom: 19.2.5([email protected])
dependencies:
google-auth-library: 10.6.2
p-retry: 4.6.2
protobufjs: 7.5.4
ws: 8.21.1([email protected])
optionalDependencies:
- '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
+ '@modelcontextprotocol/sdk': 1.29.0(@cfworker/[email protected])([email protected])
transitivePeerDependencies:
- bufferutil
- supports-color
@@ -15602,14 +15598,14 @@ snapshots:
'@keyv/[email protected]': {}
dependencies:
'@cfworker/json-schema': 4.1.1
ansi-styles: 5.2.0
camelcase: 6.3.0
decamelize: 1.2.0
js-tiktoken: 1.0.21
mustache: 4.2.0
p-queue: 6.6.2
p-retry: 4.6.2
@@ -15622,9 +15618,9 @@ snapshots:
- '@opentelemetry/sdk-trace-base'
- openai
dependencies:
js-tiktoken: 1.0.21
zod: 3.25.76
@@ -15716,7 +15712,7 @@ snapshots:
'@microsoft/[email protected]': {}
- '@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])':
+ '@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected])':
dependencies:
'@hono/node-server': 1.19.14([email protected])
ajv: 8.18.0
@@ -15733,8 +15729,8 @@ snapshots:
json-schema-typed: 8.0.2
pkce-challenge: 5.0.1
raw-body: 3.0.2
- zod: 4.3.6
- zod-to-json-schema: 3.25.2([email protected])
+ zod: 4.4.3
+ zod-to-json-schema: 3.25.2([email protected])
optionalDependencies:
'@cfworker/json-schema': 4.1.1
transitivePeerDependencies:
@@ -16511,11 +16507,6 @@ snapshots:
'@sapphire/[email protected]': {}
- '@sapphire/[email protected]':
- dependencies:
- fast-deep-equal: 3.1.3
- lodash: 4.18.1
-
'@sec-ant/[email protected]': {}
'@shikijs/[email protected]':
@@ -17678,13 +17669,13 @@ snapshots:
clean-stack: 2.2.0
indent-string: 4.0.0
dependencies:
- '@ai-sdk/gateway': 2.0.77([email protected])
+ '@ai-sdk/gateway': 2.0.77([email protected])
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
'@opentelemetry/api': 1.9.0
- zod: 4.3.6
+ zod: 4.4.3
optionalDependencies:
@@ -21825,7 +21816,7 @@ snapshots:
vscode-languageserver-textdocument: 1.0.12
vscode-uri: 3.1.0
dependencies:
'@types/uuid': 10.0.0
chalk: 4.1.2
@@ -21835,7 +21826,7 @@ snapshots:
uuid: 10.0.0
optionalDependencies:
'@opentelemetry/api': 1.9.0
@@ -23297,11 +23288,11 @@ snapshots:
dependencies:
'@ai-sdk/provider': 2.0.1
- '@ai-sdk/provider-utils': 3.0.23([email protected])
- zod: 4.3.6
+ '@ai-sdk/provider-utils': 3.0.23([email protected])
+ zod: 4.4.3
optional: true
@@ -23358,7 +23349,7 @@ snapshots:
transitivePeerDependencies:
- encoding
dependencies:
'@types/node': 18.19.130
'@types/node-fetch': 2.6.13
@@ -23369,7 +23360,7 @@ snapshots:
node-fetch: 2.7.0([email protected])
optionalDependencies:
ws: 8.21.1([email protected])
- zod: 4.3.6
+ zod: 4.4.3
transitivePeerDependencies:
- encoding
@@ -26733,9 +26724,9 @@ snapshots:
dependencies:
zod: 3.25.76
dependencies:
- zod: 4.3.6
+ zod: 4.4.3
dependencies:
@@ -26748,6 +26739,8 @@ snapshots:
+
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 44166d6fa..b8c36b54d 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -3,6 +3,9 @@ packages:
- docs
- website
+catalog:
+ zod: ^4.4.3
+
minimumReleaseAge: 1440
minimumReleaseAgeExclude:
- "@apify/*"
diff --git a/scripts/copy.ts b/scripts/copy.ts
index adebcd65d..3ee28f625 100644
--- a/scripts/copy.ts
+++ b/scripts/copy.ts
@@ -136,10 +136,44 @@ if (options['pin-versions']) {
writeFileSync(pkgPath, `${JSON.stringify(pkgJson, null, 4)}\n`);
}
+/**
+ * `catalog:` specifiers are a pnpm workspace feature; lerna publishes the manifest verbatim,
+ * so they have to be inlined with the versions from `pnpm-workspace.yaml` before publishing.
+ */
+function getCatalogVersions(): Record<string, string> {
+ const workspaceYaml = readFileSync(resolve(root, 'pnpm-workspace.yaml')).toString();
+ const catalogBlock = workspaceYaml.match(/^catalog:\n((?: {2}.+\n)+)/m)?.[1] ?? '';
+ const versions: Record<string, string> = {};
+
+ for (const line of catalogBlock.split('\n')) {
+ const match = line.match(/^ {2}["']?([^"':]+)["']?:\s*["']?(.+?)["']?\s*$/);
+ if (match) versions[match[1]] = match[2];
+ }
+
+ return versions;
+}
+
copy('README.md', root, target);
copy('LICENSE.md', root, target);
copy('package.json', process.cwd(), target);
rewrite(resolve(target, 'package.json'), (pkg) => {
- return pkg.replace(/dist\//g, '').replace(/src\/(.*)\.ts/g, '$1.js');
+ const catalog = getCatalogVersions();
+ const manifest = JSON.parse(pkg.replace(/dist\//g, '').replace(/src\/(.*)\.ts/g, '$1.js'));
+
+ for (const deps of [
+ manifest.dependencies,
+ manifest.devDependencies,
+ manifest.peerDependencies,
+ manifest.optionalDependencies,
+ ]) {
+ for (const dep of Object.keys(deps ?? {})) {
+ if (deps[dep] === 'catalog:') {
+ if (!catalog[dep]) throw new Error(`Missing catalog entry for '${dep}' in pnpm-workspace.yaml`);
+ deps[dep] = catalog[dep];
+ }
+ }
+ }
+
+ return `${JSON.stringify(manifest, null, 4)}\n`;
});
rewrite(resolve(target, 'utils.js'), (pkg) => pkg.replace('../package.json', './package.json'));
diff --git a/test/core/crawlers/adaptive_playwright_crawler.test.ts b/test/core/crawlers/adaptive_playwright_crawler.test.ts
index 923fb9010..b16ea81d5 100644
--- a/test/core/crawlers/adaptive_playwright_crawler.test.ts
+++ b/test/core/crawlers/adaptive_playwright_crawler.test.ts
@@ -744,6 +744,17 @@ describe('AdaptivePlaywrightCrawler', () => {
).toThrow(/requires transactional storage/);
});
+ test('should name transactionalStorage in the validation error', () => {
+ expect(
+ () =>
+ new AdaptivePlaywrightCrawler({
+ // @ts-expect-error invalid value on purpose
+ transactionalStorage: 'yes',
+ requestHandler: async () => {},
+ }),
+ ).toThrow('at `transactionalStorage` in `AdaptivePlaywrightCrawlerOptions`');
+ });
+
test('should capture direct key-value store manipulation and commit it with the winning attempt', async () => {
const renderingTypePredictor = makeRiggedRenderingTypePredictor({
detectionProbabilityRecommendation: 0,
diff --git a/test/core/crawlers/basic_crawler.test.ts b/test/core/crawlers/basic_crawler.test.ts
index 77086ab38..f0f540864 100644
--- a/test/core/crawlers/basic_crawler.test.ts
+++ b/test/core/crawlers/basic_crawler.test.ts
@@ -36,6 +36,7 @@ import {
} from '@crawlee/basic';
import type { CalculatedStatistics, IConcurrencySystem, IStatistics } from '@crawlee/core';
import { ConcurrencySystem, Dataset, MemoryStorageBackend, RequestState, SessionPool, Statistics } from '@crawlee/core';
+import { BaseHttpClient } from '@crawlee/http-client';
import type { Dictionary, ISession, ProxyInfo } from '@crawlee/types';
import { RobotsTxtFile, sleep } from '@crawlee/utils';
import express from 'express';
@@ -2348,12 +2349,13 @@ describe('BasicCrawler', () => {
const captured: (boolean | undefined)[] = [];
const crawler = new BasicCrawler({
- httpClient: {
- async sendRequest(request, options) {
+ // Carries the BaseHttpClient prototype so the crawler's `z.instanceof` validation accepts it.
+ httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ async sendRequest(_request: globalThis.Request, options?: { ignoreTlsErrors?: boolean }) {
captured.push(options?.ignoreTlsErrors);
return new Response('ok');
},
- },
+ }),
async requestHandler({ sendRequest }) {
await sendRequest({}, { ignoreTlsErrors: true });
},
diff --git a/test/core/crawlers/cheerio_crawler.test.ts b/test/core/crawlers/cheerio_crawler.test.ts
index cfddf75a8..12379b61e 100644
--- a/test/core/crawlers/cheerio_crawler.test.ts
+++ b/test/core/crawlers/cheerio_crawler.test.ts
@@ -19,8 +19,9 @@ import {
serviceLocator,
SessionPool,
} from '@crawlee/core';
+import { BaseHttpClient } from '@crawlee/http-client';
import { ImpitHttpClient } from '@crawlee/impit-client';
-import type { Dictionary, ISession, ProxyInfo } from '@crawlee/types';
+import type { Dictionary, ISession, ProxyInfo, SendRequestOptions } from '@crawlee/types';
import { sleep } from '@crawlee/utils';
import iconv from 'iconv-lite';
import { CookieJar } from 'tough-cookie';
@@ -204,12 +205,13 @@ describe('CheerioCrawler', () => {
test('forwards ignoreTlsErrors to the http client', async () => {
const captured: (boolean | undefined)[] = [];
const fetchClient = new FetchHttpClient();
- const capturingClient = {
+ // Carries the BaseHttpClient prototype so the crawler's `z.instanceof` validation accepts it.
+ const capturingClient = Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
sendRequest: async (request: globalThis.Request, options?: { ignoreTlsErrors?: boolean }) => {
captured.push(options?.ignoreTlsErrors);
return fetchClient.sendRequest(request, options);
},
- };
+ });
const defaultCrawler = new CheerioCrawler({
httpClient: capturingClient,
@@ -1019,8 +1021,8 @@ describe('CheerioCrawler', () => {
proxyConfiguration,
requestHandler: () => {},
- httpClient: {
- sendRequest: async (request, opts) => {
+ httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ sendRequest: async (request: globalThis.Request, opts?: SendRequestOptions) => {
const proxyUrl = opts?.session?.proxyInfo?.url;
check({ ...opts, proxyUrl });
@@ -1030,7 +1032,7 @@ describe('CheerioCrawler', () => {
throw new Error('Proxy responded with 400 - Bad request');
},
- },
+ }),
});
await expect(crawler.run([serverAddress])).resolves.not.toThrow();
@@ -1053,8 +1055,8 @@ describe('CheerioCrawler', () => {
maxRequestRetries: 5,
requestHandler: async () => {},
failedRequestHandler,
- httpClient: {
- sendRequest: async (request, opts) => {
+ httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ sendRequest: async (request: globalThis.Request, opts?: SendRequestOptions) => {
const { session } = opts ?? {};
if (session?.proxyInfo?.url.includes('localhost')) {
numberOfRotations++;
@@ -1062,7 +1064,7 @@ describe('CheerioCrawler', () => {
}
return await impit.sendRequest(request);
},
- },
+ }),
});
await crawler.run([serverAddress]);
@@ -1082,15 +1084,15 @@ describe('CheerioCrawler', () => {
proxyConfiguration,
maxRequestRetries: 1,
requestHandler: async () => {},
- httpClient: {
- sendRequest: async (request, opts) => {
+ httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ sendRequest: async (request: globalThis.Request, opts?: SendRequestOptions) => {
const { session } = opts ?? {};
if (session?.proxyInfo?.url.includes('localhost')) {
throw new Error(proxyError);
}
return impit.sendRequest(request);
},
- },
+ }),
});
const spy = vitest.spyOn((crawler as any).log, 'warning' as any).mockImplementation(() => {});
diff --git a/test/core/crawlers/http_crawler.test.ts b/test/core/crawlers/http_crawler.test.ts
index 33c246929..0f6f815cd 100644
--- a/test/core/crawlers/http_crawler.test.ts
+++ b/test/core/crawlers/http_crawler.test.ts
@@ -12,7 +12,7 @@ import {
SessionPool,
ThrottlingRequestManager,
} from '@crawlee/http';
-import { ResponseWithUrl } from '@crawlee/http-client';
+import { BaseHttpClient, ResponseWithUrl } from '@crawlee/http-client';
import { sleep } from '@crawlee/utils';
import iconv from 'iconv-lite';
@@ -580,15 +580,15 @@ test('works with a custom HttpClient', async () => {
results.push(await (await sendRequest()).text());
},
- httpClient: {
- async sendRequest(request) {
+ httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ async sendRequest(request: Request) {
return new ResponseWithUrl('<html><head><title>Schmexample Domain</title></head></html>', {
url: request.url.toString(),
status: 200,
headers: { 'content-type': 'text/html; charset=utf-8' },
});
},
- },
+ }),
});
await crawler.run([url]);
diff --git a/test/core/enqueue_links/enqueue_links.test.ts b/test/core/enqueue_links/enqueue_links.test.ts
index de7372d42..11db1c9c0 100644
--- a/test/core/enqueue_links/enqueue_links.test.ts
+++ b/test/core/enqueue_links/enqueue_links.test.ts
@@ -625,7 +625,7 @@ describe('enqueueLinks()', () => {
requestManager: requestQueue,
originalRequestUrl: 'https://example.com',
}),
- ).rejects.toThrow();
+ ).rejects.toThrow(/at `include`/);
});
test('works with no include/exclude filters (enqueues all matching strategy)', async () => {
diff --git a/test/core/proxy_configuration.test.ts b/test/core/proxy_configuration.test.ts
index bc37ef1f7..0fc4c270d 100644
--- a/test/core/proxy_configuration.test.ts
+++ b/test/core/proxy_configuration.test.ts
@@ -1,4 +1,4 @@
-import { ProxyConfiguration } from '@crawlee/core';
+import { ArgumentValidationError, ProxyConfiguration } from '@crawlee/core';
describe('ProxyConfiguration', () => {
test('newUrl() should return proxy URL', async () => {
@@ -146,26 +146,16 @@ describe('ProxyConfiguration', () => {
}
});
- test('should throw proxyUrls array is empty', async () => {
- try {
- const proxyConfiguration = new ProxyConfiguration({
- proxyUrls: [],
- });
- throw new Error('wrong error');
- } catch (err) {
- expect((err as Error).message).toMatch('Expected property array `proxyUrls` to not be empty');
- }
+ test('should throw proxyUrls array is empty', () => {
+ const create = () => new ProxyConfiguration({ proxyUrls: [] });
+ expect(create).toThrow(ArgumentValidationError);
+ expect(create).toThrow(/Too small.*at `proxyUrls`/);
});
- test('should throw invalid custom URL form', async () => {
- try {
- const proxyConfiguration = new ProxyConfiguration({
- proxyUrls: ['http://proxy.com:1111*invalid_url'],
- });
- throw new Error('wrong error');
- } catch (err) {
- expect((err as Error).message).toMatch('to be a URL, got `http://proxy.com:1111*invalid_url`');
- }
+ test('should throw invalid custom URL form', () => {
+ const create = () => new ProxyConfiguration({ proxyUrls: ['http://proxy.com:1111*invalid_url'] });
+ expect(create).toThrow(ArgumentValidationError);
+ expect(create).toThrow(/at `proxyUrls\[0\]`/);
});
});
});
diff --git a/test/core/request_list.test.ts b/test/core/request_list.test.ts
index f3a93cf59..d2ea551b7 100644
--- a/test/core/request_list.test.ts
+++ b/test/core/request_list.test.ts
@@ -1,4 +1,5 @@
import {
+ ArgumentValidationError,
Configuration,
deserializeArray,
EventType,
@@ -11,6 +12,7 @@ import {
serviceLocator,
STATE_PERSISTENCE_KEY,
} from '@crawlee/core';
+import { BaseHttpClient } from '@crawlee/http-client';
import { sleep } from '@crawlee/utils';
import { beforeAll, type MockedFunction } from 'vitest';
@@ -28,24 +30,18 @@ function shuffle(array: unknown[]): unknown[] {
return out;
}
-let mockHttpClient = vitest.mockObject({
- async sendRequest(_request: any, _options?: any) {
- return new Response();
- },
- async stream() {
- return new Response();
- },
-});
+// `vitest.mockObject` clones the object and drops its prototype, so build the mock manually to
+// keep it an `instanceof BaseHttpClient`.
+const createMockHttpClient = () =>
+ Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ sendRequest: vitest.fn(async (_request?: any, _options?: any) => new Response()),
+ stream: vitest.fn(async () => new Response()),
+ });
+
+let mockHttpClient = createMockHttpClient();
beforeEach(async () => {
- mockHttpClient = vitest.mockObject({
- async sendRequest() {
- return new Response();
- },
- async stream() {
- return new Response();
- },
- });
+ mockHttpClient = createMockHttpClient();
});
describe('RequestList', () => {
@@ -670,29 +666,17 @@ describe('RequestList', () => {
expect(setValueSpy).not.toBeCalled();
});
- test('should throw on invalid parameters', async () => {
- const args = [[], ['x', {}], ['x', 6, {}], ['x', [], []]] as const;
- for (const arg of args) {
- try {
- // @ts-ignore
- await RequestList.open(...arg);
- throw new Error('wrong error');
- } catch (err) {
- const e = err as Error;
- expect(e.message).not.toBe('wrong error');
- if (/argument to be of type `string`/.exec(e.message)) {
- expect(e.message).toMatch('received type `undefined`');
- } else if (/argument to be of type `array`/.exec(e.message)) {
- const isMatched =
- /received type `Object`/.exec(e.message) ||
- /received type `number`/.exec(e.message) ||
- /received type `undefined`/.exec(e.message);
- expect(isMatched).toBeTruthy();
- } else if (/argument to be of type `null`/.exec(e.message)) {
- expect(e.message).toMatch('received type `undefined`');
- }
- }
- }
+ test.each([
+ [[], 'Invalid input: expected array'],
+ [['x', {}], 'Invalid input: expected array'],
+ [['x', 6, {}], 'Invalid input: expected array'],
+ [['x', [], []], 'Invalid input: expected object'],
+ [[6, []], 'Invalid input: expected string, received the number `6`'],
+ ])('open(...%j) should throw on invalid argument (%s)', async (args, message) => {
+ // @ts-expect-error JS-side validation
+ await expect(RequestList.open(...args)).rejects.toThrow(ArgumentValidationError);
+ // @ts-expect-error JS-side validation
+ await expect(RequestList.open(...args)).rejects.toThrow(message);
});
});
diff --git a/test/core/storages/dataset.test.ts b/test/core/storages/dataset.test.ts
index 1cda55522..a210088b6 100644
--- a/test/core/storages/dataset.test.ts
+++ b/test/core/storages/dataset.test.ts
@@ -1,4 +1,11 @@
-import { assertJsonSerializable, Dataset, KeyValueStore, MemoryStorageBackend, serviceLocator } from '@crawlee/core';
+import {
+ ArgumentValidationError,
+ assertJsonSerializable,
+ Dataset,
+ KeyValueStore,
+ MemoryStorageBackend,
+ serviceLocator,
+} from '@crawlee/core';
import type { Dictionary } from '@crawlee/types';
import { MAX_PAYLOAD_SIZE_BYTES } from '@apify/consts';
@@ -334,26 +341,19 @@ describe('dataset', () => {
describe('pushData', () => {
test('throws on invalid args', async () => {
const dataset = await Dataset.open();
+ const dataErrMsg = /Invalid input: expected object/;
// @ts-expect-error JS-side validation
- await expect(dataset.pushData()).rejects.toThrow(
- 'Expected `data` to be of type `object` but received type `undefined`',
- );
+ await expect(dataset.pushData()).rejects.toThrow(ArgumentValidationError);
// @ts-expect-error JS-side validation
- await expect(dataset.pushData('')).rejects.toThrow(
- 'Expected `data` to be of type `object` but received type `string`',
- );
+ await expect(dataset.pushData()).rejects.toThrow(dataErrMsg);
// @ts-expect-error JS-side validation
- await expect(dataset.pushData(123)).rejects.toThrow(
- 'Expected `data` to be of type `object` but received type `number`',
- );
+ await expect(dataset.pushData('')).rejects.toThrow(dataErrMsg);
// @ts-expect-error JS-side validation
- await expect(dataset.pushData(true)).rejects.toThrow(
- 'Expected `data` to be of type `object` but received type `boolean`',
- );
+ await expect(dataset.pushData(123)).rejects.toThrow(dataErrMsg);
// @ts-expect-error JS-side validation
- await expect(dataset.pushData(false)).rejects.toThrow(
- 'Expected `data` to be of type `object` but received type `boolean`',
- );
+ await expect(dataset.pushData(true)).rejects.toThrow(dataErrMsg);
+ // @ts-expect-error JS-side validation
+ await expect(dataset.pushData(false)).rejects.toThrow(dataErrMsg);
await expect(dataset.pushData(() => {})).rejects.toThrow(
'Data item at index 0 is not an object. You can push only objects into a dataset.',
);
diff --git a/test/core/storages/key_value_store.test.ts b/test/core/storages/key_value_store.test.ts
index ea171c0d8..328b66923 100644
--- a/test/core/storages/key_value_store.test.ts
+++ b/test/core/storages/key_value_store.test.ts
@@ -1,6 +1,6 @@
import { PassThrough } from 'node:stream';
-import { KeyValueStore, MemoryStorageBackend, serviceLocator } from '@crawlee/core';
+import { ArgumentValidationError, KeyValueStore, MemoryStorageBackend, serviceLocator } from '@crawlee/core';
import type { Dictionary } from '@crawlee/types';
import { toBuffer } from '../../../packages/core/src/byte_utils.js';
@@ -10,6 +10,9 @@ beforeEach(async () => {
});
describe('KeyValueStore', () => {
+ const keyStringErrMsg = /Invalid input: expected string/;
+ const keyEmptyErrMsg = /Too small/;
+
beforeEach(async () => {
vitest.clearAllMocks();
});
@@ -93,18 +96,14 @@ describe('KeyValueStore', () => {
const store = await KeyValueStore.open();
// @ts-expect-error JS-side validation
- await expect(store.getValue()).rejects.toThrow(
- 'Expected argument to be of type `string` but received type `undefined`',
- );
+ await expect(store.getValue()).rejects.toThrow(ArgumentValidationError);
// @ts-expect-error JS-side validation
- await expect(store.getValue({})).rejects.toThrow(
- 'Expected argument to be of type `string` but received type `Object`',
- );
+ await expect(store.getValue()).rejects.toThrow(keyStringErrMsg);
// @ts-expect-error JS-side validation
- await expect(store.getValue(null)).rejects.toThrow(
- 'Expected argument to be of type `string` but received type `null`',
- );
- await expect(store.getValue('')).rejects.toThrow('Expected string to not be empty');
+ await expect(store.getValue({})).rejects.toThrow(keyStringErrMsg);
+ // @ts-expect-error JS-side validation
+ await expect(store.getValue(null)).rejects.toThrow(keyStringErrMsg);
+ await expect(store.getValue('')).rejects.toThrow(keyEmptyErrMsg);
});
test('KeyValueStore.getValue()', async () => {
@@ -128,18 +127,14 @@ describe('KeyValueStore', () => {
const store = await KeyValueStore.open();
// @ts-expect-error JS-side validation
- await expect(store.recordExists()).rejects.toThrow(
- 'Expected argument to be of type `string` but received type `undefined`',
- );
+ await expect(store.recordExists()).rejects.toThrow(ArgumentValidationError);
// @ts-expect-error JS-side validation
- await expect(store.recordExists({})).rejects.toThrow(
- 'Expected argument to be of type `string` but received type `Object`',
- );
+ await expect(store.recordExists()).rejects.toThrow(keyStringErrMsg);
// @ts-expect-error JS-side validation
- await expect(store.recordExists(null)).rejects.toThrow(
- 'Expected argument to be of type `string` but received type `null`',
- );
- await expect(store.recordExists('')).rejects.toThrow('Expected string to not be empty');
+ await expect(store.recordExists({})).rejects.toThrow(keyStringErrMsg);
+ // @ts-expect-error JS-side validation
+ await expect(store.recordExists(null)).rejects.toThrow(keyStringErrMsg);
+ await expect(store.recordExists('')).rejects.toThrow(keyEmptyErrMsg);
});
test('KeyValueStore.recordExists()', async () => {
@@ -158,19 +153,15 @@ describe('KeyValueStore', () => {
const store = await KeyValueStore.open();
// @ts-expect-error JS-side validation
- await expect(store.setValue()).rejects.toThrow(
- 'Expected `key` to be of type `string` but received type `undefined`',
- );
- await expect(store.setValue('', null)).rejects.toThrow('Expected string `key` to not be empty');
- await expect(store.setValue('', 'some value')).rejects.toThrow('Expected string `key` to not be empty');
+ await expect(store.setValue()).rejects.toThrow(ArgumentValidationError);
// @ts-expect-error JS-side validation
- await expect(store.setValue({}, 'some value')).rejects.toThrow(
- 'Expected `key` to be of type `string` but received type `Object`',
- );
+ await expect(store.setValue()).rejects.toThrow(keyStringErrMsg);
+ await expect(store.setValue('', null)).rejects.toThrow(keyEmptyErrMsg);
+ await expect(store.setValue('', 'some value')).rejects.toThrow(keyEmptyErrMsg);
// @ts-expect-error JS-side validation
- await expect(store.setValue(123, 'some value')).rejects.toThrow(
- 'Expected `key` to be of type `string` but received type `number`',
- );
+ await expect(store.setValue({}, 'some value')).rejects.toThrow(keyStringErrMsg);
+ // @ts-expect-error JS-side validation
+ await expect(store.setValue(123, 'some value')).rejects.toThrow(keyStringErrMsg);
const valueErrMsg =
'The "value" parameter must be a String, Buffer, ArrayBuffer, TypedArray, or Stream when "options.contentType" is specified';
@@ -178,18 +169,15 @@ describe('KeyValueStore', () => {
await expect(store.setValue('key', 12345, { contentType: 'image/png' })).rejects.toThrow(valueErrMsg);
await expect(store.setValue('key', () => {}, { contentType: 'image/png' })).rejects.toThrow(valueErrMsg);
+ const optionsObjectErrMsg = /Invalid input: expected object/;
// @ts-expect-error JS-side validation
- await expect(store.setValue('key', {}, 123)).rejects.toThrow(
- 'Expected argument to be of type `object` but received type `number`',
- );
+ await expect(store.setValue('key', {}, 123)).rejects.toThrow(ArgumentValidationError);
// @ts-expect-error JS-side validation
- await expect(store.setValue('key', {}, 'bla/bla')).rejects.toThrow(
- 'Expected argument to be of type `object` but received type `string`',
- );
+ await expect(store.setValue('key', {}, 123)).rejects.toThrow(optionsObjectErrMsg);
// @ts-expect-error JS-side validation
- await expect(store.setValue('key', {}, true)).rejects.toThrow(
- 'Expected argument to be of type `object` but received type `boolean`',
- );
+ await expect(store.setValue('key', {}, 'bla/bla')).rejects.toThrow(optionsObjectErrMsg);
+ // @ts-expect-error JS-side validation
+ await expect(store.setValue('key', {}, true)).rejects.toThrow(optionsObjectErrMsg);
const circularObj = {} as Dictionary;
circularObj.xxx = circularObj;
@@ -203,31 +191,28 @@ describe('KeyValueStore', () => {
// @ts-expect-error JS-side validation
await expect(store.setValue('key')).rejects.toThrow(undefinedErrMsg);
- const contTypeRedundantErrMsg = 'Expected property string `contentType` to not be empty in object';
+ const contTypeStringErrMsg = /Invalid input: expected string.*at `contentType`/;
+ const contTypeEmptyErrMsg = /Too small.*at `contentType`/;
await expect(store.setValue('key', null, { contentType: 'image/png' })).rejects.toThrow(
'The "value" parameter must be a String, Buffer, ArrayBuffer, TypedArray, or Stream when "options.contentType" is specified.',
);
- await expect(store.setValue('key', null, { contentType: '' })).rejects.toThrow(contTypeRedundantErrMsg);
+ await expect(store.setValue('key', null, { contentType: '' })).rejects.toThrow(contTypeEmptyErrMsg);
// @ts-expect-error Type '{}' is not assignable to type 'string'.
await expect(store.setValue('key', null, { contentType: {} })).rejects.toThrow(
'The "value" parameter must be a String, Buffer, ArrayBuffer, TypedArray, or Stream when "options.contentType" is specified.',
);
// @ts-expect-error Type 'number' is not assignable to type 'string'.
- await expect(store.setValue('key', 'value', { contentType: 123 })).rejects.toThrow(
- 'Expected property `contentType` to be of type `string` but received type `number` in object',
- );
+ await expect(store.setValue('key', 'value', { contentType: 123 })).rejects.toThrow(ArgumentValidationError);
+ // @ts-expect-error Type 'number' is not assignable to type 'string'.
+ await expect(store.setValue('key', 'value', { contentType: 123 })).rejects.toThrow(contTypeStringErrMsg);
// @ts-expect-error Type '{}' is not assignable to type 'string'.
- await expect(store.setValue('key', 'value', { contentType: {} })).rejects.toThrow(
- 'Expected property `contentType` to be of type `string` but received type `Object` in object',
- );
+ await expect(store.setValue('key', 'value', { contentType: {} })).rejects.toThrow(contTypeStringErrMsg);
// @ts-expect-error Type 'Date' is not assignable to type 'string'.
await expect(store.setValue('key', 'value', { contentType: new Date() })).rejects.toThrow(
- 'Expected property `contentType` to be of type `string` but received type `Date` in object',
- );
- await expect(store.setValue('key', 'value', { contentType: '' })).rejects.toThrow(
- 'Expected property string `contentType` to not be empty in object',
+ contTypeStringErrMsg,
);
+ await expect(store.setValue('key', 'value', { contentType: '' })).rejects.toThrow(contTypeEmptyErrMsg);
});
test('throws on invalid key', async () => {
@@ -236,13 +221,13 @@ describe('KeyValueStore', () => {
const INVALID_CHARACTERS = '?|\\/"*<>%:';
for (const char of INVALID_CHARACTERS) {
const key = `my_id_${char}`;
- const err = `The "key" argument "${key}" must be at most 256 characters`;
+ const err = `The "key" argument must be at most 256 characters long and only contain the following characters: a-zA-Z0-9!-_.'(), got \`${key}\``;
await expect(store.setValue(key, 'value')).rejects.toThrow(err);
}
- // test max length
+ // test max length; the received value is elided at 200 characters
const longKey = 'X'.repeat(257);
- const err = `The "key" argument "${longKey}" must be at most 256 characters`;
+ const err = `The "key" argument must be at most 256 characters long and only contain the following characters: a-zA-Z0-9!-_.'(), got \`${'X'.repeat(200)}… (57 more characters)\``;
await expect(store.setValue(longKey, '...')).rejects.toThrow(err);
});
diff --git a/test/core/storages/request_queue.test.ts b/test/core/storages/request_queue.test.ts
index fd298f569..e693037ef 100644
--- a/test/core/storages/request_queue.test.ts
+++ b/test/core/storages/request_queue.test.ts
@@ -1,26 +1,21 @@
/* eslint-disable dot-notation */
import { MemoryStorageBackend, ProxyConfiguration, Request, RequestQueue, serviceLocator } from '@crawlee/core';
+import { BaseHttpClient } from '@crawlee/http-client';
import { sleep } from '@crawlee/utils';
-let mockHttpClient = vitest.mockObject({
- async sendRequest(_request: any, _options?: any) {
- return new Response();
- },
- async stream() {
- return new Response();
- },
-});
+// `vitest.mockObject` clones the object and drops its prototype, so build the mock manually to
+// keep it an `instanceof BaseHttpClient`.
+const createMockHttpClient = () =>
+ Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ sendRequest: vitest.fn(async (_request?: any, _options?: any) => new Response()),
+ stream: vitest.fn(async () => new Response()),
+ });
+
+let mockHttpClient = createMockHttpClient();
beforeEach(async () => {
- mockHttpClient = vitest.mockObject({
- async sendRequest() {
- return new Response();
- },
- async stream() {
- return new Response();
- },
- });
+ mockHttpClient = createMockHttpClient();
});
describe('RequestQueue remote', () => {
diff --git a/test/core/storages/storage_manager.test.ts b/test/core/storages/storage_manager.test.ts
index 69b284d54..29f4d1115 100644
--- a/test/core/storages/storage_manager.test.ts
+++ b/test/core/storages/storage_manager.test.ts
@@ -7,12 +7,15 @@ beforeEach(async () => {
describe('StorageManager', () => {
test('failed openStorage call does not block subsequent calls (#3661)', async () => {
const goodBackend = serviceLocator.getStorageBackend();
- const failingBackend = {
- ...goodBackend,
+ // Delegate to the real backend via the prototype chain so the mock still satisfies
+ // the StorageBackend interface validation.
+ const failingBackend = Object.assign(Object.create(goodBackend), {
createDatasetBackend: () => {
throw new Error('boom');
},
- };
+ // The inherited method reads a private field that only the real instance carries.
+ getStorageBackendCacheKey: () => 'FailingBackend',
+ });
await expect(Dataset.open('will-fail', { storageBackend: failingBackend as any })).rejects.toThrow('boom');
diff --git a/test/core/storages/storage_transaction.test.ts b/test/core/storages/storage_transaction.test.ts
index c63ab61b2..f191c72a4 100644
--- a/test/core/storages/storage_transaction.test.ts
+++ b/test/core/storages/storage_transaction.test.ts
@@ -12,6 +12,7 @@ import {
withDirectStorageAccess,
withStorageTransaction,
} from '@crawlee/core';
+import { BaseHttpClient } from '@crawlee/http-client';
import { storage as timeoutStorage } from '@apify/timeout';
@@ -835,17 +836,14 @@ describe('RequestQueue in a transaction', () => {
'http://example.com/list-1': ['https://example.com/a', 'https://example.com/b'],
'http://example.com/list-2': ['https://example.com/c'],
};
- const httpClient = vitest.mockObject({
- async sendRequest(_request: any, _options?: any) {
- return new Response();
- },
- async stream() {
- return new Response();
- },
- });
- httpClient.sendRequest.mockImplementation(async (request: { url: string }) => {
+ // Carries the BaseHttpClient prototype so the queue's `z.instanceof` validation accepts it.
+ const sendRequest = vitest.fn(async (request: { url: string }) => {
return new Response(lists[request.url]?.join('\n') ?? '');
});
+ const httpClient = Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ sendRequest,
+ stream: vitest.fn(async () => new Response()),
+ });
// There is no `enqueuedUrlLists` on the view - the list is downloaded at call time and the
// *fetched* URLs are journaled, under either policy.
diff --git a/test/utils/extract-urls.test.ts b/test/utils/extract-urls.test.ts
index f4b40eb86..071cbdbcc 100644
--- a/test/utils/extract-urls.test.ts
+++ b/test/utils/extract-urls.test.ts
@@ -1,7 +1,7 @@
import fs from 'node:fs';
import path from 'node:path';
-import type { BaseHttpClient } from '@crawlee/types';
+import { BaseHttpClient } from '@crawlee/http-client';
import { URL_WITH_COMMAS_REGEX } from '@crawlee/utils/internal';
import { downloadListOfUrls, extractUrls } from '@crawlee/utils';
@@ -15,11 +15,11 @@ describe('downloadListOfUrls()', () => {
.split(/[\r\n]+/g)
.map((u) => u.trim());
- const mockClient: BaseHttpClient = {
+ const mockClient = Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
async sendRequest() {
return new Response(text);
},
- };
+ });
await expect(
downloadListOfUrls({
diff --git a/test/utils/validation.test.ts b/test/utils/validation.test.ts
new file mode 100644
index 000000000..01b24fc07
--- /dev/null
+++ b/test/utils/validation.test.ts
@@ -0,0 +1,248 @@
+import { BasicCrawler } from '@crawlee/basic';
+import { ProxyConfiguration } from '@crawlee/core';
+import { ArgumentValidationError, parseArgument, schemas } from '@crawlee/utils/internal';
+import { z } from 'zod';
+
+class Foo {
+ a = 1;
+ b = 2;
+}
+
+const callableObject = Object.assign(() => {}, { a: 1, b: 2 });
+
+describe('schemas', () => {
+ describe('anyObject', () => {
+ test.each([
+ ['plain object', {}],
+ ['class instance', new Foo()],
+ ['array', [1, 2, 3]],
+ ['function', () => {}],
+ ['callable object', callableObject],
+ ])('accepts %s', (_, value) => {
+ expect(schemas.anyObject.safeParse(value).success).toBe(true);
+ });
+
+ test.each([
+ ['null', null],
+ ['undefined', undefined],
+ ['string', 'foo'],
+ ['number', 123],
+ ['boolean', true],
+ ['symbol', Symbol('foo')],
+ ])('rejects %s', (_, value) => {
+ expect(schemas.anyObject.safeParse(value).success).toBe(false);
+ });
+ });
+
+ describe('objectWithKeys', () => {
+ const schema = schemas.objectWithKeys(['a', 'b']);
+
+ test.each([
+ ['plain object with both keys', { a: 1, b: 2 }],
+ ['callable object with both keys', callableObject],
+ ['class instance with both keys', new Foo()],
+ ['object with inherited keys', Object.create({ a: 1, b: 1 })],
+ ])('accepts %s', (_, value) => {
+ expect(schema.safeParse(value).success).toBe(true);
+ });
+
+ test.each([
+ ['object missing a key', { a: 1 }],
+ ['null', null],
+ ['string', 'ab'],
+ ['number', 1],
+ ['boolean', true],
+ ['empty array', []],
+ ])('rejects %s', (_, value) => {
+ expect(schema.safeParse(value).success).toBe(false);
+ });
+ });
+
+ describe('anyNumber', () => {
+ test.each([
+ ['zero', 0],
+ ['negative float', -1.5],
+ ['Infinity', Infinity],
+ ['-Infinity', -Infinity],
+ ['Number.MAX_VALUE', Number.MAX_VALUE],
+ ])('accepts %s', (_, value) => {
+ expect(schemas.anyNumber.safeParse(value).success).toBe(true);
+ });
+
+ test.each([
+ ['NaN', NaN],
+ ['numeric string', '5'],
+ ['null', null],
+ ['undefined', undefined],
+ ['bigint', BigInt(1)],
+ ])('rejects %s', (_, value) => {
+ expect(schemas.anyNumber.safeParse(value).success).toBe(false);
+ });
+ });
+
+ describe('anyArray', () => {
+ test.each([
+ ['empty array', []],
+ ['mixed array', [1, 'a', null, {}]],
+ ])('accepts %s', (_, value) => {
+ expect(schemas.anyArray.safeParse(value).success).toBe(true);
+ });
+
+ test.each([
+ ['array-like object', { length: 0 }],
+ ['string', 'abc'],
+ ['null', null],
+ ])('rejects %s', (_, value) => {
+ expect(schemas.anyArray.safeParse(value).success).toBe(false);
+ });
+ });
+
+ describe('anyFunction', () => {
+ test.each([
+ ['function declaration', function foo() {}],
+ ['arrow function', () => {}],
+ ['class', Foo],
+ ])('accepts %s', (_, value) => {
+ expect(schemas.anyFunction.safeParse(value).success).toBe(true);
+ });
+
+ test.each([
+ ['plain object', {}],
+ ['array', []],
+ ['null', null],
+ ])('rejects %s', (_, value) => {
+ expect(schemas.anyFunction.safeParse(value).success).toBe(false);
+ });
+ });
+});
+
+describe('parseArgument', () => {
+ test('throws ArgumentValidationError naming the received value', () => {
+ let error!: ArgumentValidationError;
+ try {
+ parseArgument('not an object', schemas.anyObject);
+ } catch (err) {
+ error = err as ArgumentValidationError;
+ }
+
+ expect(error).toBeInstanceOf(ArgumentValidationError);
+ expect(error).toBeInstanceOf(Error);
+ expect(error.name).toBe('ArgumentValidationError');
+ expect(error.message).toBe('Invalid input: expected object, received the string `not an object`');
+ expect(error.cause).toBeInstanceOf(z.ZodError);
+ expect(error.issues).toBe(error.cause.issues);
+ expect(error.issues.length).toBeGreaterThan(0);
+ });
+
+ test('message names the offending field and the value it received', () => {
+ const schema = z
+ .object({
+ countryCode: z.string().regex(/^[A-Z]{2}$/),
+ retries: z.number().optional(),
+ })
+ .strict();
+
+ expect(() => parseArgument({ countryCode: 'CZE' }, schema)).toThrow(
+ 'Invalid string: must match pattern /^[A-Z]{2}$/ at `countryCode`, got `CZE`',
+ );
+ });
+
+ test('message folds the received type and value into one clause', () => {
+ expect(() => parseArgument({ retries: 'three' }, z.strictObject({ retries: schemas.anyNumber }))).toThrow(
+ 'Invalid input: expected number, received the string `three` at `retries`',
+ );
+
+ // `NaN` is named as itself, not as the self-contradictory "received number".
+ expect(() => parseArgument(Number.NaN, schemas.anyNumber)).toThrow(
+ 'Invalid input: expected number, received NaN',
+ );
+
+ // An empty string would render as bare backticks — made visible instead.
+ expect(() => parseArgument('', schemas.anyNumber)).toThrow(
+ 'Invalid input: expected number, received an empty string',
+ );
+
+ // Long strings are elided rather than dumped whole into the message.
+ expect(() => parseArgument('a'.repeat(250), schemas.anyNumber)).toThrow(
+ `Invalid input: expected number, received the string \`${'a'.repeat(200)}… (50 more characters)\``,
+ );
+ });
+
+ test('arrayOf names the element type at the top level and per element', () => {
+ const schema = z.strictObject({ codes: schemas.arrayOf(schemas.anyNumber, 'numbers') });
+
+ expect(() => parseArgument({ codes: 500 }, schema)).toThrow(
+ 'Invalid input: expected an array of numbers, received the number `500` at `codes`',
+ );
+ // Element failures keep zod's per-index messages.
+ expect(() => parseArgument({ codes: [500, 'x'] }, schema)).toThrow(
+ 'Invalid input: expected number, received the string `x` at `codes[1]`',
+ );
+ expect(() => parseArgument({ codes: [500] }, schema)).not.toThrow();
+ });
+
+ test('label names the validated interface on every line', () => {
+ const schema = z.strictObject({ retries: schemas.anyNumber, name: z.string() });
+
+ expect(() => parseArgument({ retries: 'three', name: 7 }, schema, 'ExampleOptions')).toThrow(
+ 'Invalid input: expected number, received the string `three` at `retries` in `ExampleOptions`\n' +
+ 'Invalid input: expected string, received the number `7` at `name` in `ExampleOptions`',
+ );
+ });
+
+ test('returns its input for custom schemas', () => {
+ const obj = { foo: 'bar' };
+ expect(parseArgument(obj, schemas.anyObject)).toBe(obj);
+ const arr = [1, 2];
+ expect(parseArgument(arr, schemas.anyArray)).toBe(arr);
+ });
+
+ test('returns typed parsed output for object schemas', () => {
+ const options = { desc: true, limit: 10, offset: 0 };
+ const parsed: z.output<typeof schemas.datasetListItemsOptions> = parseArgument(
+ options,
+ schemas.datasetListItemsOptions,
+ );
+ expect(parsed).toEqual(options);
+ });
+
+ test('applies schema defaults in the returned value', () => {
+ const schema = z.strictObject({ limit: z.number().default(42) });
+ expect(parseArgument({}, schema)).toEqual({ limit: 42 });
+ });
+});
+
+describe('ow parity in crawler options', () => {
+ test('anyNumber accepts Infinity', () => {
+ expect(schemas.anyNumber.safeParse(Infinity).success).toBe(true);
+ });
+
+ test('BasicCrawler accepts Infinity for numeric options', () => {
+ expect(
+ () =>
+ new BasicCrawler({
+ requestHandler: async () => {},
+ maxConcurrency: Infinity,
+ maxRequestsPerMinute: Infinity,
+ }),
+ ).not.toThrow();
+ });
+
+ test('BasicCrawler throws ArgumentValidationError for an unknown key', () => {
+ const create = () => new BasicCrawler({ unknownOption: true } as any);
+ expect(create).toThrow(ArgumentValidationError);
+ expect(create).toThrow('Unrecognized key: "unknownOption"');
+ });
+
+ test('BasicCrawler throws ArgumentValidationError for NaN', () => {
+ const create = () => new BasicCrawler({ requestHandler: async () => {}, maxConcurrency: NaN });
+ expect(create).toThrow(ArgumentValidationError);
+ expect(create).toThrow('Invalid input: expected number, received NaN at `maxConcurrency`');
+ });
+
+ test('ProxyConfiguration throws ArgumentValidationError for an unknown key', () => {
+ const create = () => new ProxyConfiguration({ unknownOption: true } as any);
+ expect(create).toThrow(ArgumentValidationError);
+ expect(create).toThrow('Unrecognized key: "unknownOption"');
+ });
+});