@crawlee/core 4.0.0-beta.9 → 4.0.0-beta.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +66 -153
  3. package/autoscaling/autoscaled_pool.js +95 -251
  4. package/autoscaling/client_load_signal.d.ts +59 -0
  5. package/autoscaling/client_load_signal.js +73 -0
  6. package/autoscaling/concurrency_system.d.ts +283 -0
  7. package/autoscaling/concurrency_system.js +350 -0
  8. package/autoscaling/cpu_load_signal.d.ts +44 -0
  9. package/autoscaling/cpu_load_signal.js +46 -0
  10. package/autoscaling/event_loop_load_signal.d.ts +54 -0
  11. package/autoscaling/event_loop_load_signal.js +60 -0
  12. package/autoscaling/index.d.ts +6 -1
  13. package/autoscaling/index.js +6 -1
  14. package/autoscaling/load_signal.d.ts +99 -0
  15. package/autoscaling/load_signal.js +103 -0
  16. package/autoscaling/memory_load_signal.d.ts +56 -0
  17. package/autoscaling/memory_load_signal.js +106 -0
  18. package/autoscaling/snapshotter.d.ts +61 -163
  19. package/autoscaling/snapshotter.js +45 -263
  20. package/autoscaling/system_status.d.ts +63 -83
  21. package/autoscaling/system_status.js +90 -120
  22. package/configuration.d.ts +90 -223
  23. package/configuration.js +164 -222
  24. package/cookie_utils.d.ts +4 -3
  25. package/cookie_utils.js +20 -13
  26. package/crawlers/context_pipeline.d.ts +70 -0
  27. package/crawlers/context_pipeline.js +122 -0
  28. package/crawlers/crawler_commons.d.ts +76 -33
  29. package/crawlers/crawler_commons.js +15 -24
  30. package/crawlers/crawler_utils.d.ts +2 -3
  31. package/crawlers/crawler_utils.js +1 -2
  32. package/crawlers/error_snapshotter.d.ts +3 -3
  33. package/crawlers/error_snapshotter.js +2 -3
  34. package/crawlers/error_tracker.d.ts +2 -2
  35. package/crawlers/error_tracker.js +0 -1
  36. package/crawlers/index.d.ts +1 -2
  37. package/crawlers/index.js +1 -2
  38. package/crawlers/internals/types.d.ts +7 -0
  39. package/crawlers/internals/types.js +1 -0
  40. package/crawlers/statistics.d.ts +28 -23
  41. package/crawlers/statistics.js +38 -34
  42. package/debug.d.ts +36 -0
  43. package/debug.js +70 -0
  44. package/enqueue_links/enqueue_links.d.ts +44 -22
  45. package/enqueue_links/enqueue_links.js +51 -30
  46. package/enqueue_links/index.d.ts +0 -1
  47. package/enqueue_links/index.js +0 -1
  48. package/enqueue_links/shared.d.ts +25 -9
  49. package/enqueue_links/shared.js +69 -38
  50. package/errors.d.ts +53 -4
  51. package/errors.js +70 -5
  52. package/events/event_manager.d.ts +34 -8
  53. package/events/event_manager.js +8 -10
  54. package/events/index.d.ts +0 -1
  55. package/events/index.js +0 -1
  56. package/events/local_event_manager.d.ts +15 -3
  57. package/events/local_event_manager.js +37 -11
  58. package/index.d.ts +6 -3
  59. package/index.js +5 -2
  60. package/log.d.ts +82 -3
  61. package/log.js +102 -1
  62. package/memory-storage/consts.d.ts +4 -0
  63. package/memory-storage/consts.js +4 -0
  64. package/memory-storage/index.d.ts +1 -0
  65. package/memory-storage/index.js +1 -0
  66. package/memory-storage/memory-storage.d.ts +46 -0
  67. package/memory-storage/memory-storage.js +136 -0
  68. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  69. package/memory-storage/resource-clients/common/base-client.js +6 -0
  70. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  71. package/memory-storage/resource-clients/dataset.js +113 -0
  72. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  73. package/memory-storage/resource-clients/key-value-store.js +203 -0
  74. package/memory-storage/resource-clients/request-queue.d.ts +96 -0
  75. package/memory-storage/resource-clients/request-queue.js +421 -0
  76. package/memory-storage/utils.d.ts +17 -0
  77. package/memory-storage/utils.js +42 -0
  78. package/owned_or_injected.d.ts +60 -0
  79. package/owned_or_injected.js +98 -0
  80. package/package.json +12 -10
  81. package/proxy_configuration.d.ts +29 -152
  82. package/proxy_configuration.js +21 -173
  83. package/recoverable_state.d.ts +120 -0
  84. package/recoverable_state.js +143 -0
  85. package/request.d.ts +84 -13
  86. package/request.js +107 -28
  87. package/router.d.ts +143 -17
  88. package/router.js +125 -30
  89. package/serialization.d.ts +0 -1
  90. package/serialization.js +1 -2
  91. package/service_locator.d.ts +156 -0
  92. package/service_locator.js +238 -0
  93. package/session_pool/consts.d.ts +1 -2
  94. package/session_pool/consts.js +1 -2
  95. package/session_pool/errors.d.ts +0 -1
  96. package/session_pool/errors.js +0 -1
  97. package/session_pool/fingerprint.d.ts +9 -0
  98. package/session_pool/fingerprint.js +30 -0
  99. package/session_pool/index.d.ts +0 -2
  100. package/session_pool/index.js +0 -2
  101. package/session_pool/session.d.ts +37 -75
  102. package/session_pool/session.js +49 -102
  103. package/session_pool/session_pool.d.ts +85 -90
  104. package/session_pool/session_pool.js +131 -120
  105. package/storages/access_checking.d.ts +0 -1
  106. package/storages/access_checking.js +5 -2
  107. package/storages/dataset.d.ts +103 -53
  108. package/storages/dataset.js +174 -132
  109. package/storages/index.d.ts +8 -7
  110. package/storages/index.js +6 -7
  111. package/storages/key_value_store.d.ts +167 -38
  112. package/storages/key_value_store.js +274 -127
  113. package/storages/key_value_store_codec.d.ts +32 -0
  114. package/storages/key_value_store_codec.js +113 -0
  115. package/storages/request_dedup_cache.d.ts +23 -0
  116. package/storages/request_dedup_cache.js +48 -0
  117. package/storages/request_list.d.ts +54 -98
  118. package/storages/request_list.js +99 -75
  119. package/storages/request_loader.d.ts +96 -0
  120. package/storages/request_loader.js +1 -0
  121. package/storages/request_manager.d.ts +33 -0
  122. package/storages/request_manager.js +1 -0
  123. package/storages/request_manager_tandem.d.ts +106 -0
  124. package/storages/request_manager_tandem.js +197 -0
  125. package/storages/request_queue.d.ts +290 -47
  126. package/storages/request_queue.js +629 -215
  127. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +28 -24
  128. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +49 -47
  129. package/storages/storage_instance_manager.d.ts +91 -0
  130. package/storages/storage_instance_manager.js +258 -0
  131. package/storages/storage_stats.d.ts +48 -0
  132. package/storages/storage_stats.js +29 -0
  133. package/storages/utils.d.ts +54 -9
  134. package/storages/utils.js +64 -13
  135. package/system-info/cpu-info.d.ts +67 -0
  136. package/system-info/cpu-info.js +216 -0
  137. package/system-info/memory-info.d.ts +31 -0
  138. package/system-info/memory-info.js +115 -0
  139. package/system-info/ps-tree.d.ts +17 -0
  140. package/system-info/ps-tree.js +144 -0
  141. package/system-info/runtime.d.ts +14 -0
  142. package/system-info/runtime.js +80 -0
  143. package/typedefs.d.ts +1 -2
  144. package/typedefs.js +0 -1
  145. package/validators.d.ts +8 -1
  146. package/validators.js +10 -3
  147. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  148. package/autoscaling/autoscaled_pool.js.map +0 -1
  149. package/autoscaling/index.d.ts.map +0 -1
  150. package/autoscaling/index.js.map +0 -1
  151. package/autoscaling/snapshotter.d.ts.map +0 -1
  152. package/autoscaling/snapshotter.js.map +0 -1
  153. package/autoscaling/system_status.d.ts.map +0 -1
  154. package/autoscaling/system_status.js.map +0 -1
  155. package/configuration.d.ts.map +0 -1
  156. package/configuration.js.map +0 -1
  157. package/cookie_utils.d.ts.map +0 -1
  158. package/cookie_utils.js.map +0 -1
  159. package/crawlers/crawler_commons.d.ts.map +0 -1
  160. package/crawlers/crawler_commons.js.map +0 -1
  161. package/crawlers/crawler_extension.d.ts +0 -12
  162. package/crawlers/crawler_extension.d.ts.map +0 -1
  163. package/crawlers/crawler_extension.js +0 -14
  164. package/crawlers/crawler_extension.js.map +0 -1
  165. package/crawlers/crawler_utils.d.ts.map +0 -1
  166. package/crawlers/crawler_utils.js.map +0 -1
  167. package/crawlers/error_snapshotter.d.ts.map +0 -1
  168. package/crawlers/error_snapshotter.js.map +0 -1
  169. package/crawlers/error_tracker.d.ts.map +0 -1
  170. package/crawlers/error_tracker.js.map +0 -1
  171. package/crawlers/index.d.ts.map +0 -1
  172. package/crawlers/index.js.map +0 -1
  173. package/crawlers/statistics.d.ts.map +0 -1
  174. package/crawlers/statistics.js.map +0 -1
  175. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  176. package/enqueue_links/enqueue_links.js.map +0 -1
  177. package/enqueue_links/index.d.ts.map +0 -1
  178. package/enqueue_links/index.js.map +0 -1
  179. package/enqueue_links/shared.d.ts.map +0 -1
  180. package/enqueue_links/shared.js.map +0 -1
  181. package/errors.d.ts.map +0 -1
  182. package/errors.js.map +0 -1
  183. package/events/event_manager.d.ts.map +0 -1
  184. package/events/event_manager.js.map +0 -1
  185. package/events/index.d.ts.map +0 -1
  186. package/events/index.js.map +0 -1
  187. package/events/local_event_manager.d.ts.map +0 -1
  188. package/events/local_event_manager.js.map +0 -1
  189. package/http_clients/base-http-client.d.ts +0 -134
  190. package/http_clients/base-http-client.d.ts.map +0 -1
  191. package/http_clients/base-http-client.js +0 -33
  192. package/http_clients/base-http-client.js.map +0 -1
  193. package/http_clients/form-data-like.d.ts +0 -67
  194. package/http_clients/form-data-like.d.ts.map +0 -1
  195. package/http_clients/form-data-like.js +0 -5
  196. package/http_clients/form-data-like.js.map +0 -1
  197. package/http_clients/got-scraping-http-client.d.ts +0 -15
  198. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  199. package/http_clients/got-scraping-http-client.js +0 -69
  200. package/http_clients/got-scraping-http-client.js.map +0 -1
  201. package/http_clients/index.d.ts +0 -3
  202. package/http_clients/index.d.ts.map +0 -1
  203. package/http_clients/index.js +0 -3
  204. package/http_clients/index.js.map +0 -1
  205. package/index.d.ts.map +0 -1
  206. package/index.js.map +0 -1
  207. package/log.d.ts.map +0 -1
  208. package/log.js.map +0 -1
  209. package/proxy_configuration.d.ts.map +0 -1
  210. package/proxy_configuration.js.map +0 -1
  211. package/request.d.ts.map +0 -1
  212. package/request.js.map +0 -1
  213. package/router.d.ts.map +0 -1
  214. package/router.js.map +0 -1
  215. package/serialization.d.ts.map +0 -1
  216. package/serialization.js.map +0 -1
  217. package/session_pool/consts.d.ts.map +0 -1
  218. package/session_pool/consts.js.map +0 -1
  219. package/session_pool/errors.d.ts.map +0 -1
  220. package/session_pool/errors.js.map +0 -1
  221. package/session_pool/events.d.ts +0 -3
  222. package/session_pool/events.d.ts.map +0 -1
  223. package/session_pool/events.js +0 -3
  224. package/session_pool/events.js.map +0 -1
  225. package/session_pool/index.d.ts.map +0 -1
  226. package/session_pool/index.js.map +0 -1
  227. package/session_pool/session.d.ts.map +0 -1
  228. package/session_pool/session.js.map +0 -1
  229. package/session_pool/session_pool.d.ts.map +0 -1
  230. package/session_pool/session_pool.js.map +0 -1
  231. package/storages/access_checking.d.ts.map +0 -1
  232. package/storages/access_checking.js.map +0 -1
  233. package/storages/dataset.d.ts.map +0 -1
  234. package/storages/dataset.js.map +0 -1
  235. package/storages/index.d.ts.map +0 -1
  236. package/storages/index.js.map +0 -1
  237. package/storages/key_value_store.d.ts.map +0 -1
  238. package/storages/key_value_store.js.map +0 -1
  239. package/storages/request_list.d.ts.map +0 -1
  240. package/storages/request_list.js.map +0 -1
  241. package/storages/request_provider.d.ts +0 -307
  242. package/storages/request_provider.d.ts.map +0 -1
  243. package/storages/request_provider.js +0 -555
  244. package/storages/request_provider.js.map +0 -1
  245. package/storages/request_queue.d.ts.map +0 -1
  246. package/storages/request_queue.js.map +0 -1
  247. package/storages/request_queue_v2.d.ts +0 -87
  248. package/storages/request_queue_v2.d.ts.map +0 -1
  249. package/storages/request_queue_v2.js +0 -438
  250. package/storages/request_queue_v2.js.map +0 -1
  251. package/storages/sitemap_request_list.d.ts.map +0 -1
  252. package/storages/sitemap_request_list.js.map +0 -1
  253. package/storages/storage_manager.d.ts +0 -58
  254. package/storages/storage_manager.d.ts.map +0 -1
  255. package/storages/storage_manager.js +0 -105
  256. package/storages/storage_manager.js.map +0 -1
  257. package/storages/utils.d.ts.map +0 -1
  258. package/storages/utils.js.map +0 -1
  259. package/tsconfig.build.tsbuildinfo +0 -1
  260. package/typedefs.d.ts.map +0 -1
  261. package/typedefs.js.map +0 -1
  262. package/validators.d.ts.map +0 -1
  263. package/validators.js.map +0 -1
