@crawlee/core 4.0.0-beta.71 → 4.0.0-beta.72
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.
- package/autoscaling/autoscaled_pool.d.ts +2 -1
- package/autoscaling/autoscaled_pool.js +9 -2
- package/autoscaling/client_load_signal.d.ts +25 -0
- package/autoscaling/client_load_signal.js +36 -0
- package/autoscaling/cpu_load_signal.d.ts +28 -0
- package/autoscaling/cpu_load_signal.js +24 -0
- package/autoscaling/event_loop_load_signal.d.ts +23 -0
- package/autoscaling/event_loop_load_signal.js +35 -0
- package/autoscaling/index.d.ts +5 -1
- package/autoscaling/index.js +5 -1
- package/autoscaling/load_signal.d.ts +99 -0
- package/autoscaling/load_signal.js +135 -0
- package/autoscaling/memory_load_signal.d.ts +43 -0
- package/autoscaling/memory_load_signal.js +101 -0
- package/autoscaling/snapshotter.d.ts +36 -63
- package/autoscaling/snapshotter.js +83 -175
- package/autoscaling/system_status.d.ts +21 -33
- package/autoscaling/system_status.js +45 -82
- package/configuration.d.ts +0 -1
- package/configuration.js +0 -1
- package/cookie_utils.d.ts +0 -1
- package/cookie_utils.js +2 -1
- package/crawlers/context_pipeline.d.ts +0 -1
- package/crawlers/context_pipeline.js +0 -1
- package/crawlers/crawler_commons.d.ts +0 -1
- package/crawlers/crawler_commons.js +0 -1
- package/crawlers/crawler_utils.d.ts +0 -1
- package/crawlers/crawler_utils.js +0 -1
- package/crawlers/error_snapshotter.d.ts +0 -1
- package/crawlers/error_snapshotter.js +0 -1
- package/crawlers/error_tracker.d.ts +0 -1
- package/crawlers/error_tracker.js +0 -1
- package/crawlers/index.d.ts +0 -1
- package/crawlers/index.js +0 -1
- package/crawlers/internals/types.d.ts +0 -1
- package/crawlers/internals/types.js +0 -1
- package/crawlers/statistics.d.ts +6 -1
- package/crawlers/statistics.js +8 -1
- package/enqueue_links/enqueue_links.d.ts +8 -1
- package/enqueue_links/enqueue_links.js +9 -9
- package/enqueue_links/index.d.ts +0 -1
- package/enqueue_links/index.js +0 -1
- package/enqueue_links/shared.d.ts +0 -1
- package/enqueue_links/shared.js +0 -1
- package/errors.d.ts +20 -1
- package/errors.js +22 -1
- package/events/event_manager.d.ts +0 -1
- package/events/event_manager.js +0 -1
- package/events/index.d.ts +0 -1
- package/events/index.js +0 -1
- package/events/local_event_manager.d.ts +1 -1
- package/events/local_event_manager.js +9 -6
- package/index.d.ts +0 -1
- package/index.js +0 -1
- package/log.d.ts +0 -1
- package/log.js +0 -1
- package/memory-storage/consts.d.ts +0 -1
- package/memory-storage/consts.js +0 -1
- package/memory-storage/index.d.ts +0 -1
- package/memory-storage/index.js +0 -1
- package/memory-storage/memory-storage.d.ts +0 -1
- package/memory-storage/memory-storage.js +0 -1
- package/memory-storage/resource-clients/common/base-client.d.ts +0 -1
- package/memory-storage/resource-clients/common/base-client.js +0 -1
- package/memory-storage/resource-clients/dataset.d.ts +0 -1
- package/memory-storage/resource-clients/dataset.js +0 -1
- package/memory-storage/resource-clients/key-value-store.d.ts +0 -1
- package/memory-storage/resource-clients/key-value-store.js +0 -1
- package/memory-storage/resource-clients/request-queue.d.ts +0 -1
- package/memory-storage/resource-clients/request-queue.js +0 -1
- package/memory-storage/utils.d.ts +6 -1
- package/memory-storage/utils.js +15 -1
- package/package.json +5 -5
- package/proxy_configuration.d.ts +0 -1
- package/proxy_configuration.js +0 -1
- package/recoverable_state.d.ts +0 -1
- package/recoverable_state.js +0 -1
- package/request.d.ts +0 -1
- package/request.js +0 -1
- package/router.d.ts +117 -15
- package/router.js +124 -30
- package/serialization.d.ts +0 -1
- package/serialization.js +0 -1
- package/service_locator.d.ts +0 -1
- package/service_locator.js +0 -1
- package/session_pool/consts.d.ts +0 -1
- package/session_pool/consts.js +0 -1
- package/session_pool/errors.d.ts +0 -1
- package/session_pool/errors.js +0 -1
- package/session_pool/fingerprint.d.ts +0 -1
- package/session_pool/fingerprint.js +0 -1
- package/session_pool/index.d.ts +0 -1
- package/session_pool/index.js +0 -1
- package/session_pool/session.d.ts +0 -1
- package/session_pool/session.js +0 -1
- package/session_pool/session_pool.d.ts +0 -1
- package/session_pool/session_pool.js +0 -1
- package/storages/access_checking.d.ts +0 -1
- package/storages/access_checking.js +0 -1
- package/storages/dataset.d.ts +1 -2
- package/storages/dataset.js +0 -1
- package/storages/index.d.ts +0 -1
- package/storages/index.js +0 -1
- package/storages/key_value_store.d.ts +0 -1
- package/storages/key_value_store.js +0 -1
- package/storages/key_value_store_codec.d.ts +0 -1
- package/storages/key_value_store_codec.js +0 -1
- package/storages/request_dedup_cache.d.ts +23 -0
- package/storages/request_dedup_cache.js +48 -0
- package/storages/request_list.d.ts +6 -1
- package/storages/request_list.js +16 -3
- package/storages/request_loader.d.ts +0 -1
- package/storages/request_loader.js +0 -1
- package/storages/request_manager.d.ts +0 -1
- package/storages/request_manager.js +0 -1
- package/storages/request_manager_tandem.d.ts +0 -1
- package/storages/request_manager_tandem.js +0 -1
- package/storages/request_queue.d.ts +24 -1
- package/storages/request_queue.js +80 -27
- package/storages/sitemap_request_loader.d.ts +0 -1
- package/storages/sitemap_request_loader.js +0 -1
- package/storages/storage_instance_manager.d.ts +0 -1
- package/storages/storage_instance_manager.js +0 -1
- package/storages/storage_stats.d.ts +0 -1
- package/storages/storage_stats.js +0 -1
- package/storages/utils.d.ts +0 -1
- package/storages/utils.js +0 -1
- package/typedefs.d.ts +0 -1
- package/typedefs.js +0 -1
- package/validators.d.ts +0 -1
- package/validators.js +0 -1
- package/autoscaling/autoscaled_pool.d.ts.map +0 -1
- package/autoscaling/autoscaled_pool.js.map +0 -1
- package/autoscaling/index.d.ts.map +0 -1
- package/autoscaling/index.js.map +0 -1
- package/autoscaling/snapshotter.d.ts.map +0 -1
- package/autoscaling/snapshotter.js.map +0 -1
- package/autoscaling/system_status.d.ts.map +0 -1
- package/autoscaling/system_status.js.map +0 -1
- package/configuration.d.ts.map +0 -1
- package/configuration.js.map +0 -1
- package/cookie_utils.d.ts.map +0 -1
- package/cookie_utils.js.map +0 -1
- package/crawlers/context_pipeline.d.ts.map +0 -1
- package/crawlers/context_pipeline.js.map +0 -1
- package/crawlers/crawler_commons.d.ts.map +0 -1
- package/crawlers/crawler_commons.js.map +0 -1
- package/crawlers/crawler_utils.d.ts.map +0 -1
- package/crawlers/crawler_utils.js.map +0 -1
- package/crawlers/error_snapshotter.d.ts.map +0 -1
- package/crawlers/error_snapshotter.js.map +0 -1
- package/crawlers/error_tracker.d.ts.map +0 -1
- package/crawlers/error_tracker.js.map +0 -1
- package/crawlers/index.d.ts.map +0 -1
- package/crawlers/index.js.map +0 -1
- package/crawlers/internals/types.d.ts.map +0 -1
- package/crawlers/internals/types.js.map +0 -1
- package/crawlers/statistics.d.ts.map +0 -1
- package/crawlers/statistics.js.map +0 -1
- package/enqueue_links/enqueue_links.d.ts.map +0 -1
- package/enqueue_links/enqueue_links.js.map +0 -1
- package/enqueue_links/index.d.ts.map +0 -1
- package/enqueue_links/index.js.map +0 -1
- package/enqueue_links/shared.d.ts.map +0 -1
- package/enqueue_links/shared.js.map +0 -1
- package/errors.d.ts.map +0 -1
- package/errors.js.map +0 -1
- package/events/event_manager.d.ts.map +0 -1
- package/events/event_manager.js.map +0 -1
- package/events/index.d.ts.map +0 -1
- package/events/index.js.map +0 -1
- package/events/local_event_manager.d.ts.map +0 -1
- package/events/local_event_manager.js.map +0 -1
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/log.d.ts.map +0 -1
- package/log.js.map +0 -1
- package/memory-storage/consts.d.ts.map +0 -1
- package/memory-storage/consts.js.map +0 -1
- package/memory-storage/index.d.ts.map +0 -1
- package/memory-storage/index.js.map +0 -1
- package/memory-storage/memory-storage.d.ts.map +0 -1
- package/memory-storage/memory-storage.js.map +0 -1
- package/memory-storage/resource-clients/common/base-client.d.ts.map +0 -1
- package/memory-storage/resource-clients/common/base-client.js.map +0 -1
- package/memory-storage/resource-clients/dataset.d.ts.map +0 -1
- package/memory-storage/resource-clients/dataset.js.map +0 -1
- package/memory-storage/resource-clients/key-value-store.d.ts.map +0 -1
- package/memory-storage/resource-clients/key-value-store.js.map +0 -1
- package/memory-storage/resource-clients/request-queue.d.ts.map +0 -1
- package/memory-storage/resource-clients/request-queue.js.map +0 -1
- package/memory-storage/utils.d.ts.map +0 -1
- package/memory-storage/utils.js.map +0 -1
- package/proxy_configuration.d.ts.map +0 -1
- package/proxy_configuration.js.map +0 -1
- package/recoverable_state.d.ts.map +0 -1
- package/recoverable_state.js.map +0 -1
- package/request.d.ts.map +0 -1
- package/request.js.map +0 -1
- package/router.d.ts.map +0 -1
- package/router.js.map +0 -1
- package/serialization.d.ts.map +0 -1
- package/serialization.js.map +0 -1
- package/service_locator.d.ts.map +0 -1
- package/service_locator.js.map +0 -1
- package/session_pool/consts.d.ts.map +0 -1
- package/session_pool/consts.js.map +0 -1
- package/session_pool/errors.d.ts.map +0 -1
- package/session_pool/errors.js.map +0 -1
- package/session_pool/fingerprint.d.ts.map +0 -1
- package/session_pool/fingerprint.js.map +0 -1
- package/session_pool/index.d.ts.map +0 -1
- package/session_pool/index.js.map +0 -1
- package/session_pool/session.d.ts.map +0 -1
- package/session_pool/session.js.map +0 -1
- package/session_pool/session_pool.d.ts.map +0 -1
- package/session_pool/session_pool.js.map +0 -1
- package/storages/access_checking.d.ts.map +0 -1
- package/storages/access_checking.js.map +0 -1
- package/storages/dataset.d.ts.map +0 -1
- package/storages/dataset.js.map +0 -1
- package/storages/index.d.ts.map +0 -1
- package/storages/index.js.map +0 -1
- package/storages/key_value_store.d.ts.map +0 -1
- package/storages/key_value_store.js.map +0 -1
- package/storages/key_value_store_codec.d.ts.map +0 -1
- package/storages/key_value_store_codec.js.map +0 -1
- package/storages/request_list.d.ts.map +0 -1
- package/storages/request_list.js.map +0 -1
- package/storages/request_loader.d.ts.map +0 -1
- package/storages/request_loader.js.map +0 -1
- package/storages/request_manager.d.ts.map +0 -1
- package/storages/request_manager.js.map +0 -1
- package/storages/request_manager_tandem.d.ts.map +0 -1
- package/storages/request_manager_tandem.js.map +0 -1
- package/storages/request_queue.d.ts.map +0 -1
- package/storages/request_queue.js.map +0 -1
- package/storages/sitemap_request_loader.d.ts.map +0 -1
- package/storages/sitemap_request_loader.js.map +0 -1
- package/storages/storage_instance_manager.d.ts.map +0 -1
- package/storages/storage_instance_manager.js.map +0 -1
- package/storages/storage_stats.d.ts.map +0 -1
- package/storages/storage_stats.js.map +0 -1
- package/storages/utils.d.ts.map +0 -1
- package/storages/utils.js.map +0 -1
- package/typedefs.d.ts.map +0 -1
- package/typedefs.js.map +0 -1
- package/validators.d.ts.map +0 -1
- package/validators.js.map +0 -1
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { isBuffer, isStream, toBuffer } from '@crawlee/utils';
|
|
2
|
+
/**
|
|
3
|
+
* Resolves `segment` against `baseDirectory` and ensures the result stays within `baseDirectory`.
|
|
4
|
+
* Storage names and record keys are used as filesystem path components, so a value containing `..`
|
|
5
|
+
* or an absolute path could otherwise escape the intended directory.
|
|
6
|
+
*/
|
|
7
|
+
export declare function resolveWithinDirectory(baseDirectory: string, segment: string): string;
|
|
2
8
|
/**
|
|
3
9
|
* Removes all properties with a null value
|
|
4
10
|
* from the provided object.
|
|
@@ -9,4 +15,3 @@ export declare function purgeNullsFromObject<T>(object: T): T;
|
|
|
9
15
|
*/
|
|
10
16
|
export declare function uniqueKeyToRequestId(uniqueKey: string): string;
|
|
11
17
|
export { isBuffer, isStream, toBuffer };
|
|
12
|
-
//# sourceMappingURL=utils.d.ts.map
|
package/memory-storage/utils.js
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
+
import { resolve, sep } from 'node:path';
|
|
2
3
|
import { isBuffer, isStream, toBuffer } from '@crawlee/utils';
|
|
3
4
|
import { REQUEST_ID_LENGTH } from './consts.js';
|
|
5
|
+
/**
|
|
6
|
+
* Resolves `segment` against `baseDirectory` and ensures the result stays within `baseDirectory`.
|
|
7
|
+
* Storage names and record keys are used as filesystem path components, so a value containing `..`
|
|
8
|
+
* or an absolute path could otherwise escape the intended directory.
|
|
9
|
+
*/
|
|
10
|
+
export function resolveWithinDirectory(baseDirectory, segment) {
|
|
11
|
+
const base = resolve(baseDirectory);
|
|
12
|
+
const resolved = resolve(base, segment);
|
|
13
|
+
if (resolved !== base && !resolved.startsWith(`${base}${sep}`)) {
|
|
14
|
+
throw new Error(`"${segment}" is not allowed because it would resolve outside of the storage directory. ` +
|
|
15
|
+
`Storage names and record keys must not contain path traversal segments ("..") or absolute paths.`);
|
|
16
|
+
}
|
|
17
|
+
return resolved;
|
|
18
|
+
}
|
|
4
19
|
/**
|
|
5
20
|
* Removes all properties with a null value
|
|
6
21
|
* from the provided object.
|
|
@@ -25,4 +40,3 @@ export function uniqueKeyToRequestId(uniqueKey) {
|
|
|
25
40
|
return str.length > REQUEST_ID_LENGTH ? str.slice(0, REQUEST_ID_LENGTH) : str;
|
|
26
41
|
}
|
|
27
42
|
export { isBuffer, isStream, toBuffer };
|
|
28
|
-
//# sourceMappingURL=utils.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crawlee/core",
|
|
3
|
-
"version": "4.0.0-beta.
|
|
3
|
+
"version": "4.0.0-beta.72",
|
|
4
4
|
"description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=22.0.0"
|
|
@@ -53,9 +53,9 @@
|
|
|
53
53
|
"@apify/pseudo_url": "^2.0.59",
|
|
54
54
|
"@apify/timeout": "^0.3.2",
|
|
55
55
|
"@apify/utilities": "^2.15.5",
|
|
56
|
-
"@crawlee/fs-storage": "4.0.0-beta.
|
|
57
|
-
"@crawlee/types": "4.0.0-beta.
|
|
58
|
-
"@crawlee/utils": "4.0.0-beta.
|
|
56
|
+
"@crawlee/fs-storage": "4.0.0-beta.72",
|
|
57
|
+
"@crawlee/types": "4.0.0-beta.72",
|
|
58
|
+
"@crawlee/utils": "4.0.0-beta.72",
|
|
59
59
|
"@sapphire/async-queue": "^1.5.5",
|
|
60
60
|
"@sapphire/shapeshift": "^4.0.0",
|
|
61
61
|
"@vladfrangu/async_event_emitter": "^2.4.6",
|
|
@@ -79,5 +79,5 @@
|
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
81
|
},
|
|
82
|
-
"gitHead": "
|
|
82
|
+
"gitHead": "3f698f0120bc3e6cc87b66d0127b5f36c125c255"
|
|
83
83
|
}
|
package/proxy_configuration.d.ts
CHANGED
package/proxy_configuration.js
CHANGED
package/recoverable_state.d.ts
CHANGED
package/recoverable_state.js
CHANGED
package/request.d.ts
CHANGED
package/request.js
CHANGED
package/router.d.ts
CHANGED
|
@@ -1,14 +1,57 @@
|
|
|
1
1
|
import type { Dictionary } from '@crawlee/types';
|
|
2
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
3
|
import type { CrawlingContext, LoadedRequest, RestrictedCrawlingContext } from './crawlers/crawler_commons.js';
|
|
3
4
|
import type { Request } from './request.js';
|
|
4
5
|
import type { Awaitable } from './typedefs.js';
|
|
5
|
-
|
|
6
|
+
/**
|
|
7
|
+
* The key of the default route — the fallback handler registered via {@link Router.addDefaultHandler}.
|
|
8
|
+
* Use it in a {@link RouteSchemas} map to register a schema that validates the `userData` of every request
|
|
9
|
+
* that falls through to the default handler (i.e. whose label has no route of its own).
|
|
10
|
+
*/
|
|
11
|
+
export declare const defaultRoute: unique symbol;
|
|
12
|
+
/**
|
|
13
|
+
* The crawling context received by a route handler, with `request.userData` narrowed to `UserData`.
|
|
14
|
+
*/
|
|
15
|
+
export type RouterHandlerContext<Context, UserData extends Dictionary> = Omit<Context, 'request'> & {
|
|
16
|
+
request: LoadedRequest<Request<UserData>>;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* A map of request labels to a [Standard Schema](https://standardschema.dev) (Zod, Valibot, ArkType, …)
|
|
20
|
+
* validating that label's `request.userData`. Pass it to {@link Router.create} or a `createXRouter`
|
|
21
|
+
* factory to derive the per-label `request.userData` types *and* validate them at runtime. The optional
|
|
22
|
+
* {@link defaultRoute} key registers a schema for requests handled by the default route.
|
|
23
|
+
*/
|
|
24
|
+
export type RouteSchemas = Record<string, StandardSchemaV1> & {
|
|
25
|
+
[defaultRoute]?: StandardSchemaV1;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Derives a route map (label → `userData` type) from a {@link RouteSchemas} map by inferring each
|
|
29
|
+
* schema's output type. Outputs that are not object-shaped fall back to a plain {@link Dictionary}. The
|
|
30
|
+
* {@link defaultRoute} schema drives runtime validation only, so it is excluded from the typed route map.
|
|
31
|
+
*/
|
|
32
|
+
export type RoutesFromSchemas<Schemas extends RouteSchemas> = {
|
|
33
|
+
[Label in Extract<keyof Schemas, string>]: StandardSchemaV1.InferOutput<Schemas[Label]> extends Dictionary ? StandardSchemaV1.InferOutput<Schemas[Label]> : Dictionary;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Validates `userData` against a {@link RouteSchemas|Standard Schema}, returning the parsed (and coerced)
|
|
37
|
+
* value. Throws a {@link RequestValidationError} when validation fails.
|
|
38
|
+
* @internal
|
|
39
|
+
*/
|
|
40
|
+
export declare function validateUserData(label: string | symbol, schema: StandardSchemaV1, userData: unknown): Promise<Dictionary>;
|
|
41
|
+
/**
|
|
42
|
+
* The set of labels accepted by {@link Router.addHandler}. When the router declares a concrete
|
|
43
|
+
* route map (e.g. `{ PRODUCT: ...; CATEGORY: ... }`), only those labels (plus symbols) are
|
|
44
|
+
* allowed — unknown labels become a compile-time error. When the map is left open (the default
|
|
45
|
+
* `Record<string, ...>`), any string or symbol label is accepted, preserving the original behaviour.
|
|
46
|
+
*/
|
|
47
|
+
export type RouterLabel<Routes extends Record<keyof Routes, Dictionary>> = string extends keyof Routes ? string | symbol : (keyof Routes & string) | symbol;
|
|
48
|
+
export interface RouterHandler<Context extends Omit<RestrictedCrawlingContext, 'enqueueLinks'> = CrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>> extends Router<Context, Routes> {
|
|
6
49
|
(ctx: Context): Awaitable<void>;
|
|
7
50
|
}
|
|
8
51
|
export type GetUserDataFromRequest<T> = T extends Request<infer Y> ? Y : never;
|
|
9
|
-
export type RouterRoutes<Context,
|
|
10
|
-
[
|
|
11
|
-
request: Request<
|
|
52
|
+
export type RouterRoutes<Context, Routes extends Record<keyof Routes, Dictionary>> = {
|
|
53
|
+
[Label in keyof Routes]: (ctx: Omit<Context, 'request'> & {
|
|
54
|
+
request: Request<Routes[Label]>;
|
|
12
55
|
}) => Awaitable<void>;
|
|
13
56
|
};
|
|
14
57
|
/**
|
|
@@ -75,9 +118,51 @@ export type RouterRoutes<Context, UserData extends Dictionary> = {
|
|
|
75
118
|
* ctx.log.info('...');
|
|
76
119
|
* });
|
|
77
120
|
* ```
|
|
121
|
+
*
|
|
122
|
+
* To get `request.userData` typed per label, declare a route map and pass it as the second
|
|
123
|
+
* type argument. The label passed to {@link Router.addHandler} then drives the type of
|
|
124
|
+
* `request.userData`, and unknown labels are rejected at compile time:
|
|
125
|
+
*
|
|
126
|
+
* ```ts
|
|
127
|
+
* import { createCheerioRouter, CheerioCrawlingContext } from 'crawlee';
|
|
128
|
+
*
|
|
129
|
+
* interface Routes {
|
|
130
|
+
* PRODUCT: { sku: string; price: number };
|
|
131
|
+
* CATEGORY: { categoryId: string };
|
|
132
|
+
* }
|
|
133
|
+
*
|
|
134
|
+
* const router = createCheerioRouter<CheerioCrawlingContext, Routes>();
|
|
135
|
+
*
|
|
136
|
+
* router.addHandler('PRODUCT', async ({ request }) => {
|
|
137
|
+
* request.userData.sku; // string
|
|
138
|
+
* request.userData.price; // number
|
|
139
|
+
* });
|
|
140
|
+
*
|
|
141
|
+
* router.addHandler('TYPO', async () => {}); // compile error: not a known label
|
|
142
|
+
* ```
|
|
143
|
+
*
|
|
144
|
+
* Passing a [Standard Schema](https://standardschema.dev) per label instead of a plain type both infers the
|
|
145
|
+
* `request.userData` types *and* validates them at runtime — when the request is handled, and when it is
|
|
146
|
+
* added to the crawler (`crawler.addRequests`, `context.addRequests`, `enqueueLinks`). A failing request
|
|
147
|
+
* throws a {@link RequestValidationError}.
|
|
148
|
+
*
|
|
149
|
+
* ```ts
|
|
150
|
+
* import { z } from 'zod';
|
|
151
|
+
* import { createCheerioRouter } from 'crawlee';
|
|
152
|
+
*
|
|
153
|
+
* const router = createCheerioRouter({
|
|
154
|
+
* PRODUCT: z.object({ sku: z.string(), price: z.number() }),
|
|
155
|
+
* CATEGORY: z.object({ categoryId: z.string() }),
|
|
156
|
+
* });
|
|
157
|
+
*
|
|
158
|
+
* router.addHandler('PRODUCT', async ({ request }) => {
|
|
159
|
+
* request.userData.price; // number, inferred from the schema and validated at runtime
|
|
160
|
+
* });
|
|
161
|
+
* ```
|
|
78
162
|
*/
|
|
79
|
-
export declare class Router<Context extends Omit<RestrictedCrawlingContext, 'enqueueLinks'
|
|
163
|
+
export declare class Router<Context extends Omit<RestrictedCrawlingContext, 'enqueueLinks'>, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>> {
|
|
80
164
|
private readonly routes;
|
|
165
|
+
private readonly schemas;
|
|
81
166
|
private readonly middlewares;
|
|
82
167
|
/**
|
|
83
168
|
* use Router.create() instead!
|
|
@@ -85,17 +170,28 @@ export declare class Router<Context extends Omit<RestrictedCrawlingContext, 'enq
|
|
|
85
170
|
*/
|
|
86
171
|
protected constructor();
|
|
87
172
|
/**
|
|
88
|
-
* Registers new route handler for given label.
|
|
173
|
+
* Registers new route handler for given label. When the router declares a route map, the
|
|
174
|
+
* `label` is restricted to the declared labels and `request.userData` is typed accordingly.
|
|
175
|
+
*/
|
|
176
|
+
addHandler<Label extends keyof Routes & string>(label: Label, handler: (ctx: RouterHandlerContext<Context, Routes[Label]>) => Awaitable<void>): void;
|
|
177
|
+
/**
|
|
178
|
+
* Registers new route handler for given label, explicitly typing `request.userData` via the
|
|
179
|
+
* `UserData` type argument. Useful when the router has no declared route map (the open default)
|
|
180
|
+
* and you want to type a single handler, or to register a handler under a `symbol` label.
|
|
89
181
|
*/
|
|
90
|
-
addHandler<UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(label:
|
|
91
|
-
request: LoadedRequest<Request<UserData>>;
|
|
92
|
-
}) => Awaitable<void>): void;
|
|
182
|
+
addHandler<UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(label: RouterLabel<Routes>, handler: (ctx: RouterHandlerContext<Context, UserData>) => Awaitable<void>): void;
|
|
93
183
|
/**
|
|
94
|
-
* Registers default route handler.
|
|
184
|
+
* Registers default route handler. As a fallback it can receive any request (including labels not
|
|
185
|
+
* declared in the route map), so `request.userData` defaults to the context's `userData` type
|
|
186
|
+
* (loosely typed by default). Pass an explicit `UserData` type argument to narrow it.
|
|
95
187
|
*/
|
|
96
|
-
addDefaultHandler<UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(handler: (ctx:
|
|
97
|
-
|
|
98
|
-
|
|
188
|
+
addDefaultHandler<UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(handler: (ctx: RouterHandlerContext<Context, UserData>) => Awaitable<void>): void;
|
|
189
|
+
/**
|
|
190
|
+
* Returns the {@link RouteSchemas|Standard Schema} registered for a label, if any. Used by the crawler
|
|
191
|
+
* to validate `request.userData` when requests are added.
|
|
192
|
+
* @internal
|
|
193
|
+
*/
|
|
194
|
+
getSchema(label?: string | symbol): StandardSchemaV1 | undefined;
|
|
99
195
|
/**
|
|
100
196
|
* Registers a middleware that will be fired before the matching route handler.
|
|
101
197
|
* Multiple middlewares can be registered, they will be fired in the same order.
|
|
@@ -105,6 +201,11 @@ export declare class Router<Context extends Omit<RestrictedCrawlingContext, 'enq
|
|
|
105
201
|
* Returns route handler for given label. If no label is provided, the default request handler will be returned.
|
|
106
202
|
*/
|
|
107
203
|
getHandler(label?: string | symbol): (ctx: Context) => Awaitable<void>;
|
|
204
|
+
/**
|
|
205
|
+
* Validates `request.userData` against the schema registered for its label (if any), replacing it with
|
|
206
|
+
* the parsed value. Throws a {@link RequestValidationError} when validation fails.
|
|
207
|
+
*/
|
|
208
|
+
private validateRequest;
|
|
108
209
|
/**
|
|
109
210
|
* Throws when the label already exists in our registry.
|
|
110
211
|
*/
|
|
@@ -129,6 +230,7 @@ export declare class Router<Context extends Omit<RestrictedCrawlingContext, 'enq
|
|
|
129
230
|
* await crawler.run();
|
|
130
231
|
* ```
|
|
131
232
|
*/
|
|
132
|
-
static create<Context extends Omit<RestrictedCrawlingContext, 'enqueueLinks'> = CrawlingContext,
|
|
233
|
+
static create<Context extends Omit<RestrictedCrawlingContext, 'enqueueLinks'> = CrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
|
|
234
|
+
static create<Context extends Omit<RestrictedCrawlingContext, 'enqueueLinks'> = CrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
|
|
235
|
+
static create<Context extends Omit<RestrictedCrawlingContext, 'enqueueLinks'> = CrawlingContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;
|
|
133
236
|
}
|
|
134
|
-
//# sourceMappingURL=router.d.ts.map
|
package/router.js
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
|
-
import { MissingRouteError } from './errors.js';
|
|
2
|
-
|
|
1
|
+
import { MissingRouteError, RequestValidationError } from './errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* The key of the default route — the fallback handler registered via {@link Router.addDefaultHandler}.
|
|
4
|
+
* Use it in a {@link RouteSchemas} map to register a schema that validates the `userData` of every request
|
|
5
|
+
* that falls through to the default handler (i.e. whose label has no route of its own).
|
|
6
|
+
*/
|
|
7
|
+
export const defaultRoute = Symbol('default-route');
|
|
8
|
+
/** Whether a validation issue points at the top-level `label` key. */
|
|
9
|
+
function isLabelIssue(issue) {
|
|
10
|
+
if (issue.path?.length !== 1) {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
const [segment] = issue.path;
|
|
14
|
+
return (typeof segment === 'object' ? segment.key : segment) === 'label';
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Validates `userData` against a {@link RouteSchemas|Standard Schema}, returning the parsed (and coerced)
|
|
18
|
+
* value. Throws a {@link RequestValidationError} when validation fails.
|
|
19
|
+
* @internal
|
|
20
|
+
*/
|
|
21
|
+
export async function validateUserData(label, schema, userData) {
|
|
22
|
+
const { label: _label, ...rest } = (userData ?? {});
|
|
23
|
+
// `label` is a Crawlee-managed key that lives inside `userData`, so validating it is opt-in: we validate
|
|
24
|
+
// without it first, letting schemas that don't describe it pass (including `.strict()` ones). A schema that
|
|
25
|
+
// *does* declare `label` reports an issue for the now-missing key — so we re-validate with it included,
|
|
26
|
+
// honouring the declaration. Unlike `userData.__crawlee`, `label` is enumerable, so schemas do see it.
|
|
27
|
+
let result = await schema['~standard'].validate(rest);
|
|
28
|
+
if (result.issues?.some(isLabelIssue)) {
|
|
29
|
+
result = await schema['~standard'].validate({ ...rest, label });
|
|
30
|
+
}
|
|
31
|
+
if (result.issues) {
|
|
32
|
+
throw new RequestValidationError(label, result.issues);
|
|
33
|
+
}
|
|
34
|
+
// Restore the label so it survives schemas that strip undeclared keys.
|
|
35
|
+
return { ...result.value, label };
|
|
36
|
+
}
|
|
3
37
|
/**
|
|
4
38
|
* Simple router that works based on request labels. This instance can then serve as a `requestHandler` of your crawler.
|
|
5
39
|
*
|
|
@@ -64,29 +98,90 @@ const defaultRoute = Symbol('default-route');
|
|
|
64
98
|
* ctx.log.info('...');
|
|
65
99
|
* });
|
|
66
100
|
* ```
|
|
101
|
+
*
|
|
102
|
+
* To get `request.userData` typed per label, declare a route map and pass it as the second
|
|
103
|
+
* type argument. The label passed to {@link Router.addHandler} then drives the type of
|
|
104
|
+
* `request.userData`, and unknown labels are rejected at compile time:
|
|
105
|
+
*
|
|
106
|
+
* ```ts
|
|
107
|
+
* import { createCheerioRouter, CheerioCrawlingContext } from 'crawlee';
|
|
108
|
+
*
|
|
109
|
+
* interface Routes {
|
|
110
|
+
* PRODUCT: { sku: string; price: number };
|
|
111
|
+
* CATEGORY: { categoryId: string };
|
|
112
|
+
* }
|
|
113
|
+
*
|
|
114
|
+
* const router = createCheerioRouter<CheerioCrawlingContext, Routes>();
|
|
115
|
+
*
|
|
116
|
+
* router.addHandler('PRODUCT', async ({ request }) => {
|
|
117
|
+
* request.userData.sku; // string
|
|
118
|
+
* request.userData.price; // number
|
|
119
|
+
* });
|
|
120
|
+
*
|
|
121
|
+
* router.addHandler('TYPO', async () => {}); // compile error: not a known label
|
|
122
|
+
* ```
|
|
123
|
+
*
|
|
124
|
+
* Passing a [Standard Schema](https://standardschema.dev) per label instead of a plain type both infers the
|
|
125
|
+
* `request.userData` types *and* validates them at runtime — when the request is handled, and when it is
|
|
126
|
+
* added to the crawler (`crawler.addRequests`, `context.addRequests`, `enqueueLinks`). A failing request
|
|
127
|
+
* throws a {@link RequestValidationError}.
|
|
128
|
+
*
|
|
129
|
+
* ```ts
|
|
130
|
+
* import { z } from 'zod';
|
|
131
|
+
* import { createCheerioRouter } from 'crawlee';
|
|
132
|
+
*
|
|
133
|
+
* const router = createCheerioRouter({
|
|
134
|
+
* PRODUCT: z.object({ sku: z.string(), price: z.number() }),
|
|
135
|
+
* CATEGORY: z.object({ categoryId: z.string() }),
|
|
136
|
+
* });
|
|
137
|
+
*
|
|
138
|
+
* router.addHandler('PRODUCT', async ({ request }) => {
|
|
139
|
+
* request.userData.price; // number, inferred from the schema and validated at runtime
|
|
140
|
+
* });
|
|
141
|
+
* ```
|
|
67
142
|
*/
|
|
68
143
|
export class Router {
|
|
69
144
|
routes = new Map();
|
|
145
|
+
schemas = new Map();
|
|
70
146
|
middlewares = [];
|
|
71
147
|
/**
|
|
72
148
|
* use Router.create() instead!
|
|
73
149
|
* @ignore
|
|
74
150
|
*/
|
|
75
151
|
constructor() { }
|
|
76
|
-
/**
|
|
77
|
-
* Registers new route handler for given label.
|
|
78
|
-
*/
|
|
79
152
|
addHandler(label, handler) {
|
|
80
153
|
this.validate(label);
|
|
81
154
|
this.routes.set(label, handler);
|
|
82
155
|
}
|
|
83
156
|
/**
|
|
84
|
-
* Registers default route handler.
|
|
157
|
+
* Registers default route handler. As a fallback it can receive any request (including labels not
|
|
158
|
+
* declared in the route map), so `request.userData` defaults to the context's `userData` type
|
|
159
|
+
* (loosely typed by default). Pass an explicit `UserData` type argument to narrow it.
|
|
85
160
|
*/
|
|
86
161
|
addDefaultHandler(handler) {
|
|
87
162
|
this.validate(defaultRoute);
|
|
88
163
|
this.routes.set(defaultRoute, handler);
|
|
89
164
|
}
|
|
165
|
+
/**
|
|
166
|
+
* Returns the {@link RouteSchemas|Standard Schema} registered for a label, if any. Used by the crawler
|
|
167
|
+
* to validate `request.userData` when requests are added.
|
|
168
|
+
* @internal
|
|
169
|
+
*/
|
|
170
|
+
getSchema(label) {
|
|
171
|
+
if (label != null) {
|
|
172
|
+
const schema = this.schemas.get(label);
|
|
173
|
+
if (schema) {
|
|
174
|
+
return schema;
|
|
175
|
+
}
|
|
176
|
+
// A label with its own route is fully specified; don't fall back to the default-route schema.
|
|
177
|
+
if (this.routes.has(label)) {
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
// Requests with no route of their own fall through to the default handler, so validate their
|
|
182
|
+
// `userData` against the default-route schema, if one was registered.
|
|
183
|
+
return this.schemas.get(defaultRoute);
|
|
184
|
+
}
|
|
90
185
|
/**
|
|
91
186
|
* Registers a middleware that will be fired before the matching route handler.
|
|
92
187
|
* Multiple middlewares can be registered, they will be fired in the same order.
|
|
@@ -108,6 +203,17 @@ export class Router {
|
|
|
108
203
|
' You must set up a route for this label or a default route.' +
|
|
109
204
|
' Use `requestHandler`, `router.addHandler` or `router.addDefaultHandler`.');
|
|
110
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* Validates `request.userData` against the schema registered for its label (if any), replacing it with
|
|
208
|
+
* the parsed value. Throws a {@link RequestValidationError} when validation fails.
|
|
209
|
+
*/
|
|
210
|
+
async validateRequest(context) {
|
|
211
|
+
const label = context.request.label;
|
|
212
|
+
const schema = this.getSchema(label);
|
|
213
|
+
if (schema) {
|
|
214
|
+
context.request.userData = (await validateUserData(label, schema, context.request.userData));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
111
217
|
/**
|
|
112
218
|
* Throws when the label already exists in our registry.
|
|
113
219
|
*/
|
|
@@ -119,39 +225,28 @@ export class Router {
|
|
|
119
225
|
throw new Error(message);
|
|
120
226
|
}
|
|
121
227
|
}
|
|
122
|
-
|
|
123
|
-
* Creates new router instance. This instance can then serve as a `requestHandler` of your crawler.
|
|
124
|
-
*
|
|
125
|
-
* ```ts
|
|
126
|
-
* import { Router, CheerioCrawler, CheerioCrawlingContext } from 'crawlee';
|
|
127
|
-
*
|
|
128
|
-
* const router = Router.create<CheerioCrawlingContext>();
|
|
129
|
-
* router.addHandler('label-a', async (ctx) => {
|
|
130
|
-
* ctx.log.info('...');
|
|
131
|
-
* });
|
|
132
|
-
* router.addDefaultHandler(async (ctx) => {
|
|
133
|
-
* ctx.log.info('...');
|
|
134
|
-
* });
|
|
135
|
-
*
|
|
136
|
-
* const crawler = new CheerioCrawler({
|
|
137
|
-
* requestHandler: router,
|
|
138
|
-
* });
|
|
139
|
-
* await crawler.run();
|
|
140
|
-
* ```
|
|
141
|
-
*/
|
|
142
|
-
static create(routes) {
|
|
228
|
+
static create(routesOrSchemas) {
|
|
143
229
|
const router = new Router();
|
|
144
230
|
const obj = Object.create(Function.prototype);
|
|
145
231
|
obj.addHandler = router.addHandler.bind(router);
|
|
146
232
|
obj.addDefaultHandler = router.addDefaultHandler.bind(router);
|
|
233
|
+
obj.getSchema = router.getSchema.bind(router);
|
|
147
234
|
obj.getHandler = router.getHandler.bind(router);
|
|
148
235
|
obj.use = router.use.bind(router);
|
|
149
|
-
|
|
150
|
-
|
|
236
|
+
// `Reflect.ownKeys` (unlike `Object.entries`) also yields the `defaultRoute` symbol key.
|
|
237
|
+
for (const label of Reflect.ownKeys(routesOrSchemas ?? {})) {
|
|
238
|
+
const value = routesOrSchemas[label];
|
|
239
|
+
if (typeof value === 'function') {
|
|
240
|
+
router.addHandler(label, value);
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
router.schemas.set(label, value);
|
|
244
|
+
}
|
|
151
245
|
}
|
|
152
246
|
const func = async function (context) {
|
|
153
247
|
const { url, loadedUrl, label } = context.request;
|
|
154
248
|
context.log.debug('Page opened.', { label, url: loadedUrl ?? url });
|
|
249
|
+
await router.validateRequest(context);
|
|
155
250
|
for (const middleware of router.middlewares) {
|
|
156
251
|
await middleware(context);
|
|
157
252
|
}
|
|
@@ -161,4 +256,3 @@ export class Router {
|
|
|
161
256
|
return func;
|
|
162
257
|
}
|
|
163
258
|
}
|
|
164
|
-
//# sourceMappingURL=router.js.map
|
package/serialization.d.ts
CHANGED
package/serialization.js
CHANGED
package/service_locator.d.ts
CHANGED
package/service_locator.js
CHANGED
|
@@ -236,4 +236,3 @@ export const serviceLocator = new Proxy({}, {
|
|
|
236
236
|
throw new TypeError(`Cannot set property '${String(prop)}' on serviceLocator directly. Use the setter methods (e.g. setConfiguration(), setStorageBackend()) instead.`);
|
|
237
237
|
},
|
|
238
238
|
});
|
|
239
|
-
//# sourceMappingURL=service_locator.js.map
|
package/session_pool/consts.d.ts
CHANGED
package/session_pool/consts.js
CHANGED
package/session_pool/errors.d.ts
CHANGED
package/session_pool/errors.js
CHANGED
package/session_pool/index.d.ts
CHANGED
package/session_pool/index.js
CHANGED
package/session_pool/session.js
CHANGED
|
@@ -10,4 +10,3 @@ export declare const checkStorageAccess: () => void | undefined;
|
|
|
10
10
|
* @param callback The code that should be invoked with the `checkFunction` setting
|
|
11
11
|
*/
|
|
12
12
|
export declare const withCheckedStorageAccess: <T>(checkFunction: () => void, callback: () => Awaitable<T>) => Promise<T>;
|
|
13
|
-
//# sourceMappingURL=access_checking.d.ts.map
|
|
@@ -15,4 +15,3 @@ export const checkStorageAccess = () => {
|
|
|
15
15
|
* @param callback The code that should be invoked with the `checkFunction` setting
|
|
16
16
|
*/
|
|
17
17
|
export const withCheckedStorageAccess = async (checkFunction, callback) => storage.run({ checkFunction }, callback);
|
|
18
|
-
//# sourceMappingURL=access_checking.js.map
|
package/storages/dataset.d.ts
CHANGED
|
@@ -295,7 +295,7 @@ export declare class Dataset<Data extends Dictionary = Dictionary> {
|
|
|
295
295
|
* If the dataset is empty, reduce will return undefined.
|
|
296
296
|
*
|
|
297
297
|
* @param iteratee
|
|
298
|
-
* @param memo Unset parameter,
|
|
298
|
+
* @param memo Unset parameter, necessary to be able to pass options
|
|
299
299
|
* @param [options] An object containing extra options for `reduce()`
|
|
300
300
|
*/
|
|
301
301
|
reduce(iteratee: DatasetReducer<Data, Data>, memo: undefined, options: DatasetIteratorOptions): Promise<Data | undefined>;
|
|
@@ -478,4 +478,3 @@ export interface DatasetContent<Data> {
|
|
|
478
478
|
/** Should the results be in descending order. */
|
|
479
479
|
desc?: boolean;
|
|
480
480
|
}
|
|
481
|
-
//# sourceMappingURL=dataset.d.ts.map
|
package/storages/dataset.js
CHANGED
package/storages/index.d.ts
CHANGED
package/storages/index.js
CHANGED