@crawlee/basic 4.0.0-beta.13 → 4.0.0-beta.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,35 @@
1
- import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, AutoscaledPoolOptions, BaseHttpClient, CrawlingContext, DatasetExportOptions, EventManager, FinalStatistics, GetUserDataFromRequest, IRequestList, ProxyConfiguration, ProxyInfo, Request, RequestOptions, RouterHandler, RouterRoutes, Session, SessionPoolOptions, SkippedRequestCallback, Source, StatisticsOptions, StatisticState } from '@crawlee/core';
2
- import { AutoscaledPool, Configuration, ContextPipeline, Dataset, RequestProvider, SessionPool, Statistics } from '@crawlee/core';
3
- import type { Awaitable, Dictionary, SetStatusMessageOptions } from '@crawlee/types';
1
+ import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, ConcurrencySystemOptions, CrawleeLogger, CrawlingContext, DatasetExportOptions, EnqueueUrlsOptions, FinalStatistics, GetUserDataFromRequest, IConcurrencySystem, IProxyConfiguration, IRequestLoader, IRequestManager, IStatistics, RequestsLike, RouterHandler, RouterRoutes, SkippedRequestCallback, Source, StatisticState, StorageIdentifier, StorageWritePolicy, TaskLoopPredicates, TypedRequestsLike } from '@crawlee/core';
2
+ import { ConcurrencySystem, Configuration, ContextPipeline, Request, Dataset, EventManager, RequestQueue } from '@crawlee/core';
3
+ import { BaseHttpClient } from '@crawlee/http-client';
4
+ import type { Awaitable, Dictionary, ISession, ISessionPool, ProxyInfo, SetStatusMessageOptions, StorageBackend } from '@crawlee/types';
4
5
  import { RobotsTxtFile } from '@crawlee/utils';
5
6
  import type { ReadonlyDeep } from 'type-fest';
6
- import type { Log } from '@apify/log';
7
+ import { z } from 'zod';
7
8
  import { TimeoutError } from '@apify/timeout';
8
9
  export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary> extends CrawlingContext<UserData> {
9
10
  }
11
+ export { navigationDeadlineKey, remainingNavigationWindowMillis } from './request-timeout.js';
10
12
  export type RequestHandler<Context extends CrawlingContext = CrawlingContext> = (inputs: Context) => Awaitable<void>;