@@ -0,0 +1,122 @@
1
+ import { ContextPipelineCleanupError, ContextPipelineInitializationError, ContextPipelineInterruptedError, RequestHandlerError, SessionError, } from '../errors.js';
2
+ import { serviceLocator } from '../service_locator.js';
3
+ /**
4
+ * Encapsulates the logic of gradually enhancing the crawling context with additional information and utilities.
5
+ *
6
+ * The enhancement is done by a chain of middlewares that are added to the pipeline after its creation.
7
+ * This class provides a type-safe way to build a pipeline of context transformations where each step
8
+ * can enhance the context with additional properties or utilities.
9
+ *
10
+ * @template TContextBase - The base context type that serves as the starting point
11
+ * @template TCrawlingContext - The final context type after all middleware transformations
12
+ */
13
+ export class ContextPipeline {
14
+ /**
15
+ * Creates a new empty context pipeline.
16
+ *
17
+ * @template TContextBase - The base context type for the pipeline
18
+ * @returns A new ContextPipeline instance with no transformations
19
+ */
20
+ static create() {
21
+ return new ContextPipelineImpl({ action: async (context) => context });
22
+ }
23
+ }
24
+ /**
25
+ * Implementation of the `ContextPipeline` logic. This hides implementation details such as the `middleware` and `parent`
26
+ * properties from the `ContextPipeline` interface, making type checking more reliable.
27
+ */
28
+ class ContextPipelineImpl extends ContextPipeline {
29
+ middleware;
30
+ parent;
31
+ constructor(middleware, parent) {
32
+ super();
33
+ this.middleware = middleware;
34
+ this.parent = parent;
35
+ }
36
+ /**
37
+ * @inheritdoc
38
+ */
39
+ compose(middleware) {
40
+ return new ContextPipelineImpl(middleware, this);
41
+ }
42
+ chain(other) {
43
+ const otherMiddlewares = Array.from(other.middlewareChain()).reverse();
44
+ let result = this;
45
+ for (const middleware of otherMiddlewares) {
46
+ result = result.compose(middleware);
47
+ }
48
+ return result;
49
+ }
50
+ *middlewareChain() {
51
+ let step = this;
52
+ while (step !== undefined) {
53
+ yield step.middleware;
54
+ step = step.parent;
55
+ }
56
+ }
57
+ /**
58
+ * @inheritdoc
59
+ */
60
+ async call(crawlingContext, finalContextConsumer) {
61
+ const middlewares = Array.from(this.middlewareChain()).reverse();
62
+ const cleanupStack = [];
63
+ let consumerException;
64
+ try {
65
+ for (const { action, cleanup } of middlewares) {
66
+ try {
67
+ const contextExtension = await action(crawlingContext);
68
+ const extensionNames = [
69
+ ...Object.getOwnPropertyNames(contextExtension),
70
+ ...Object.getOwnPropertySymbols(contextExtension),
71
+ ];
72
+ for (const key of extensionNames) {
73
+ try {
74
+ if (Object.getOwnPropertyDescriptor(crawlingContext, key)?.configurable !== false) {
75
+ Object.defineProperty(crawlingContext, key, Object.getOwnPropertyDescriptor(contextExtension, key));
76
+ }
77
+ }
78
+ catch (error) {
79
+ serviceLocator
80
+ .getLogger()
81
+ .debug(`Context pipeline failed to define property ${key.toString()}:`, error);
82
+ }
83
+ }
84
+ if (cleanup) {
85
+ cleanupStack.push(cleanup);
86
+ }
87
+ }
88
+ catch (exception) {
89
+ if (exception instanceof SessionError) {
90
+ throw exception; // Session errors are re-thrown as-is
91
+ }
92
+ if (exception instanceof ContextPipelineInterruptedError) {
93
+ throw exception;
94
+ }
95
+ throw new ContextPipelineInitializationError(exception);
96
+ }
97
+ }
98
+ try {
99
+ await finalContextConsumer(crawlingContext);
100
+ }
101
+ catch (exception) {
102
+ if (exception instanceof SessionError) {
103
+ consumerException = exception;
104
+ throw exception; // Session errors are re-thrown as-is
105
+ }
106
+ consumerException = exception;
107
+ throw new RequestHandlerError(exception);
108
+ }
109
+ }
110
+ finally {
111
+ try {
112
+ for (const cleanup of cleanupStack.reverse()) {
113
+ await cleanup(crawlingContext, consumerException);
114
+ }
115
+ }
116
+ catch (exception) {
117
+ // eslint-disable-next-line no-unsafe-finally
118
+ throw new ContextPipelineCleanupError(exception);
119
+ }
120
+ }
121
+ }
122
+ }
@@ -1,18 +1,67 @@
1
- import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
2
- // @ts-ignore optional peer dependency or compatibility with es2022
3
- import type { OptionsInit, Response as GotResponse } from 'got-scraping';
4
- import type { ReadonlyDeep } from 'type-fest';
1
+ import type { Dictionary, HttpRequestOptions, ISession, ProxyInfo, SendRequestOptions } from '@crawlee/types';
2
+ import type { ReadonlyDeep, SetRequired } from 'type-fest';
5
3
  import type { Configuration } from '../configuration.js';
6
4
  import type { EnqueueLinksOptions } from '../enqueue_links/enqueue_links.js';
7
- import type { Log } from '../log.js';
8
- import type { ProxyInfo } from '../proxy_configuration.js';
9
- import type { Request, Source } from '../request.js';
10
- import type { Session } from '../session_pool/session.js';
5
+ import type { CrawleeLogger } from '../log.js';
6
+ import type { Request, RequestOptions, Source } from '../request.js';
11
7
  import type { Dataset } from '../storages/dataset.js';
12
8
  import { KeyValueStore, type RecordOptions } from '../storages/key_value_store.js';
13
- import type { RequestQueueOperationOptions } from '../storages/request_provider.js';
9
+ import type { RequestQueueOperationOptions } from '../storages/request_queue.js';
10
+ import type { StorageIdentifier } from '../storages/storage_instance_manager.js';
14
11
  /** @internal */
15
12
  export type IsAny<T> = 0 extends 1 & T ? true : false;
13
+ /**
14
+ * A request input (URL string, request-options object, or {@link Request}) whose `userData` is typed
15
+ * according to its `label`, based on a router's route map.
16
+ *
17
+ * When the route map is open (the default `Record<string, ...>`), this is just the regular loose
18
+ * {@link Source} input. When the map declares concrete labels, providing a `label` requires the matching
19
+ * `userData` shape and rejects labels not present in the map; unlabeled requests keep loose `userData`.
20
+ * @internal
21
+ */
22
+ export type LabeledSource<Routes extends Record<keyof Routes, Dictionary>> = string extends keyof Routes ? string | Source : string | Request | ({
23
+ requestsFromUrl?: string;
24
+ regex?: RegExp;
25
+ } & ({
26
+ [Label in keyof Routes & string]: Omit<Partial<RequestOptions<Routes[Label]>>, 'label'> & {
27
+ label: Label;
28
+ };
29
+ }[keyof Routes & string] | (Omit<Partial<RequestOptions>, 'label'> & {
30
+ label?: undefined;
31
+ })));
32
+ /**
33
+ * The iterable/array of {@link LabeledSource} inputs accepted by the label-aware `addRequests`/`run`
34
+ * methods of a crawler bound to a typed router.
35
+ * @internal
36
+ */
37
+ export type TypedRequestsLike<Routes extends Record<keyof Routes, Dictionary>> = AsyncIterable<LabeledSource<Routes>> | Iterable<LabeledSource<Routes>> | LabeledSource<Routes>[];
38
+ /**
39
+ * The label-aware `addRequests` method signature exposed on a request handler's context when the crawler is
40
+ * bound to a typed router. Mirrors {@link RestrictedCrawlingContext.addRequests} with typed sources.
41
+ * @internal
42
+ */
43
+ export type TypedContextAddRequests<Routes extends Record<keyof Routes, Dictionary>> = (requestsLike: ReadonlyDeep<LabeledSource<Routes>[]>, options?: ReadonlyDeep<RequestQueueOperationOptions>) => Promise<void>;
44
+ /**
45
+ * An `enqueueLinks`-options object with its `label`/`userData` retyped according to a router's route map: a
46
+ * declared `label` requires the matching `userData` shape (unknown labels are rejected), while unlabeled
47
+ * calls keep loose `userData`. Returns the options unchanged when the route map is open (the default).
48
+ */
49
+ type TypedEnqueueLinksOptions<Options, Routes extends Record<keyof Routes, Dictionary>> = string extends keyof Routes ? Options : Omit<Options, 'label' | 'userData'> & ({
50
+ [Label in keyof Routes & string]: {
51
+ label: Label;
52
+ userData?: Routes[Label];
53
+ };
54
+ }[keyof Routes & string] | {
55
+ label?: undefined;
56
+ userData?: Dictionary;
57
+ });
58
+ /**
59
+ * Transforms a context's existing `enqueueLinks` method so that the `label`/`userData` in its options follow
60
+ * the router's route map, while preserving everything else about the signature (argument optionality and
61
+ * return type, which differ between crawler types).
62
+ * @internal
63
+ */
64
+ export type TypedContextEnqueueLinks<EnqueueLinks, Routes extends Record<keyof Routes, Dictionary>> = EnqueueLinks extends (options?: infer Options) => infer Result ? (options?: TypedEnqueueLinksOptions<Options, Routes>) => Result : EnqueueLinks extends (options: infer Options) => infer Result ? (options: TypedEnqueueLinksOptions<Options, Routes>) => Result : EnqueueLinks;
16
65
  /** @internal */