11
- export type ErrorHandler<Context extends CrawlingContext = CrawlingContext, ExtendedContext extends Context = Context> = (inputs: Context & Partial<ExtendedContext>, error: Error) => Awaitable<void>;
12
- export interface StatusMessageCallbackParams<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any> = BasicCrawler<Context>> {
13
+ /**
14
+ * An error handler receives the crawling context and the error that was thrown while processing the request.
15
+ *
16
+ * Unlike the {@link RequestHandler}, an error handler may run before the context pipeline has finished
17
+ * building the full context (e.g. when navigation or session setup fails). Therefore only `BaseContext` is
18
+ * guaranteed to be present, while the extra properties added by the pipeline and `extendContext` (the
19
+ * difference between `BaseContext` and `ExtendedContext`) are only available as a `Partial`.
20
+ */
21
+ export type ErrorHandler<BaseContext extends CrawlingContext = CrawlingContext, ExtendedContext extends BaseContext = BaseContext> = (inputs: BaseContext & Partial<ExtendedContext>, error: Error) => Awaitable<void>;
22
+ export interface StatusMessageCallbackParams<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any, any, any, any> = BasicCrawler<Context>> {
13
23
  state: StatisticState;
14
24
  crawler: Crawler;
15
25
  previousState: StatisticState;
16
26
  message: string;
17
27
  }
18
- export type StatusMessageCallback<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any> = BasicCrawler<Context>> = (params: StatusMessageCallbackParams<Context, Crawler>) => Awaitable<void>;
28
+ export type StatusMessageCallback<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any, any, any, any> = BasicCrawler<Context>> = (params: StatusMessageCallbackParams<Context, Crawler>) => Awaitable<void>;
19
29
  export type RequireContextPipeline<DefaultContextType extends CrawlingContext, FinalContextType extends DefaultContextType> = DefaultContextType extends FinalContextType ? {} : {
20
30
  contextPipelineBuilder: () => ContextPipeline<CrawlingContext, FinalContextType>;
21
31
  };
22
- export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingContext, ContextExtension = {}, ExtendedContext extends Context = Context & ContextExtension> {
32
+ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingContext, ContextExtension = Dictionary<never>, ExtendedContext extends Context = Context & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>, StatisticStateExtension extends object = {}> {
23
33
  /**
24
34
  * User-provided function that performs the logic of the crawler. It is called for each URL to crawl.
25
35
  *
@@ -37,9 +47,15 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
37
47
  * The exceptions are logged to the request using the
38
48
  * {@link Request.pushErrorMessage|`Request.pushErrorMessage()`} function.
39
49
  */
40
- requestHandler?: RequestHandler<ExtendedContext>;
50
+ requestHandler?: RouterHandler<ExtendedContext, Routes> | RequestHandler<ExtendedContext>;
41
51
  /**
42
- * Allows the user to extend the crawling context passed to the request handler with custom functionality.
52
+ * Allows the user to extend the crawling context with custom functionality (helpers, references, etc.).
53
+ *
54
+ * `extendContext` runs *before* navigation, so the returned members are visible to the
55
+ * `preNavigationHooks`, `postNavigationHooks`, and the `requestHandler` alike. As a consequence,
56
+ * the `context` passed to `extendContext` is the pre-navigation {@link CrawlingContext} and does
57
+ * **not** include navigation-dependent members (e.g. `page`, `response`, `$`, `body`). If you need
58
+ * those, use a `postNavigationHook` or the `requestHandler` instead.
43
59
  *
44
60
  * **Example usage:**
45
61
  *
@@ -59,7 +75,7 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
59
75
  * });
60
76
  * ```
61
77
  */
62
- extendContext?: (context: Context) => Awaitable<ContextExtension>;
78
+ extendContext?: (context: CrawlingContext) => Awaitable<ContextExtension>;
63
79
  /**
64
80
  * *Intended for BasicCrawler subclasses*. Prepares a context pipeline that transforms the initial crawling context into the shape given by the `Context` type parameter.
65
81
  *
@@ -68,18 +84,27 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
68
84
  contextPipelineBuilder?: () => ContextPipeline<CrawlingContext, Context>;
69
85
  /**
70
86
  * Static list of URLs to be processed.
71
- * If not provided, the crawler will open the default request queue when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called.
72
- * > Alternatively, `requests` parameter of {@link BasicCrawler.run|`crawler.run()`} could be used to enqueue the initial requests -
73
- * it is a shortcut for running `crawler.addRequests()` before the `crawler.run()`.
87
+ *
88
+ * @deprecated Use the `requestManager` option instead. To combine a read-only loader (such as a `RequestList`)
89
+ * with a writable queue, build a tandem with {@link IRequestLoader.toTandem|`requestList.toTandem(requestQueue)`}
90
+ * and pass the result as `requestManager`. When both `requestList` and `requestQueue` are provided, they are
91
+ * combined into a tandem automatically.
74
92
  */
75
- requestList?: IRequestList;
93
+ requestList?: IRequestLoader;
76
94
  /**
77
95
  * Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
78
- * If not provided, the crawler will open the default request queue when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called.
79
- * > Alternatively, `requests` parameter of {@link BasicCrawler.run|`crawler.run()`} could be used to enqueue the initial requests -
80
- * it is a shortcut for running `crawler.addRequests()` before the `crawler.run()`.
96
+ *
97
+ * @deprecated Use the `requestManager` option instead. A `RequestQueue` is itself a request manager, so you can
98
+ * pass it directly as `requestManager`.
99
+ */
100
+ requestQueue?: RequestQueue;
101
+ /**
102
+ * Manager of requests that should be processed by the crawler. Mutually exclusive with the deprecated
103
+ * `requestQueue` and `requestList` options.
104
+ *
105
+ * If not provided, the crawler will open the default {@link RequestQueue} when it is first needed.
81
106
  */
82
- requestQueue?: RequestProvider;
107
+ requestManager?: IRequestManager;
83
108
  /**
84
109
  * Timeout in which the function passed as {@link BasicCrawlerOptions.requestHandler|`requestHandler`} needs to finish, in seconds.
85
110
  * @default 60
@@ -106,27 +131,20 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
106
131
  failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
107
132
  /**
108
133
  * Specifies the maximum number of retries allowed for a request if its processing fails.
109
- * This includes retries due to navigation errors or errors thrown from user-supplied functions
110
- * (`requestHandler`, `preNavigationHooks`, `postNavigationHooks`).
111
- *
112
- * This limit does not apply to retries triggered by session rotation
113
- * (see {@link BasicCrawlerOptions.maxSessionRotations|`maxSessionRotations`}).
134
+ * This includes retries due to navigation errors, session/proxy errors, or errors thrown from user-supplied
135
+ * functions (`requestHandler`, `preNavigationHooks`, `postNavigationHooks`).
114
136
  * @default 3
115
137
  */
116
138
  maxRequestRetries?: number;
117
139
  /**
118
- * Indicates how much time (in seconds) to wait before crawling another same domain request.
140
+ * Indicates how much time (in seconds) to wait before crawling another same domain request. Subdomains are
141
+ * paced together with the site they belong to.
142
+ *
143
+ * Wraps the crawler's request manager in a {@link ThrottlingRequestManager}; pass one as `requestManager`
144
+ * yourself to configure it further.
119
145
  * @default 0
120
146
  */
121
147
  sameDomainDelaySecs?: number;
122
- /**
123
- * Maximum number of session rotations per request.
124
- * The crawler will automatically rotate the session in case of a proxy error or if it gets blocked by the website.
125
- *
126
- * The session rotations are not counted towards the {@link BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} limit.
127
- * @default 10
128
- */
129
- maxSessionRotations?: number;
130
148
  /**
131
149
  * Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.
132
150
  * This value should always be set in order to prevent infinite loops in misconfigured crawlers.
@@ -134,29 +152,56 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
134
152
  */
135
153
  maxRequestsPerCrawl?: number;
136
154
  /**
137
- * Custom options passed to the underlying {@link AutoscaledPool} constructor.
138
- * > *NOTE:* The {@link AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`}
139
- * and {@link AutoscaledPoolOptions.isTaskReadyFunction|`isTaskReadyFunction`} options
140
- * are provided by the crawler and cannot be overridden.
141
- * However, we can provide a custom implementation of {@link AutoscaledPoolOptions.isFinishedFunction|`isFinishedFunction`}.
155
+ * Maximum depth of the crawl. If not set, the crawl will continue until all requests are processed.
156
+ * Setting this to `0` will only process the initial requests, skipping all links enqueued by `crawlingContext.enqueueLinks` and `crawlingContext.addRequests`.
157
+ * Passing `1` will process the initial requests and all links enqueued by `crawlingContext.enqueueLinks` and `crawlingContext.addRequests` in the handler for initial requests.
158
+ */
159
+ maxCrawlDepth?: number;
160
+ /**
161
+ * Lets you override the predicates that steer the crawler's task loop: `isTaskReadyFunction` (may another request
162
+ * start?) and `isFinishedFunction` (is the crawl over?). The task itself — fetching a request and running it
163
+ * through the pipeline — is owned by the crawler and cannot be overridden.
164
+ *
165
+ * Concurrency is configured elsewhere — through the `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute`
166
+ * shortcuts, or a {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} for finer control.
167
+ */
168
+ taskLoopOptions?: TaskLoopPredicates;
169
+ /**
170
+ * A pre-configured concurrency governor — the component that decides whether there is free compute for one more
171
+ * task. Typically a {@link ConcurrencySystem}, though any {@link IConcurrencySystem} is accepted. All
172
+ * scaling configuration (min/max/desired concurrency, scaling ratios, `maxTasksPerMinute`, snapshotter tuning)
173
+ * lives on the instance itself.
174
+ *
175
+ * Inject the *same* instance into several concurrent crawlers to cap their **combined** concurrency against a
176
+ * single budget. Each crawler still builds and drives its own {@link AutoscaledPool}; only the load/scaling
177
+ * accounting is shared.
178
+ *
179
+ * Mutually exclusive with the `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts, which configure
180
+ * the default system this one replaces — combining the two throws.
181
+ *
182
+ * You own a supplied system's lifecycle: `start()` it before `run()` (which throws otherwise) and `stop()` it once
183
+ * every crawler borrowing it has finished. The crawler does neither on your behalf.
142
184
  */
143
- autoscaledPoolOptions?: AutoscaledPoolOptions;
185
+ concurrencySystem?: IConcurrencySystem;
144
186
  /**
145
187
  * Sets the minimum concurrency (parallelism) for the crawl. Shortcut for the
146
- * AutoscaledPool {@link AutoscaledPoolOptions.minConcurrency|`minConcurrency`} option.
188
+ * {@link ConcurrencySystemOptions.minConcurrency|`minConcurrency`} option of the crawler's default
189
+ * {@link ConcurrencySystem}.
147
190
  * > *WARNING:* If we set this value too high with respect to the available system memory and CPU, our crawler will run extremely slow or crash.
148
191
  * If not sure, it's better to keep the default value and the concurrency will scale up automatically.
149
192
  */
150
193
  minConcurrency?: number;
151
194
  /**
152
195
  * Sets the maximum concurrency (parallelism) for the crawl. Shortcut for the
153
- * AutoscaledPool {@link AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} option.
196
+ * {@link ConcurrencySystemOptions.maxConcurrency|`maxConcurrency`} option of the crawler's default
197
+ * {@link ConcurrencySystem}.
154
198
  */
155
199
  maxConcurrency?: number;
156
200
  /**
157
201
  * The maximum number of requests per minute the crawler should run.
158
202
  * By default, this is set to `Infinity`, but we can pass any positive, non-zero integer.
159
- * Shortcut for the AutoscaledPool {@link AutoscaledPoolOptions.maxTasksPerMinute|`maxTasksPerMinute`} option.
203
+ * Shortcut for the {@link ConcurrencySystemOptions.maxTasksPerMinute|`maxTasksPerMinute`} option of the
204
+ * crawler's default {@link ConcurrencySystem}.
160
205
  */
161
206
  maxRequestsPerMinute?: number;
162
207
  /**
@@ -166,14 +211,14 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
166
211
  */
167
212
  keepAlive?: boolean;
168
213
  /**
169
- * Basic crawler will initialize the {@link SessionPool} with the corresponding {@link SessionPoolOptions|`sessionPoolOptions`}.
170
- * The session instance will be than available in the {@link BasicCrawlerOptions.requestHandler|`requestHandler`}.
171
- */
172
- useSessionPool?: boolean;
173
- /**
174
- * The configuration options for {@link SessionPool} to use.
214
+ * An existing session pool instance to use. When provided, the crawler will use this pool directly instead of
215
+ * creating a new one, enabling session sharing across multiple crawlers. The crawler will not tear down a shared
216
+ * pool — the caller is responsible for its lifecycle.
217
+ *
218
+ * Accepts the built-in {@link SessionPool} or any object implementing the {@link ISessionPool} interface,
219
+ * so custom session-management strategies can be plugged in.
175
220
  */
176
- sessionPoolOptions?: SessionPoolOptions;
221
+ sessionPool?: ISessionPool;
177
222
  /**
178
223
  * Defines the length of the interval for calling the `setStatusMessage` in seconds.
179
224
  */
@@ -195,6 +240,15 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
195
240
  * ```
196
241
  */
197
242
  statusMessageCallback?: StatusMessageCallback;
243
+ /**
244
+ * HTTP status codes that indicate the session should be retired.
245
+ *
246
+ * A 429 from a domain covered by a {@link ThrottlingRequestManager} is handled as a rate limit before
247
+ * this is consulted, so removing 429 here only affects domains that manager does not cover.
248
+ *
249
+ * @default [401, 403, 429]
250
+ */
251
+ blockedStatusCodes?: number[];
198
252
  /**
199
253
  * If set to `true`, the crawler will automatically try to bypass any detected bot protection.
200
254
  *
@@ -206,50 +260,112 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
206
260
  /**
207
261
  * If set to `true`, the crawler will automatically try to fetch the robots.txt file for each domain,
208
262
  * and skip those that are not allowed. This also prevents disallowed URLs to be added via `enqueueLinks`.
263
+ *
264
+ * If an object is provided, it may contain a `userAgent` property to specify which user-agent
265
+ * should be used when checking the robots.txt file. If not provided, the default user-agent `*` will be used.
209
266
  */
210
- respectRobotsTxtFile?: boolean;
267
+ respectRobotsTxtFile?: boolean | {
268
+ userAgent?: string;
269
+ };
211
270
  /**
212
271
  * When a request is skipped for some reason, you can use this callback to act on it.
213
- * This is currently fired only for requests skipped based on robots.txt file.
272
+ * This is currently fired for requests skipped
273
+ * 1. based on robots.txt file,
274
+ * 2. because they don't match enqueueLinks filters,
275
+ * 3. because they are redirected to a URL that doesn't match the enqueueLinks strategy,
276
+ * 4. or because the {@link BasicCrawlerOptions.maxRequestsPerCrawl|`maxRequestsPerCrawl`} limit has been reached
214
277
  */
215
278
  onSkippedRequest?: SkippedRequestCallback;
216
- /** @internal */
217
- log?: Log;
218
- /**
219
- * Enables experimental features of Crawlee, which can alter the behavior of the crawler.
220
- * WARNING: these options are not guaranteed to be stable and may change or be removed at any time.
221
- */
222
- experiments?: CrawlerExperiments;
223
279
  /**
224
- * Customize the way statistics collecting works, such as logging interval or
225
- * whether to output them to the Key-Value store.
280
+ * A preconfigured statistics instance. When provided, the crawler records into it instead of building its own and
281
+ * will not `reset()` it between `run()` calls. Accepts the built-in {@link Statistics} or any object
282
+ * implementing {@link IStatistics}.
283
+ *
284
+ * Custom fields declared via {@link StatisticsOptions.stateExtension|`stateExtension`} are carried over to
285
+ * {@link BasicCrawler.statistics|`crawler.statistics.state`}:
286
+ *
287
+ * ```ts
288
+ * const statistics = new Statistics({ stateExtension: { defaultState: { productsFound: 0 } } });
289
+ *
290
+ * const crawler = new BasicCrawler({
291
+ * statistics,
292
+ * requestHandler: async () => {
293
+ * statistics.state.productsFound++;
294
+ * },
295
+ * });
296
+ *
297
+ * await crawler.run();
298
+ * // the custom fields are typed on `crawler.statistics` too
299
+ * console.log(crawler.statistics.state.productsFound);
300
+ * ```
226
301
  */
227
- statisticsOptions?: StatisticsOptions;
302
+ statistics?: IStatistics<StatisticStateExtension>;
228
303
  /**
229
304
  * HTTP client implementation for the `sendRequest` context helper and for plain HTTP crawling.
230
- * Defaults to a new instance of {@link GotScrapingHttpClient}
305
+ * Defaults to {@link ImpitHttpClient} when `@crawlee/impit-client` is installed, otherwise {@link FetchHttpClient}.
231
306
  */
232
307
  httpClient?: BaseHttpClient;
233
308
  /**
234
309
  * If set, the crawler will be configured for all connections to use
235
310
  * the Proxy URLs provided and rotated according to the configuration.
236
311
  */
237
- proxyConfiguration?: ProxyConfiguration;
238
- }
239
- /**
240
- * A set of options that you can toggle to enable experimental features in Crawlee.
241
- *
242
- * NOTE: These options will not respect semantic versioning and may be removed or changed at any time. Use at your own risk.
243
- * If you do use these and encounter issues, please report them to us.
244
- */
245
- export interface CrawlerExperiments {
312
+ proxyConfiguration?: IProxyConfiguration;
313
+ /**
314
+ * Custom configuration to use for this crawler.
315
+ * If provided, the crawler will use its own ServiceLocator instance instead of the global one.
316
+ */
317
+ configuration?: Configuration;
318
+ /**
319
+ * Custom storage backend to use for this crawler.
320
+ * If provided, the crawler will use its own ServiceLocator instance instead of the global one.
321
+ */
322
+ storageBackend?: StorageBackend;
246
323
  /**
247
- * @deprecated This experiment is now enabled by default, and this flag will be removed in a future release.
248
- * If you encounter issues due to this change, please:
249
- * - report it to us: https://github.com/apify/crawlee
250
- * - set `requestLocking` to `false` in the `experiments` option of the crawler
324
+ * Custom event manager to use for this crawler.
325
+ * If provided, the crawler will use its own ServiceLocator instance instead of the global one.
251
326
  */
252
- requestLocking?: boolean;
327
+ eventManager?: EventManager;
328
+ /**
329
+ * Custom logger to use for this crawler.
330
+ * If provided, the crawler will use its own ServiceLocator instance instead of the global one.
331
+ */
332
+ logger?: CrawleeLogger;
333
+ /**
334
+ * A unique identifier for the crawler instance. This ID is used to isolate the state returned by
335
+ * {@link BasicCrawler.useState|`crawler.useState()`} from other crawler instances.
336
+ *
337
+ * When multiple crawler instances use `useState()` without an explicit `id`, they will share the same
338
+ * state object for backward compatibility. A warning will be logged in this case.
339
+ *
340
+ * To ensure each crawler has its own isolated state that also persists across script restarts
341
+ * (e.g., during Apify migrations), provide a stable, unique ID for each crawler instance.
342
+ *
343
+ */
344
+ id?: string;
345
+ /**
346
+ * Makes the storage writes performed while handling a request atomic with respect to the request
347
+ * succeeding: they are recorded in a {@link StorageTransaction} spanning the whole request
348
+ * lifecycle and only applied when the request handler succeeds, so a thrown handler leaves no partial
349
+ * writes behind and a retry does not double-write. Reads within the handler see its own writes.
350
+ *
351
+ * `false` disables the mechanism entirely; an object overrides the per-storage-type
352
+ * {@link StorageWritePolicy} (e.g. `{ requestQueue: 'deferred' }` for all-or-nothing enqueues).
353
+ * {@link withDirectStorageAccess} is the per-call-site escape hatch; `useState()` is deliberately
354
+ * *not* transactional.
355
+ *
356
+ * @default true
357
+ */
358
+ transactionalStorage?: boolean | Partial<StorageWritePolicy>;
359
+ /**
360
+ * An array of HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be excluded from error consideration.
361
+ * By default, status codes >= 500 trigger errors.
362
+ */
363
+ ignoreHttpErrorStatusCodes?: number[];
364
+ /**
365
+ * An array of additional HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be treated as errors.
366
+ * By default, status codes >= 500 trigger errors.
367
+ */
368
+ additionalHttpErrorStatusCodes?: number[];
253
369
  }
254
370
  /**
255
371
  * Provides a simple framework for parallel crawling of web pages.
@@ -263,25 +379,31 @@ export interface CrawlerExperiments {
263
379
  *
264
380
  * `BasicCrawler` invokes the user-provided {@link BasicCrawlerOptions.requestHandler|`requestHandler`}
265
381
  * for each {@link Request} object, which represents a single URL to crawl.
266
- * The {@link Request} objects are fed from the {@link RequestList} or {@link RequestQueue}
267
- * instances provided by the {@link BasicCrawlerOptions.requestList|`requestList`} or {@link BasicCrawlerOptions.requestQueue|`requestQueue`}
268
- * constructor options, respectively. If neither `requestList` nor `requestQueue` options are provided,
269
- * the crawler will open the default request queue either when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called,
270
- * or if `requests` parameter (representing the initial requests) of the {@link BasicCrawler.run|`crawler.run()`} function is provided.
382
+ * The {@link Request} objects are fed from the {@link IRequestManager|request manager} provided via the
383
+ * {@link BasicCrawlerOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is
384
+ * itself a request manager). If no `requestManager` is provided, the crawler opens the default {@link RequestQueue}
385
+ * either when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called, or if the `requests`
386
+ * parameter (representing the initial requests) of the {@link BasicCrawler.run|`crawler.run()`} function is provided.
387
+ *
388
+ * To read requests from a read-only source such as a {@link RequestList} or {@link SitemapRequestLoader} while
389
+ * still being able to enqueue new ones, combine the loader with a queue into a {@link RequestManagerTandem} using
390
+ * {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`. The tandem
391
+ * first processes URLs from the loader and automatically enqueues them into the queue, ensuring a single URL is not
392
+ * crawled multiple times.
271
393
  *
272
- * If both {@link BasicCrawlerOptions.requestList|`requestList`} and {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are used,
273
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
274
- * to the {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
394
+ * > The legacy {@link BasicCrawlerOptions.requestList|`requestList`} and
395
+ * > {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are deprecated. They are still accepted and
396
+ * > folded into a single `requestManager` (combined into a tandem when both are given), but new code should use
397
+ * > `requestManager` directly.
275
398
  *
276
399
  * The crawler finishes if there are no more {@link Request} objects to crawl.
277
400
  *
278
- * New requests are only dispatched when there is enough free CPU and memory available,
279
- * using the functionality provided by the {@link AutoscaledPool} class.
280
- * All {@link AutoscaledPool} configuration options can be passed to the {@link BasicCrawlerOptions.autoscaledPoolOptions|`autoscaledPoolOptions`}
281
- * parameter of the `BasicCrawler` constructor.
282
- * For user convenience, the {@link AutoscaledPoolOptions.minConcurrency|`minConcurrency`} and
283
- * {@link AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} options of the
284
- * underlying {@link AutoscaledPool} constructor are available directly in the `BasicCrawler` constructor.
401
+ * New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's
402
+ * {@link ConcurrencySystem}.
403
+ * Concurrency is tuned via the {@link BasicCrawlerOptions.minConcurrency|`minConcurrency`},
404
+ * {@link BasicCrawlerOptions.maxConcurrency|`maxConcurrency`} and
405
+ * {@link BasicCrawlerOptions.maxRequestsPerMinute|`maxRequestsPerMinute`} shortcuts, or, for finer control, by
406
+ * injecting a pre-configured {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`}.
285
407
  *
286
408
  * **Example usage:**
287
409
  *
@@ -315,142 +437,229 @@ export interface CrawlerExperiments {
315
437
  * ```
316
438
  * @category Crawlers
317
439
  */
318
- export declare class BasicCrawler<Context extends CrawlingContext = CrawlingContext, ContextExtension = {}, ExtendedContext extends Context = Context & ContextExtension> {
319
- readonly config: Configuration;
440
+ /**
441
+ * Identifies a crawler instance for storage aliasing, `useState()` and status-message events.
442
+ */
443
+ interface CrawlerIdentity {
444
+ /**
445
+ * 0-based instantiation order across all crawlers in the process.
446
+ * Note that the value can be subject to race conditions between different script invocations.
447
+ */
448
+ readonly instanceIndex: number;
449
+ /** The user-supplied `id` option, or a fallback derived from `instanceIndex`. */
450
+ readonly id: string;
451
+ /** Whether `id` came from the user (as opposed to being derived from `instanceIndex`). */
452
+ readonly hasExplicitId: boolean;
453
+ }
454
+ export declare 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']>>, StatisticStateExtension extends object = {}> {
455
+ #private;
320
456
  protected static readonly CRAWLEE_STATE_KEY = "CRAWLEE_STATE";
321
457
  /**
322
- * A reference to the underlying {@link Statistics} class that collects and logs run statistics for requests.
458
+ * Tracks the number of crawler instances created. The first crawler uses the default
459
+ * request queue; subsequent ones get their own queue via a unique alias so they don't
460
+ * collide.
323
461
  */
324
- readonly stats: Statistics;
462
+ private static instanceCount;
325
463
  /**
326
- * A reference to the underlying {@link RequestList} class that manages the crawler's {@link Request|requests}.
327
- * Only available if used by the crawler.
464
+ * The statistics instance collecting the crawler's run statistics - either the injected `statistics` option or a
465
+ * crawler-built default. Typed as {@link IStatistics} so custom implementations can be plugged in.
328
466
  */
329
- requestList?: IRequestList;
467
+ get statistics(): IStatistics<StatisticStateExtension>;
330
468
  /**
331
- * Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
332
- * A reference to the underlying {@link RequestQueue} class that manages the crawler's {@link Request|requests}.
333
- * Only available if used by the crawler.
469
+ * The main request-handling component of the crawler. It manages the requests that the crawler processes,
470
+ * combining any provided request loader and/or queue. It's initialized during the crawler startup or lazily
471
+ * via {@link BasicCrawler.getRequestManager|`getRequestManager()`}.
334
472
  */
335
- requestQueue?: RequestProvider;
473
+ protected requestManager?: IRequestManager;
336
474
  /**
337
- * A reference to the underlying {@link SessionPool} class that manages the crawler's {@link Session|sessions}.
338
- * Only available if used by the crawler.
475
+ * A reference to the underlying session pool that manages the crawler's {@link Session|sessions}. Typed as
476
+ * {@link ISessionPool} so custom implementations can be plugged in via the `sessionPool` constructor option.
339
477
  */
340
- sessionPool?: SessionPool;
478
+ get sessionPool(): ISessionPool;
341
479
  /**
342
- * A reference to the underlying {@link AutoscaledPool} class that manages the concurrency of the crawler.
343
- * > *NOTE:* This property is only initialized after calling the {@link BasicCrawler.run|`crawler.run()`} function.
344
- * We can use it to change the concurrency settings on the fly,
345
- * to pause the crawler by calling {@link AutoscaledPool.pause|`autoscaledPool.pause()`}
346
- * or to abort it by calling {@link AutoscaledPool.abort|`autoscaledPool.abort()`}.
480
+ * The concurrency governor this run is booking its requests against either the
481
+ * {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} that was injected, or the default the
482
+ * crawler built for itself. Read it for telemetry: `desiredConcurrency`, `currentConcurrency`, `isRunning`.
483
+ *
484
+ * > *NOTE:* `undefined` until {@link BasicCrawler.run|`crawler.run()`} has resolved it. A crawler-owned default
485
+ * is also rebuilt for every run, so the instance is not stable across runs.
486
+ *
487
+ * {@link IConcurrencySystem} is deliberately read-only. Tuning concurrency *while a crawl is running* means
488
+ * owning the instance: build a {@link ConcurrencySystem} yourself and inject it, then set
489
+ * `minConcurrency`/`maxConcurrency`/`desiredConcurrency` on your own reference.
347
490
  */
348
- autoscaledPool?: AutoscaledPool;
491
+ get concurrencySystem(): IConcurrencySystem | undefined;
349
492
  /**
350
- * A reference to the underlying {@link ProxyConfiguration} class that manages the crawler's proxies.
493
+ * A reference to the underlying {@link IProxyConfiguration} instance that manages the crawler's proxies.
351
494
  * Only available if used by the crawler.
352
495
  */
353
- proxyConfiguration?: ProxyConfiguration;
496
+ readonly proxyConfiguration?: IProxyConfiguration;
354
497
  /**
355
498
  * Default {@link Router} instance that will be used if we don't specify any {@link BasicCrawlerOptions.requestHandler|`requestHandler`}.
356
499
  * See {@link Router.addHandler|`router.addHandler()`} and {@link Router.addDefaultHandler|`router.addDefaultHandler()`}.
357
500
  */
358
- readonly router: RouterHandler<Context>;
359
- private contextPipelineBuilder;
360
- private _contextPipeline?;
501
+ readonly router: RouterHandler<Context, Routes>;
502
+ /**
503
+ * The basic part of the context pipeline. Unlike the subclass pipeline, this
504
+ * part has no major side effects (e.g. launching a browser). It also makes typing more explicit, as subclass
505
+ * pipelines expect the basic crawler fields to already be present in the context at runtime.
506
+ *
507
+ * Context built with this pipeline can be passed into multiple crawler pipelines at once.
508
+ * This is used e.g. in the {@link AdaptivePlaywrightCrawler|`AdaptivePlaywrightCrawler`}.
509
+ */
510
+ get basicContextPipeline(): ContextPipeline<{
511
+ request: Request;
512
+ }, CrawlingContext>;
361
513
  get contextPipeline(): ContextPipeline<CrawlingContext, ExtendedContext>;
362
514
  running: boolean;
363
515
  hasFinishedBefore: boolean;
364
- readonly log: Log;
365
- protected requestHandler: RequestHandler<ExtendedContext>;
366
- protected errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
367
- protected failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
368
- protected requestHandlerTimeoutMillis: number;
369
- protected internalTimeoutMillis: number;
370
- protected maxRequestRetries: number;
371
- protected sameDomainDelayMillis: number;
372
- protected domainAccessedTime: Map<string, number>;
373
- protected maxSessionRotations: number;
374
- protected handledRequestsCount: number;
375
- protected statusMessageLoggingInterval: number;
376
- protected statusMessageCallback?: StatusMessageCallback;
377
- protected sessionPoolOptions: SessionPoolOptions;
378
- protected useSessionPool: boolean;
379
- protected autoscaledPoolOptions: AutoscaledPoolOptions;
380
- protected events: EventManager;
381
- protected httpClient: BaseHttpClient;
382
- protected retryOnBlocked: boolean;
383
- protected respectRobotsTxtFile: boolean;
384
- protected onSkippedRequest?: SkippedRequestCallback;
385
- private _closeEvents?;
386
- private experiments;
387
- private readonly robotsTxtFileCache;
388
- private _experimentWarnings;
516
+ get log(): CrawleeLogger;
517
+ protected readonly requestHandler: RequestHandler<ExtendedContext>;
518
+ protected readonly errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
519
+ protected readonly failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
520
+ private requestHandlerTimeoutMillis;
521
+ protected readonly internalTimeoutMillis: number;
522
+ protected readonly maxRequestRetries: number;
523
+ protected readonly maxCrawlDepth?: number;
524
+ protected readonly maxRequestsPerCrawl?: number;
525
+ private get handledRequestsCount();
526
+ protected blockedStatusCodes: Set<number>;
527
+ protected readonly additionalHttpErrorStatusCodes: Set<number>;
528
+ /**
529
+ * The resolved options for the crawler's own task loop — the crawler-owned `runTaskFunction`, the (possibly
530
+ * user-overridden) ready/finished predicates and cadence/logging. Concurrency configuration lives on the
531
+ * {@link ConcurrencySystem} instead, and the loop's `consumer` identity is the crawler's own, so neither is
532
+ * settable here.
533
+ */
534
+ private taskLoopOptions;
535
+ protected readonly httpClient: BaseHttpClient;
536
+ protected readonly retryOnBlocked: boolean;
537
+ protected readonly onSkippedRequest?: SkippedRequestCallback;
538
+ protected readonly identity: CrawlerIdentity;
389
539
  protected static optionsShape: {
390
- // @ts-ignore optional peer dependency or compatibility with es2022
391
- contextPipelineBuilder: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
392
- // @ts-ignore optional peer dependency or compatibility with es2022
393
- extendContext: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
394
- // @ts-ignore optional peer dependency or compatibility with es2022
395
- requestList: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
396
- // @ts-ignore optional peer dependency or compatibility with es2022
397
- requestQueue: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
398
- // @ts-ignore optional peer dependency or compatibility with es2022
399
- requestHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
400
- // @ts-ignore optional peer dependency or compatibility with es2022
401
- requestHandlerTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
402
- // @ts-ignore optional peer dependency or compatibility with es2022
403
- errorHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
404
- // @ts-ignore optional peer dependency or compatibility with es2022
405
- failedRequestHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
406
- // @ts-ignore optional peer dependency or compatibility with es2022
407
- maxRequestRetries: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
408
- // @ts-ignore optional peer dependency or compatibility with es2022
409
- sameDomainDelaySecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
410
- // @ts-ignore optional peer dependency or compatibility with es2022
411
- maxSessionRotations: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
412
- // @ts-ignore optional peer dependency or compatibility with es2022
413
- maxRequestsPerCrawl: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
414
- // @ts-ignore optional peer dependency or compatibility with es2022
415
- autoscaledPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
416
- // @ts-ignore optional peer dependency or compatibility with es2022
417
- sessionPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
418
- // @ts-ignore optional peer dependency or compatibility with es2022
419
- useSessionPool: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
420
- // @ts-ignore optional peer dependency or compatibility with es2022
421
- proxyConfiguration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
422
- // @ts-ignore optional peer dependency or compatibility with es2022
423
- statusMessageLoggingInterval: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
424
- // @ts-ignore optional peer dependency or compatibility with es2022
425
- statusMessageCallback: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
426
- // @ts-ignore optional peer dependency or compatibility with es2022
427
- retryOnBlocked: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
428
- // @ts-ignore optional peer dependency or compatibility with es2022
429
- respectRobotsTxtFile: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
430
- // @ts-ignore optional peer dependency or compatibility with es2022
431
- onSkippedRequest: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
432
- // @ts-ignore optional peer dependency or compatibility with es2022
433
- httpClient: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
434
- // @ts-ignore optional peer dependency or compatibility with es2022
435
- minConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
436
- // @ts-ignore optional peer dependency or compatibility with es2022
437
- maxConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
438
- // @ts-ignore optional peer dependency or compatibility with es2022
439
- maxRequestsPerMinute: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
440
- // @ts-ignore optional peer dependency or compatibility with es2022
441
- keepAlive: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
442
- // @ts-ignore optional peer dependency or compatibility with es2022
443
- log: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
444
- // @ts-ignore optional peer dependency or compatibility with es2022
445
- experiments: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
446
- // @ts-ignore optional peer dependency or compatibility with es2022
447
- statisticsOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
540
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
541
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
542
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
543
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
544
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
545
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
546
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
547
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
548
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
549
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
550
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
551
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
552
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
553
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
554
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
555
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
556
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
557
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
558
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
559
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
560
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
561
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
562
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
563
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
564
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
565
+ requestQueue: z.ZodOptional<z.ZodEnum<{
566
+ deferred: "deferred";
567
+ writeThrough: "writeThrough";
568
+ }>>;
569
+ }, z.core.$strict>]>>;
570
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
571
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
572
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
573
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
574
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
575
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
576
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
577
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
578
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
579
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
580
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
581
+ id: z.ZodOptional<z.ZodString>;
448
582
  };
583
+ protected static optionsSchema: z.ZodObject<{
584
+ contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
585
+ extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
586
+ requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
587
+ requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
588
+ requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
589
+ requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
590
+ requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
591
+ errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
592
+ failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
593
+ maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
594
+ sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
595
+ maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
596
+ maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
597
+ taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
598
+ concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
599
+ sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
600
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
601
+ statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
602
+ statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
603
+ additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
604
+ ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
605
+ blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
606
+ retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
607
+ respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
608
+ transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
609
+ requestQueue: z.ZodOptional<z.ZodEnum<{
610
+ deferred: "deferred";
611
+ writeThrough: "writeThrough";
612
+ }>>;
613
+ }, z.core.$strict>]>>;
614
+ onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
615
+ httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
616
+ configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
617
+ storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
618
+ eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
619
+ logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
620
+ minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
621
+ maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
622
+ maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
623
+ keepAlive: z.ZodOptional<z.ZodBoolean>;
624
+ statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
625
+ id: z.ZodOptional<z.ZodString>;
626
+ }, z.core.$strict>;
449
627
  /**
450
628
  * All `BasicCrawler` parameters are passed via an options object.
451
629
  */
452
- constructor(options?: BasicCrawlerOptions<Context, ContextExtension, ExtendedContext> & RequireContextPipeline<CrawlingContext, Context>, // cast because the constructor logic handles missing `contextPipelineBuilder` - the type is just for DX
453
- config?: Configuration);
630
+ constructor(options?: BasicCrawlerOptions<Context, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> & RequireContextPipeline<CrawlingContext, Context>);
631
+ /**
632
+ * Builds the crawler-owned default {@link ConcurrencySystem} from the resolved
633
+ * `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts. Not called when a
634
+ * {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} was injected.
635
+ *
636
+ * Subclasses may override this to tune the default system (e.g. {@link HttpCrawler} raises the starting
637
+ * concurrency and relaxes the event loop signal) while still honouring the user's shortcuts.
638
+ */
639
+ protected createDefaultConcurrencySystem(options: ConcurrencySystemOptions): ConcurrencySystem;
640
+ /**
641
+ * Determines if the given HTTP status code is an error status code given
642
+ * the default behaviour and user-set preferences.
643
+ * @param status
644
+ * @returns `true` if the status code is considered an error, `false` otherwise
645
+ */
646
+ protected isErrorStatusCode(status: number): boolean;
647
+ /**
648
+ * Builds the basic context pipeline that transforms `{ request }` into a full `CrawlingContext`.
649
+ * This handles base context creation, session resolution, and context helpers.
650
+ */
651
+ private buildBasicContextPipeline;
652
+ private checkRobotsTxt;
653
+ /**
654
+ * Builds the subclass-specific context pipeline that transforms a `CrawlingContext` into the crawler's target context type.
655
+ * Subclasses should override this to add their own pipeline stages.
656
+ */
657
+ protected buildContextPipeline(): ContextPipeline<CrawlingContext, CrawlingContext>;
658
+ private createBaseContext;
659
+ private resolveRequest;
660
+ private resolveSession;
661
+ private createContextHelpers;
662
+ private buildFinalContextPipeline;
454
663
  /**
455
664
  * Checks if the given error is a proxy error by comparing its message to a list of known proxy error messages.
456
665
  * Used for retrying requests that failed due to proxy errors.
@@ -459,13 +668,20 @@ export declare class BasicCrawler<Context extends CrawlingContext = CrawlingCont
459
668
  */
460
669
  protected isProxyError(error: Error): boolean;
461
670
  /**
671
+ * Sets the status message for the current crawler run.
672
+ *
462
673
  * This method is periodically called by the crawler, every `statusMessageLoggingInterval` seconds.
674
+ *
675
+ * The message is logged and broadcast via the {@link EventType.STATUS_MESSAGE|`statusMessage`}
676
+ * event. Integrations such as the Apify SDK subscribe to that event and forward the message to
677
+ * their status-reporting backend (e.g. the Apify platform).
463
678
  */
464
- setStatusMessage(message: string, options?: SetStatusMessageOptions): Promise<void>;
679
+ setStatusMessage(message: string, options?: SetStatusMessageOptions): void;
465
680
  private getPeriodicLogger;
466
681
  /**
467
- * Runs the crawler. Returns a promise that resolves once all the requests are processed
468
- * and `autoscaledPool.isFinished` returns `true`.
682
+ * Runs the crawler. Returns a promise that resolves once every request has been processed and the crawler's
683
+ * finished-check ({@link BasicCrawlerOptions.taskLoopOptions|`taskLoopOptions.isFinishedFunction`}, or the
684
+ * default "the request manager is empty") reports that the crawl is over.
469
685
  *
470
686
  * We can use the `requests` parameter to enqueue the initial requests — it is a shortcut for
471
687
  * running {@link BasicCrawler.addRequests|`crawler.addRequests()`} before {@link BasicCrawler.run|`crawler.run()`}.
@@ -473,35 +689,91 @@ export declare class BasicCrawler<Context extends CrawlingContext = CrawlingCont
473
689
  * @param [requests] The requests to add.
474
690
  * @param [options] Options for the request queue.
475
691
  */
476
- run(requests?: (string | Request | RequestOptions)[], options?: CrawlerRunOptions): Promise<FinalStatistics>;
692
+ run(requests?: TypedRequestsLike<Routes>, options?: CrawlerRunOptions): Promise<FinalStatistics>;
477
693
  /**
478
694
  * Gracefully stops the current run of the crawler.
479
695
  *
480
696
  * All the tasks active at the time of calling this method will be allowed to finish.
697
+ *
698
+ * To stop the crawler immediately, use {@link BasicCrawler.teardown|`crawler.teardown()`} instead.
481
699
  */
482
- stop(message?: string): void;
483
- getRequestQueue(): Promise<RequestProvider>;
700
+ stop(reason?: string): void;
701
+ /**
702
+ * Stops dispatching new requests, letting the in-progress ones finish. Resolves once they have settled, or rejects
703
+ * after `timeoutSecs` if they take too long. Unlike {@link BasicCrawler.stop|`stop()`}, this does not end the
704
+ * run — {@link BasicCrawler.run|`run()`} stays pending until {@link BasicCrawler.resume|`resume()`}.
705
+ *
706
+ * > *NOTE:* The {@link BasicCrawler.concurrencySystem|concurrency system} keeps monitoring and autoscaling
707
+ * throughout, since a shared one may still be serving other crawlers.
708
+ */
709
+ pause(timeoutSecs?: number): Promise<void>;
710
+ /**
711
+ * Resumes a run suspended with {@link BasicCrawler.pause|`pause()`}, letting the crawler dispatch requests
712
+ * again. A no-op on a crawler that is not paused.
713
+ */
714
+ resume(): void;
715
+ /**
716
+ * Returns the crawler's {@link IRequestManager|request manager}, opening the default {@link RequestQueue}
717
+ * if none has been configured or opened yet.
718
+ */
719
+ getRequestManager(): Promise<IRequestManager>;
720
+ /**
721
+ * @deprecated Use {@link BasicCrawler.getRequestManager|`getRequestManager()`} instead. This returns the
722
+ * crawler's request manager, which is no longer guaranteed to be a {@link RequestQueue}.
723
+ */
724
+ getRequestQueue(): Promise<IRequestManager>;
725
+ /**
726
+ * Opens the default {@link RequestQueue}, applies the crawler's timeouts to it and records it as the
727
+ * crawler-owned queue (so it gets purged between repeated `run()` calls).
728
+ * @private
729
+ */
730
+ private openOwnedRequestQueue;
731
+ /**
732
+ * Tells a request manager how long we expect to hold a fetched request, so that one backed by a
733
+ * locking storage backend keeps it reserved for slightly longer than the request handler timeout
734
+ * (with some padding for overhead), but never for less than a minute. This prevents a long-running
735
+ * request from being handed out a second time while it is still being processed — and it works
736
+ * regardless of whether the manager is a plain {@link RequestQueue} or a `RequestManagerTandem`.
737
+ */
738
+ private applyRequestManagerTimeouts;
739
+ /**
740
+ * Validates a request source's `userData` against the {@link RouteSchemas|Standard Schema} registered
741
+ * for its label on the crawler's schema-router (if any), throwing a {@link RequestValidationError} on
742
+ * mismatch. A no-op when the user's request handler is not a schema-router, or no schema is registered for
743
+ * the request's label. Applied by the crawler on the add paths it owns — `crawler.addRequests`,
744
+ * `crawler.run`, `context.addRequests` and `context.enqueueLinks`.
745
+ */
746
+ private validateRequestUserData;
484
747
  useState<State extends Dictionary = Dictionary>(defaultValue?: State): Promise<State>;
748
+ protected getPendingRequestCountApproximation(): Promise<number>;
749
+ protected calculateEnqueuedRequestLimit(explicitLimit?: number): Promise<number | undefined>;
750
+ protected handleSkippedRequest(options: Parameters<SkippedRequestCallback>[0]): Promise<void>;
751
+ private logOncePerRun;
485
752
  /**
486
753
  * Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
487
754
  * adding the rest in background. You can configure the batch size via `batchSize` option and the sleep time in between
488
755
  * the batches via `waitBetweenBatchesMillis`. If you want to wait for all batches to be added to the queue, you can use
489
756
  * the `waitForAllRequestsToBeAdded` promise you get in the response object.
490
757
  *
758
+ * Optionally, the requests can be filtered using `include`/`exclude` glob or regexp patterns and an
759
+ * enqueue `strategy` (both AND-ed together, same as {@link CrawlingContext.enqueueLinks|`enqueueLinks`}),
760
+ * relative to `baseUrl`. Unlike `enqueueLinks`, there is no implicit "current page" to anchor the strategy
761
+ * to, so `strategy` defaults to {@link EnqueueStrategy.All|`all`} here.
762
+ *
491
763
  * This is an alias for calling `addRequestsBatched()` on the implicit `RequestQueue` for this crawler instance.
492
764
  *
493
765
  * @param requests The requests to add
494
766
  * @param options Options for the request queue
495
767
  */
496
- addRequests(requests: ReadonlyDeep<(string | Source)[]>, options?: CrawlerAddRequestsOptions): Promise<CrawlerAddRequestsResult>;
768
+ addRequests(requests: ReadonlyDeep<TypedRequestsLike<Routes>>, options?: CrawlerAddRequestsOptions): Promise<CrawlerAddRequestsResult>;
497
769
  /**
498
770
  * Pushes data to the specified {@link Dataset}, or the default crawler {@link Dataset} by calling {@link Dataset.pushData}.
499
771
  */
500
- pushData(data: Parameters<Dataset['pushData']>[0], datasetIdOrName?: string): Promise<void>;
772
+ pushData(data: Parameters<Dataset['pushData']>[0], datasetIdentifier?: string | StorageIdentifier): Promise<void>;
501
773
  /**
502
774
  * Retrieves the specified {@link Dataset}, or the default crawler {@link Dataset}.
503
775
  */
504
- getDataset(idOrName?: string): Promise<Dataset>;
776
+ getDataset(identifier?: string | StorageIdentifier): Promise<Dataset>;
505
777
  /**
506
778
  * Retrieves data from the default crawler {@link Dataset} by calling {@link Dataset.getData}.
507
779
  */
@@ -511,45 +783,89 @@ export declare class BasicCrawler<Context extends CrawlingContext = CrawlingCont
511
783
  * Supported formats are currently 'json' and 'csv', and will be inferred from the `path` automatically.
512
784
  */
513
785
  exportData<Data>(path: string, format?: 'json' | 'csv', options?: DatasetExportOptions): Promise<Data[]>;
514
- protected _init(): Promise<void>;
515
- protected runRequestHandler(crawlingContext: CrawlingContext): Promise<void>;
786
+ /**
787
+ * Initializes the crawler.
788
+ */
789
+ protected init(): Promise<void>;
790
+ /**
791
+ * The navigation timeout (pre-navigation hooks, navigation, and post-navigation hooks) in milliseconds, used
792
+ * to size the internal request timeout. `BasicCrawler` has no navigation phase, so this is 0; the HTTP and
793
+ * browser crawlers override it with their `navigationTimeoutSecs`.
794
+ */
795
+ protected getNavigationTimeoutMillis(): number;
796
+ /**
797
+ * Races the request against the internal timeout (see {@link raceWithTimeout}), sized to outlast the phases
798
+ * that have their own timeout - the navigation, its hooks, and the request handler - so a legitimately slow
799
+ * request, a per-route override, or a low `CRAWLEE_INTERNAL_TIMEOUT` is not cut short mid-phase. It takes
800
+ * whichever is larger: the configured internal timeout, or this request's combined phase budget.
801
+ */
802
+ private withRequestTimeout;
803
+ /**
804
+ * The request handler timeout for a request with the given route label. A router route may override the
805
+ * crawler's own `requestHandlerTimeoutSecs`; anything else falls back to `fallbackMillis`.
806
+ *
807
+ * @param label The request's route label, or `undefined` for the default route / no specific request.
808
+ * @param fallbackMillis Timeout to use when no route overrides it.
809
+ */
810
+ private resolveRequestHandlerTimeoutMillis;
811
+ /**
812
+ * The timeout the router route with the given label asked for, or `undefined` when it did not override one
813
+ * (or the request handler is not a router at all).
814
+ */
815
+ private getRouteTimeoutMillis;
816
+ protected runRequestHandler(crawlingContext: ExtendedContext): Promise<void>;
817
+ /**
818
+ * Runs `callback` inside a {@link StorageTransaction}, unless transactional storage is disabled.
819
+ * Deliberately does **not** commit on return - `handleRequest` swallows request handler failures, so
820
+ * a normal return says nothing about success. `handleRequest` owns the outcome.
821
+ */
822
+ private runInStorageTransaction;
516
823
  /**
517
824
  * Handles blocked request
518
825
  */
519
- protected _throwOnBlockedRequest(session: Session, statusCode: number): void;
826
+ protected throwOnBlockedRequest(statusCode: number): void;
520
827
  private isAllowedBasedOnRobotsTxtFile;
521
- protected getRobotsTxtFileForUrl(url: string): Promise<RobotsTxtFile | undefined>;
522
- protected _pauseOnMigration(): Promise<void>;
523
828
  /**
524
- * Fetches request from either RequestList or RequestQueue. If request comes from a RequestList
525
- * and RequestQueue is present then enqueues it to the queue first.
829
+ * Records an HTTP 429 against the URL's domain so the request manager can pace the retry.
830
+ *
831
+ * @param retryAfterHeader The raw `Retry-After` response header, if the server sent one.
832
+ * @returns `true` if a manager took responsibility for the delay, in which case the caller should throw
833
+ * {@link RequestThrottledError} rather than treating the response as a blocked session.
834
+ */
835
+ protected recordDomainRateLimit(url: string, retryAfterHeader?: string | null): boolean;
836
+ /**
837
+ * Hands a robots.txt `Crawl-delay` to the request manager, warning if nothing is able to honour it.
838
+ *
839
+ * The warning is driven by whether the delay was actually accepted rather than by the type of the manager,
840
+ * because a manager that does throttle still drops the delay for a domain missing from its `domains` list.
526
841
  */
527
- protected _fetchNextRequest(): Promise<Request<Dictionary> | null | undefined>;
842
+ private applyCrawlDelay;
843
+ protected getRobotsTxtFileForUrl(url: string): Promise<RobotsTxtFile | undefined>;
844
+ private pauseOnMigration;
528
845
  /**
529
- * Delays processing of the request based on the `sameDomainDelaySecs` option,
530
- * adding it back to the queue after the timeout passes. Returns `true` if the request
531
- * should be ignored and will be reclaimed to the queue once ready.
846
+ * Fetches the next request to process from the underlying request provider.
532
847
  */
533
- protected delayRequest(request: Request, source: IRequestList | RequestProvider): boolean;
848
+ private fetchNextRequest;
849
+ /** Handles a single request - runs the request handler with retries, error handling, and lifecycle management. */
850
+ private handleRequest;
534
851
  /**
535
- * Wrapper around requestHandler that fetches requests from RequestList/RequestQueue
536
- * then retries them in a case of an error, etc.
852
+ * Generator function that yields requests injected with the given crawl depth.
853
+ * @internal
537
854
  */
538
- protected _runTaskFunction(): Promise<void>;
855
+ protected addCrawlDepthRequestGenerator(requests: RequestsLike, newRequestDepth: number): AsyncGenerator<Source, void, undefined>;
539
856
  /**
540
- * Run async callback with given timeout and retry.
857
+ * Run async callback with given timeout and retry. Returns the result of the callback.
541
858
  * @ignore
542
859
  */
543
- protected _timeoutAndRetry(handler: () => Promise<unknown>, timeout: number, error: Error | string, maxRetries?: number, retried?: number): Promise<void>;
860
+ private timeoutAndRetry;
544
861
  /**
545
862
  * Returns true if either RequestList or RequestQueue have a request ready for processing.
546
863
  */
547
- protected _isTaskReadyFunction(): Promise<boolean>;
864
+ private isTaskReadyFunction;
548
865
  /**
549
866
  * Returns true if both RequestList and RequestQueue have all requests finished.
550
867
  */
551
- protected _defaultIsFinishedFunction(): Promise<boolean>;
552
- private _rotateSession;
868
+ private defaultIsFinishedFunction;
553
869
  /**
554
870
  * Unwraps errors thrown by the context pipeline to get the actual user error.
555
871
  * RequestHandlerError and ContextPipelineInitializationError wrap the actual error.
@@ -557,50 +873,53 @@ export declare class BasicCrawler<Context extends CrawlingContext = CrawlingCont
557
873
  private unwrapError;
558
874
  /**
559
875
  * Handles errors thrown by user provided requestHandler()
876
+ *
877
+ * @param request The request object, passed separately to circumvent potential dynamic logic in crawlingContext.request
560
878
  */
561
- protected _requestFunctionErrorHandler(error: Error, crawlingContext: CrawlingContext, source: IRequestList | RequestProvider): Promise<void>;
562
- protected _tagUserHandlerError<T>(cb: () => unknown): Promise<T>;
563
- protected _handleFailedRequestHandler(crawlingContext: CrawlingContext, error: Error): Promise<void>;
879
+ private requestFunctionErrorHandler;
880
+ private handleFailedRequestHandler;
564
881
  /**
565
882
  * Resolves the most verbose error message from a thrown error
566
883
  * @param error The error received
567
884
  * @returns The message to be logged
568
885
  */
569
- protected _getMessageFromError(error: Error, forceStack?: boolean): string | TimeoutError | undefined;
570
- protected _canRequestBeRetried(request: Request, error: Error): boolean;
886
+ protected getMessageFromError(error: Error, forceStack?: boolean): string | TimeoutError | undefined;
571
887
  /**
572
- * Updates handledRequestsCount from possibly stored counts,
573
- * usually after worker migration. Since one of the stores
574
- * needs to have priority when both are present,
575
- * it is the request queue, because generally, the request
576
- * list will first be dumped into the queue and then left
577
- * empty.
888
+ * Whether the session should be spared for this error - either because it was already retired, or because the
889
+ * failure says nothing about the session (a rate limit is a property of the domain).
578
890
  */
579
- protected _loadHandledRequestCount(): Promise<void>;
580
- protected _executeHooks<HookLike extends (...args: any[]) => Awaitable<void>>(hooks: HookLike[], ...args: Parameters<HookLike>): Promise<void>;
891
+ private errorAbsolvesSession;
892
+ private canRequestBeRetried;
581
893
  /**
582
- * Function for cleaning up after all request are processed.
583
- * @ignore
894
+ * Stops the crawler immediately.
895
+ *
896
+ * This method doesn't wait for currently active requests to finish.
897
+ *
898
+ * To stop the crawler gracefully (waiting for all running requests to finish), use {@link BasicCrawler.stop|`crawler.stop()`} instead.
584
899
  */
585
900
  teardown(): Promise<void>;
586
- protected _getCookieHeaderFromRequest(request: Request): string;
587
- private _getRequestQueue;
588
- protected requestMatchesEnqueueStrategy(request: Request): boolean;
901
+ protected getCookieHeaderFromRequest(request: Request): string;
902
+ private requestMatchesEnqueueStrategy;
589
903
  }
590
904
  export interface CreateContextOptions {
591
905
  request: Request;
592
- session?: Session;
906
+ session: ISession;
593
907
  proxyInfo?: ProxyInfo;
594
908
  }
595
- export interface CrawlerAddRequestsOptions extends AddRequestsBatchedOptions {
909
+ export interface CrawlerAddRequestsOptions extends AddRequestsBatchedOptions, EnqueueUrlsOptions {
596
910
  }
597
911
  export interface CrawlerAddRequestsResult extends AddRequestsBatchedResult {
598
912
  }
599
913
  export interface CrawlerRunOptions extends CrawlerAddRequestsOptions {
600
914
  /**
601
- * Whether to purge the RequestQueue before running the crawler again. Defaults to true, so it is possible to reprocess failed requests.
602
- * When disabled, only new requests will be considered. Note that even a failed request is considered as handled.
603
- * @default true
915
+ * Controls whether the request queue is purged between repeated `run()` calls on the same crawler instance.
916
+ * Purging clears all requests and resets internal counters, allowing the same URLs to be processed again.
917
+ *
918
+ * - **`undefined`** (default) — only the crawler's own (auto-created) queue is purged.
919
+ * A user-supplied `requestQueue` is left untouched.
920
+ * - **`true`** — the queue is always purged, even if it was supplied by the user.
921
+ * - **`false`** — nothing is purged. Only genuinely new requests will be processed;
922
+ * note that even a failed request is considered handled.
604
923
  */
605
924
  purgeRequestQueue?: boolean;
606
925
  }
@@ -628,5 +947,5 @@ export interface CrawlerRunOptions extends CrawlerAddRequestsOptions {
628
947
  * await crawler.run();
629
948
  * ```
630
949
  */
631
- export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): RouterHandler<Context>;
632
- //# sourceMappingURL=basic-crawler.d.ts.map
950
+ export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
951
+ export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;