17
66
  export type WithRequired<T, K extends keyof T> = T & {
18
67
  [P in K]-?: T[P];
@@ -22,9 +71,9 @@ export type LoadedRequest<R extends Request> = WithRequired<R, 'id' | 'loadedUrl
22
71
  export type LoadedContext<Context extends RestrictedCrawlingContext> = IsAny<Context> extends true ? Context : {
23
72
  request: LoadedRequest<Context['request']>;
24
73
  } & Omit<Context, 'request'>;
25
- export interface RestrictedCrawlingContext<UserData extends Dictionary = Dictionary> extends Record<string & {}, unknown> {
74
+ export interface RestrictedCrawlingContext<UserData extends Dictionary = Dictionary> {
26
75
  id: string;
27
- session?: Session;
76
+ session: ISession;
28
77
  /**
29
78
  * An object with information about currently used proxy by the crawler
30
79
  * and configured by the {@link ProxyConfiguration} class.
@@ -41,7 +90,7 @@ export interface RestrictedCrawlingContext<UserData extends Dictionary = Diction
41
90
  *
42
91
  * @param [data] Data to be pushed to the default dataset.
43
92
  */
44
- pushData(data: ReadonlyDeep<Parameters<Dataset['pushData']>[0]>, datasetIdOrName?: string): Promise<void>;
93
+ pushData(data: ReadonlyDeep<Parameters<Dataset['pushData']>[0]>, datasetIdentifier?: string | StorageIdentifier): Promise<void>;
45
94
  /**
46
95
  * This function automatically finds and enqueues links from the current page, adding them to the {@link RequestQueue}
47
96
  * currently used by the crawler.
@@ -66,7 +115,7 @@ export interface RestrictedCrawlingContext<UserData extends Dictionary = Diction
66
115
  *
67
116
  * @param [options] All `enqueueLinks()` parameters are passed via an options object.
68
117
  */
69
- enqueueLinks: (options?: ReadonlyDeep<Omit<EnqueueLinksOptions, 'requestQueue'>>) => Promise<unknown>;
118
+ enqueueLinks: (options: ReadonlyDeep<Omit<SetRequired<EnqueueLinksOptions, 'urls'>, 'requestManager' | 'robotsTxtFile'>>) => Promise<unknown>;
70
119
  /**
71
120
  * Add requests directly to the request queue.
72
121
  *
@@ -81,14 +130,13 @@ export interface RestrictedCrawlingContext<UserData extends Dictionary = Diction
81
130
  /**
82
131
  * Get a key-value store with given name or id, or the default one for the crawler.
83
132
  */
84
- getKeyValueStore: (idOrName?: string) => Promise<Pick<KeyValueStore, 'id' | 'name' | 'getValue' | 'getAutoSavedValue' | 'setValue' | 'getPublicUrl'>>;
133
+ getKeyValueStore: (identifier?: string | StorageIdentifier) => Promise<Pick<KeyValueStore, 'id' | 'name' | 'getValue' | 'getAutoSavedValue' | 'setValue' | 'getPublicUrl'>>;
85
134
  /**
86
135
  * A preconfigured logger for the request handler.
87
136
  */
88
- log: Log;
137
+ log: CrawleeLogger;
89
138
  }
90
- export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary = Dictionary> extends RestrictedCrawlingContext<UserData> {
91
- crawler: Crawler;
139
+ export interface CrawlingContext<UserData extends Dictionary = Dictionary> extends RestrictedCrawlingContext<UserData> {
92
140
  /**
93
141
  * This function automatically finds and enqueues links from the current page, adding them to the {@link RequestQueue}
94
142
  * currently used by the crawler.
@@ -114,14 +162,9 @@ export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary
114
162
  * @param [options] All `enqueueLinks()` parameters are passed via an options object.
115
163
  * @returns Promise that resolves to {@link BatchAddRequestsResult} object.
116
164
  */
117
- enqueueLinks(options?: ReadonlyDeep<Omit<EnqueueLinksOptions, 'requestQueue'>> & Pick<EnqueueLinksOptions, 'requestQueue'>): Promise<BatchAddRequestsResult>;
118
- /**
119
- * Get a key-value store with given name or id, or the default one for the crawler.
120
- */
121
- getKeyValueStore: (idOrName?: string) => Promise<KeyValueStore>;
165
+ enqueueLinks(options: ReadonlyDeep<Omit<SetRequired<EnqueueLinksOptions, 'urls'>, 'requestManager' | 'robotsTxtFile'>> & Pick<EnqueueLinksOptions, 'requestManager' | 'robotsTxtFile'>): Promise<unknown>;
122
166
  /**
123
- * Fires HTTP request via [`got-scraping`](https://crawlee.dev/js/docs/guides/got-scraping), allowing to override the request
124
- * options on the fly.
167
+ * Fires HTTP request via the internal HTTP client, allowing to override the request options on the fly.
125
168
  *
126
169
  * This is handy when you work with a browser crawler but want to execute some requests outside it (e.g. API requests).
127
170
  * Check the [Skipping navigations for certain requests](https://crawlee.dev/js/docs/examples/skip-navigation) example for
@@ -136,7 +179,11 @@ export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary
136
179
  * },
137
180
  * ```
138
181
  */
139
- sendRequest<Response = string>(overrideOptions?: Partial<OptionsInit>): Promise<GotResponse<Response>>;
182
+ sendRequest: (requestOverrides?: Partial<HttpRequestOptions>, optionsOverrides?: SendRequestOptions) => Promise<Response>;
183
+ /**
184
+ * Register a function to be called at the very end of the request handling process. This is useful for resources that should be accessible to error handlers, for instance.
185
+ */
186
+ registerDeferredCleanup(cleanup: () => Promise<unknown>): void;
140
187
  }
141
188
  /**
142
189
  * A partial implementation of {@link RestrictedCrawlingContext} that stores parameters of calls to context methods for later inspection.
@@ -144,20 +191,18 @@ export interface CrawlingContext<Crawler = unknown, UserData extends Dictionary
144
191
  * @experimental
145
192
  */
146
193
  export declare class RequestHandlerResult {
147
- private config;
194
+ private configuration;
148
195
  private crawleeStateKey;
149
196
  private _keyValueStoreChanges;
150
197
  private pushDataCalls;
151
198
  private addRequestsCalls;
152
- private enqueueLinksCalls;
153
- constructor(config: Configuration, crawleeStateKey: string);
199
+ constructor(configuration: Configuration, crawleeStateKey: string);
154
200
  /**
155
201
  * A record of calls to {@link RestrictedCrawlingContext.pushData}, {@link RestrictedCrawlingContext.addRequests}, {@link RestrictedCrawlingContext.enqueueLinks} made by a request handler.
156
202
  */
157
203
  get calls(): ReadonlyDeep<{
158
204
  pushData: Parameters<RestrictedCrawlingContext['pushData']>[];
159
205
  addRequests: Parameters<RestrictedCrawlingContext['addRequests']>[];
160
- enqueueLinks: Parameters<RestrictedCrawlingContext['enqueueLinks']>[];
161
206
  }>;
162
207
  /**
163
208
  * A record of changes made to key-value stores by a request handler.
@@ -171,7 +216,7 @@ export declare class RequestHandlerResult {
171
216
  */
172
217
  get datasetItems(): ReadonlyDeep<{
173
218
  item: Dictionary;
174
- datasetIdOrName?: string;
219
+ datasetIdentifier?: string | StorageIdentifier;
175
220
  }[]>;
176
221
  /**
177
222
  * URLs enqueued to the request queue by a request handler, either via {@link RestrictedCrawlingContext.addRequests} or {@link RestrictedCrawlingContext.enqueueLinks}
@@ -188,12 +233,10 @@ export declare class RequestHandlerResult {
188
233
  label?: string;
189
234
  }[]>;
190
235
  pushData: RestrictedCrawlingContext['pushData'];
191
- enqueueLinks: RestrictedCrawlingContext['enqueueLinks'];
192
236
  addRequests: RestrictedCrawlingContext['addRequests'];
193
237
  useState: RestrictedCrawlingContext['useState'];
194
238
  getKeyValueStore: RestrictedCrawlingContext['getKeyValueStore'];
195
- private idOrDefault;
196
239
  private getKeyValueStoreChangedValue;
197
240
  private setKeyValueStoreChangedValue;
198
241
  }
199
- //# sourceMappingURL=crawler_commons.d.ts.map
242
+ export {};
@@ -5,14 +5,13 @@ import { KeyValueStore } from '../storages/key_value_store.js';
5
5
  * @experimental
6
6
  */
7
7
  export class RequestHandlerResult {
8
- config;
8
+ configuration;
9
9
  crawleeStateKey;
10
10
  _keyValueStoreChanges = {};
11
11
  pushDataCalls = [];
12
12
  addRequestsCalls = [];
13
- enqueueLinksCalls = [];
14
- constructor(config, crawleeStateKey) {
15
- this.config = config;
13
+ constructor(configuration, crawleeStateKey) {
14
+ this.configuration = configuration;
16
15
  this.crawleeStateKey = crawleeStateKey;
17
16
  }
18
17
  /**
@@ -22,7 +21,6 @@ export class RequestHandlerResult {
22
21
  return {
23
22
  pushData: this.pushDataCalls,
24
23
  addRequests: this.addRequestsCalls,
25
- enqueueLinks: this.enqueueLinksCalls,
26
24
  };
27
25
  }
28
26
  /**
@@ -35,16 +33,13 @@ export class RequestHandlerResult {
35
33
  * Items added to datasets by a request handler.
36
34
  */
37
35
  get datasetItems() {
38
- return this.pushDataCalls.flatMap(([data, datasetIdOrName]) => (Array.isArray(data) ? data : [data]).map((item) => ({ item, datasetIdOrName })));
36
+ return this.pushDataCalls.flatMap(([data, datasetIdentifier]) => (Array.isArray(data) ? data : [data]).map((item) => ({ item, datasetIdentifier })));
39
37
  }
40
38
  /**
41
39
  * URLs enqueued to the request queue by a request handler, either via {@link RestrictedCrawlingContext.addRequests} or {@link RestrictedCrawlingContext.enqueueLinks}
42
40
  */
43
41
  get enqueuedUrls() {
44
42
  const result = [];
45
- for (const [options] of this.enqueueLinksCalls) {
46
- result.push(...(options?.urls?.map((url) => ({ url, label: options?.label })) ?? []));
47
- }
48
43
  for (const [requests] of this.addRequestsCalls) {
49
44
  for (const request of requests) {
50
45
  if (typeof request === 'object' &&
@@ -78,9 +73,6 @@ export class RequestHandlerResult {
78
73
  pushData = async (data, datasetIdOrName) => {
79
74
  this.pushDataCalls.push([data, datasetIdOrName]);
80
75
  };
81
- enqueueLinks = async (options) => {
82
- this.enqueueLinksCalls.push([options]);
83
- };
84
76
  addRequests = async (requests, options = {}) => {
85
77
  this.addRequestsCalls.push([requests, options]);
86
78
  };
@@ -88,29 +80,28 @@ export class RequestHandlerResult {
88
80
  const store = await this.getKeyValueStore(undefined);
89
81
  return await store.getAutoSavedValue(this.crawleeStateKey, defaultValue);
90
82
  };
91
- getKeyValueStore = async (idOrName) => {
92
- const store = await KeyValueStore.open(idOrName, { config: this.config });
83
+ getKeyValueStore = async (identifier) => {
84
+ const store = await KeyValueStore.open(identifier, { configuration: this.configuration });
85
+ const storeId = store.id;
93
86
  return {
94
- id: this.idOrDefault(idOrName),
95
- name: idOrName,
96
- getValue: async (key) => this.getKeyValueStoreChangedValue(idOrName, key) ?? (await store.getValue(key)),
87
+ id: storeId ?? this.configuration.defaultKeyValueStoreId,
88
+ name: store.name,
89
+ getValue: async (key) => this.getKeyValueStoreChangedValue(storeId, key) ?? (await store.getValue(key)),
97
90
  setValue: async (key, value, options) => {
98
- this.setKeyValueStoreChangedValue(idOrName, key, value, options);
91
+ this.setKeyValueStoreChangedValue(storeId, key, value, options);
99
92
  },
100
93
  getAutoSavedValue: store.getAutoSavedValue.bind(store),
101
94
  getPublicUrl: store.getPublicUrl.bind(store),
102
95
  };
103
96
  };
104
- idOrDefault = (idOrName) => idOrName ?? this.config.get('defaultKeyValueStoreId');
105
- getKeyValueStoreChangedValue = (idOrName, key) => {
106
- const id = this.idOrDefault(idOrName);
97
+ getKeyValueStoreChangedValue = (storeKey, key) => {
98
+ const id = storeKey ?? this.configuration.defaultKeyValueStoreId;
107
99
  this._keyValueStoreChanges[id] ??= {};
108
100
  return this.keyValueStoreChanges[id][key]?.changedValue ?? null;
109
101
  };
110
- setKeyValueStoreChangedValue = (idOrName, key, changedValue, options) => {
111
- const id = this.idOrDefault(idOrName);
102
+ setKeyValueStoreChangedValue = (storeKey, key, changedValue, options) => {
103
+ const id = storeKey ?? this.configuration.defaultKeyValueStoreId;
112
104
  this._keyValueStoreChanges[id] ??= {};
113
105
  this._keyValueStoreChanges[id][key] = { changedValue, options };
114
106
  };
115
107
  }
116
- //# sourceMappingURL=crawler_commons.js.map
@@ -1,10 +1,9 @@
1
- import type { Session } from '../session_pool/session.js';
1
+ import type { ISession } from '@crawlee/types';
2
2
  /**
3
3
  * Handles timeout request
4
4
  * @internal
5
5
  */
6
6
  export declare function handleRequestTimeout({ session, errorMessage }: {
7
- session?: Session;
7
+ session?: ISession;
8
8
  errorMessage: string;
9
9
  }): void;
10
- //# sourceMappingURL=crawler_utils.d.ts.map
@@ -5,8 +5,7 @@ import { TimeoutError } from '@apify/timeout';
5
5
  */
6
6
  export function handleRequestTimeout({ session, errorMessage }) {
7
7
  session?.markBad();
8
- const timeoutMillis = errorMessage.match(/(\d+)\s?ms/)?.[1]; // first capturing group
8
+ const timeoutMillis = /(\d+)\s?ms/.exec(errorMessage)?.[1]; // first capturing group
9
9
  const timeoutSecs = Number(timeoutMillis) / 1000;
10
10
  throw new TimeoutError(`Navigation timed out after ${timeoutSecs} seconds.`);
11
11
  }
12
- //# sourceMappingURL=crawler_utils.js.map
@@ -1,6 +1,7 @@
1
1
  import type { CrawlingContext } from '../crawlers/crawler_commons.js';
2
2
  import type { KeyValueStore } from '../storages/key_value_store.js';
3
3
  import type { ErrnoException } from './error_tracker.js';
4
+ import type { SnapshottableProperties } from './internals/types.js';
4
5
  interface BrowserCrawlingContext {
5
6
  saveSnapshot: (options: {
6
7
  key: string;
@@ -39,7 +40,7 @@ export declare class ErrorSnapshotter {
39
40
  /**
40
41
  * Capture a snapshot of the error context.
41
42
  */
42
- captureSnapshot(error: ErrnoException, context: CrawlingContext): Promise<ErrorSnapshot>;
43
+ captureSnapshot(error: ErrnoException, context: CrawlingContext & SnapshottableProperties): Promise<ErrorSnapshot>;
43
44
  /**
44
45
  * Captures a snapshot of the current page using the context.saveSnapshot function.
45
46
  * This function is applicable for browser contexts only.
@@ -49,11 +50,10 @@ export declare class ErrorSnapshotter {
49
50
  /**
50
51
  * Save the HTML snapshot of the page, and return the fileName with the extension.
51
52
  */
52
- saveHTMLSnapshot(html: string, keyValueStore: KeyValueStore, fileName: string): Promise<string | undefined>;
53
+ saveHTMLSnapshot(html: string, keyValueStore: Pick<KeyValueStore, 'setValue'>, fileName: string): Promise<string | undefined>;
53
54
  /**
54
55
  * Generate a unique fileName for each error snapshot.
55
56
  */
56
57
  generateFilename(error: ErrnoException): string;
57
58
  }
58
59
  export {};
59
- //# sourceMappingURL=error_snapshotter.d.ts.map
@@ -52,9 +52,9 @@ export class ErrorSnapshotter {
52
52
  }
53
53
  return {
54
54
  screenshotFileName,
55
- screenshotFileUrl: screenshotFileName && keyValueStore.getPublicUrl(screenshotFileName),
55
+ screenshotFileUrl: screenshotFileName && (await keyValueStore.getPublicUrl(screenshotFileName)),
56
56
  htmlFileName,
57
- htmlFileUrl: htmlFileName && keyValueStore.getPublicUrl(htmlFileName),
57
+ htmlFileUrl: htmlFileName && (await keyValueStore.getPublicUrl(htmlFileName)),
58
58
  };
59
59
  }
60
60
  catch {
@@ -115,4 +115,3 @@ export class ErrorSnapshotter {
115
115
  return fileName;
116
116
  }
117
117
  }
118
- //# sourceMappingURL=error_snapshotter.js.map
@@ -1,5 +1,6 @@
1
1
  import type { CrawlingContext } from '../crawlers/crawler_commons.js';
2
2
  import { ErrorSnapshotter } from './error_snapshotter.js';
3
+ import type { SnapshottableProperties } from './internals/types.js';
3
4
  /**
4
5
  * Node.js Error interface
5
6
  */
@@ -48,7 +49,6 @@ export declare class ErrorTracker {
48
49
  addAsync(error: ErrnoException, context?: CrawlingContext): Promise<void>;
49
50
  getUniqueErrorCount(): number;
50
51
  getMostPopularErrors(count: number): [number, string[]][];
51
- captureSnapshot(storage: Record<string, unknown>, error: ErrnoException, context: CrawlingContext): Promise<void>;
52
+ captureSnapshot(storage: Record<string, unknown>, error: ErrnoException, context: CrawlingContext & SnapshottableProperties): Promise<void>;
52
53
  reset(): void;
53
54
  }
54
- //# sourceMappingURL=error_tracker.d.ts.map
@@ -306,4 +306,3 @@ export class ErrorTracker {
306
306
  }
307
307
  }
308
308
  }
309
- //# sourceMappingURL=error_tracker.js.map
@@ -1,7 +1,6 @@
1
+ export * from './context_pipeline.js';
1
2
  export * from './crawler_commons.js';
2
- export * from './crawler_extension.js';
3
3
  export * from './crawler_utils.js';
4
4
  export * from './statistics.js';
5
5
  export * from './error_tracker.js';
6
6
  export * from './error_snapshotter.js';
7
- //# sourceMappingURL=index.d.ts.map
package/crawlers/index.js CHANGED
@@ -1,7 +1,6 @@
1
+ export * from './context_pipeline.js';
1
2
  export * from './crawler_commons.js';
2
- export * from './crawler_extension.js';
3
3
  export * from './crawler_utils.js';
4
4
  export * from './statistics.js';
5
5
  export * from './error_tracker.js';
6
6
  export * from './error_snapshotter.js';
7
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ export interface BrowserPage {
2
+ content: () => Promise<string>;
3
+ }
4
+ export interface SnapshottableProperties {
5
+ body?: unknown;
6
+ page?: BrowserPage;
7
+ }
@@ -0,0 +1 @@
1
+ export {};