@crawlee/core 4.0.0-beta.11 → 4.0.0-beta.111

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 (271) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +165 -320
  4. package/autoscaling/client_load_signal.d.ts +55 -0
  5. package/autoscaling/client_load_signal.js +73 -0
  6. package/autoscaling/concurrency_system.d.ts +268 -0
  7. package/autoscaling/concurrency_system.js +351 -0
  8. package/autoscaling/cpu_load_signal.d.ts +43 -0
  9. package/autoscaling/cpu_load_signal.js +46 -0
  10. package/autoscaling/event_loop_load_signal.d.ts +51 -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 +104 -0
  16. package/autoscaling/memory_load_signal.d.ts +47 -0
  17. package/autoscaling/memory_load_signal.js +105 -0
  18. package/autoscaling/snapshotter.d.ts +58 -163
  19. package/autoscaling/snapshotter.js +45 -263
  20. package/autoscaling/system_status.d.ts +62 -84
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +4 -3
  29. package/cookie_utils.js +22 -13
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -83
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +1 -4
  35. package/crawlers/error_snapshotter.js +3 -6
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +91 -41
  43. package/crawlers/statistics.js +83 -72
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +59 -68
  47. package/enqueue_links/enqueue_links.js +57 -62
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +40 -27
  51. package/enqueue_links/shared.js +90 -68
  52. package/errors.d.ts +41 -4
  53. package/errors.js +50 -5
  54. package/events/event_manager.d.ts +34 -8
  55. package/events/event_manager.js +8 -10
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +37 -11
  60. package/index.d.ts +6 -4
  61. package/index.js +5 -3
  62. package/iterables.d.ts +79 -0
  63. package/iterables.js +134 -0
  64. package/log.d.ts +82 -3
  65. package/log.js +106 -1
  66. package/memory-storage/consts.d.ts +4 -0
  67. package/memory-storage/consts.js +4 -0
  68. package/memory-storage/index.d.ts +1 -0
  69. package/memory-storage/index.js +1 -0
  70. package/memory-storage/memory-storage.d.ts +42 -0
  71. package/memory-storage/memory-storage.js +136 -0
  72. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  73. package/memory-storage/resource-clients/common/base-client.js +6 -0
  74. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  75. package/memory-storage/resource-clients/dataset.js +114 -0
  76. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  77. package/memory-storage/resource-clients/key-value-store.js +204 -0
  78. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  79. package/memory-storage/resource-clients/request-queue.js +422 -0
  80. package/memory-storage/utils.d.ts +16 -0
  81. package/memory-storage/utils.js +41 -0
  82. package/owned_or_injected.d.ts +58 -0
  83. package/owned_or_injected.js +98 -0
  84. package/package.json +13 -12
  85. package/proxy_configuration.d.ts +27 -152
  86. package/proxy_configuration.js +27 -179
  87. package/recoverable_state.d.ts +111 -0
  88. package/recoverable_state.js +143 -0
  89. package/request.d.ts +86 -17
  90. package/request.js +117 -41
  91. package/router.d.ts +193 -21
  92. package/router.js +188 -43
  93. package/serialization.d.ts +0 -1
  94. package/serialization.js +9 -11
  95. package/service_locator.d.ts +147 -0
  96. package/service_locator.js +244 -0
  97. package/session_pool/consts.d.ts +1 -2
  98. package/session_pool/consts.js +1 -2
  99. package/session_pool/errors.d.ts +0 -1
  100. package/session_pool/errors.js +0 -1
  101. package/session_pool/fingerprint.d.ts +9 -0
  102. package/session_pool/fingerprint.js +30 -0
  103. package/session_pool/index.d.ts +0 -2
  104. package/session_pool/index.js +0 -2
  105. package/session_pool/session.d.ts +37 -86
  106. package/session_pool/session.js +85 -138
  107. package/session_pool/session_pool.d.ts +77 -91
  108. package/session_pool/session_pool.js +159 -147
  109. package/storages/dataset.d.ts +114 -54
  110. package/storages/dataset.js +285 -144
  111. package/storages/index.d.ts +9 -8
  112. package/storages/index.js +7 -8
  113. package/storages/key_value_store.d.ts +185 -42
  114. package/storages/key_value_store.js +424 -151
  115. package/storages/key_value_store_codec.d.ts +32 -0
  116. package/storages/key_value_store_codec.js +113 -0
  117. package/storages/request_dedup_cache.d.ts +22 -0
  118. package/storages/request_dedup_cache.js +48 -0
  119. package/storages/request_list.d.ts +52 -116
  120. package/storages/request_list.js +158 -133
  121. package/storages/request_loader.d.ts +96 -0
  122. package/storages/request_loader.js +1 -0
  123. package/storages/request_manager.d.ts +33 -0
  124. package/storages/request_manager.js +1 -0
  125. package/storages/request_manager_tandem.d.ts +97 -0
  126. package/storages/request_manager_tandem.js +197 -0
  127. package/storages/request_queue.d.ts +290 -47
  128. package/storages/request_queue.js +825 -216
  129. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +37 -88
  130. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +136 -143
  131. package/storages/storage_instance_manager.d.ts +87 -0
  132. package/storages/storage_instance_manager.js +256 -0
  133. package/storages/storage_stats.d.ts +48 -0
  134. package/storages/storage_stats.js +29 -0
  135. package/storages/transaction.d.ts +252 -0
  136. package/storages/transaction.js +251 -0
  137. package/storages/utils.d.ts +54 -9
  138. package/storages/utils.js +64 -13
  139. package/system-info/cpu-info.d.ts +67 -0
  140. package/system-info/cpu-info.js +216 -0
  141. package/system-info/memory-info.d.ts +31 -0
  142. package/system-info/memory-info.js +115 -0
  143. package/system-info/ps-tree.d.ts +17 -0
  144. package/system-info/ps-tree.js +144 -0
  145. package/system-info/runtime.d.ts +14 -0
  146. package/system-info/runtime.js +80 -0
  147. package/typedefs.d.ts +0 -6
  148. package/typedefs.js +0 -1
  149. package/validators.d.ts +8 -1
  150. package/validators.js +10 -3
  151. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  152. package/autoscaling/autoscaled_pool.js.map +0 -1
  153. package/autoscaling/index.d.ts.map +0 -1
  154. package/autoscaling/index.js.map +0 -1
  155. package/autoscaling/snapshotter.d.ts.map +0 -1
  156. package/autoscaling/snapshotter.js.map +0 -1
  157. package/autoscaling/system_status.d.ts.map +0 -1
  158. package/autoscaling/system_status.js.map +0 -1
  159. package/configuration.d.ts.map +0 -1
  160. package/configuration.js.map +0 -1
  161. package/cookie_utils.d.ts.map +0 -1
  162. package/cookie_utils.js.map +0 -1
  163. package/crawlers/context_pipeline.d.ts.map +0 -1
  164. package/crawlers/context_pipeline.js.map +0 -1
  165. package/crawlers/crawler_commons.d.ts.map +0 -1
  166. package/crawlers/crawler_commons.js.map +0 -1
  167. package/crawlers/crawler_utils.d.ts +0 -10
  168. package/crawlers/crawler_utils.d.ts.map +0 -1
  169. package/crawlers/crawler_utils.js +0 -12
  170. package/crawlers/crawler_utils.js.map +0 -1
  171. package/crawlers/error_snapshotter.d.ts.map +0 -1
  172. package/crawlers/error_snapshotter.js.map +0 -1
  173. package/crawlers/error_tracker.d.ts.map +0 -1
  174. package/crawlers/error_tracker.js.map +0 -1
  175. package/crawlers/index.d.ts.map +0 -1
  176. package/crawlers/index.js.map +0 -1
  177. package/crawlers/internals/types.d.ts.map +0 -1
  178. package/crawlers/internals/types.js.map +0 -1
  179. package/crawlers/statistics.d.ts.map +0 -1
  180. package/crawlers/statistics.js.map +0 -1
  181. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  182. package/enqueue_links/enqueue_links.js.map +0 -1
  183. package/enqueue_links/index.d.ts.map +0 -1
  184. package/enqueue_links/index.js.map +0 -1
  185. package/enqueue_links/shared.d.ts.map +0 -1
  186. package/enqueue_links/shared.js.map +0 -1
  187. package/errors.d.ts.map +0 -1
  188. package/errors.js.map +0 -1
  189. package/events/event_manager.d.ts.map +0 -1
  190. package/events/event_manager.js.map +0 -1
  191. package/events/index.d.ts.map +0 -1
  192. package/events/index.js.map +0 -1
  193. package/events/local_event_manager.d.ts.map +0 -1
  194. package/events/local_event_manager.js.map +0 -1
  195. package/http_clients/base-http-client.d.ts +0 -134
  196. package/http_clients/base-http-client.d.ts.map +0 -1
  197. package/http_clients/base-http-client.js +0 -33
  198. package/http_clients/base-http-client.js.map +0 -1
  199. package/http_clients/form-data-like.d.ts +0 -67
  200. package/http_clients/form-data-like.d.ts.map +0 -1
  201. package/http_clients/form-data-like.js +0 -5
  202. package/http_clients/form-data-like.js.map +0 -1
  203. package/http_clients/got-scraping-http-client.d.ts +0 -15
  204. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  205. package/http_clients/got-scraping-http-client.js +0 -69
  206. package/http_clients/got-scraping-http-client.js.map +0 -1
  207. package/http_clients/index.d.ts +0 -3
  208. package/http_clients/index.d.ts.map +0 -1
  209. package/http_clients/index.js +0 -3
  210. package/http_clients/index.js.map +0 -1
  211. package/index.d.ts.map +0 -1
  212. package/index.js.map +0 -1
  213. package/log.d.ts.map +0 -1
  214. package/log.js.map +0 -1
  215. package/proxy_configuration.d.ts.map +0 -1
  216. package/proxy_configuration.js.map +0 -1
  217. package/request.d.ts.map +0 -1
  218. package/request.js.map +0 -1
  219. package/router.d.ts.map +0 -1
  220. package/router.js.map +0 -1
  221. package/serialization.d.ts.map +0 -1
  222. package/serialization.js.map +0 -1
  223. package/session_pool/consts.d.ts.map +0 -1
  224. package/session_pool/consts.js.map +0 -1
  225. package/session_pool/errors.d.ts.map +0 -1
  226. package/session_pool/errors.js.map +0 -1
  227. package/session_pool/events.d.ts +0 -3
  228. package/session_pool/events.d.ts.map +0 -1
  229. package/session_pool/events.js +0 -3
  230. package/session_pool/events.js.map +0 -1
  231. package/session_pool/index.d.ts.map +0 -1
  232. package/session_pool/index.js.map +0 -1
  233. package/session_pool/session.d.ts.map +0 -1
  234. package/session_pool/session.js.map +0 -1
  235. package/session_pool/session_pool.d.ts.map +0 -1
  236. package/session_pool/session_pool.js.map +0 -1
  237. package/storages/access_checking.d.ts +0 -13
  238. package/storages/access_checking.d.ts.map +0 -1
  239. package/storages/access_checking.js +0 -14
  240. package/storages/access_checking.js.map +0 -1
  241. package/storages/dataset.d.ts.map +0 -1
  242. package/storages/dataset.js.map +0 -1
  243. package/storages/index.d.ts.map +0 -1
  244. package/storages/index.js.map +0 -1
  245. package/storages/key_value_store.d.ts.map +0 -1
  246. package/storages/key_value_store.js.map +0 -1
  247. package/storages/request_list.d.ts.map +0 -1
  248. package/storages/request_list.js.map +0 -1
  249. package/storages/request_provider.d.ts +0 -308
  250. package/storages/request_provider.d.ts.map +0 -1
  251. package/storages/request_provider.js +0 -555
  252. package/storages/request_provider.js.map +0 -1
  253. package/storages/request_queue.d.ts.map +0 -1
  254. package/storages/request_queue.js.map +0 -1
  255. package/storages/request_queue_v2.d.ts +0 -87
  256. package/storages/request_queue_v2.d.ts.map +0 -1
  257. package/storages/request_queue_v2.js +0 -438
  258. package/storages/request_queue_v2.js.map +0 -1
  259. package/storages/sitemap_request_list.d.ts.map +0 -1
  260. package/storages/sitemap_request_list.js.map +0 -1
  261. package/storages/storage_manager.d.ts +0 -58
  262. package/storages/storage_manager.d.ts.map +0 -1
  263. package/storages/storage_manager.js +0 -105
  264. package/storages/storage_manager.js.map +0 -1
  265. package/storages/utils.d.ts.map +0 -1
  266. package/storages/utils.js.map +0 -1
  267. package/tsconfig.build.tsbuildinfo +0 -1
  268. package/typedefs.d.ts.map +0 -1
  269. package/typedefs.js.map +0 -1
  270. package/validators.d.ts.map +0 -1
  271. package/validators.js.map +0 -1
@@ -0,0 +1,143 @@
1
+ import { KeyValueStore, serviceLocator } from '@crawlee/core';
2
+ /**
3
+ * A class for managing persistent recoverable state using a plain JavaScript object.
4
+ *
5
+ * This class facilitates state persistence to a `KeyValueStore`, allowing data to be saved and retrieved
6
+ * across migrations or restarts. It manages the loading, saving, and resetting of state data,
7
+ * with optional persistence capabilities.
8
+ *
9
+ * The state is represented by a plain JavaScript object that can be serialized to and deserialized from JSON.
10
+ * The class automatically hooks into the event system to persist state when needed.
11
+ */
12
+ export class RecoverableState {
13
+ #defaultState;
14
+ #state = null;
15
+ #persistenceEnabled;
16
+ #persistStateKey;
17
+ #persistStateKvsName;
18
+ #persistStateKvsId;
19
+ #keyValueStore = null;
20
+ #log;
21
+ #serialize;
22
+ #deserialize;
23
+ /**
24
+ * Initialize a new recoverable state object.
25
+ *
26
+ * @param options Configuration options for the recoverable state
27
+ */
28
+ constructor(options) {
29
+ this.#defaultState = options.defaultState;
30
+ this.#persistStateKey = options.persistStateKey;
31
+ this.#persistenceEnabled = options.persistenceEnabled ?? false;
32
+ this.#persistStateKvsName = options.persistStateKvsName;
33
+ this.#persistStateKvsId = options.persistStateKvsId;
34
+ this.#log = options.logger ?? serviceLocator.getLogger().child({ prefix: 'RecoverableState' });
35
+ this.#serialize = options.serialize ?? JSON.stringify;
36
+ this.#deserialize = options.deserialize ?? JSON.parse;
37
+ this.persistState = this.persistState.bind(this);
38
+ }
39
+ /**
40
+ * Initialize the recoverable state.
41
+ *
42
+ * This method must be called before using the recoverable state. It loads the saved state
43
+ * if persistence is enabled and registers the object to listen for PERSIST_STATE events.
44
+ *
45
+ * @returns The loaded state object
46
+ */
47
+ async initialize() {
48
+ if (this.#state !== null && this.#state !== undefined) {
49
+ return this.currentValue;
50
+ }
51
+ if (!this.#persistenceEnabled) {
52
+ this.#state = this.#deserialize(this.#serialize(this.#defaultState));
53
+ return this.currentValue;
54
+ }
55
+ let kvsIdentifier = null;
56
+ if (this.#persistStateKvsName) {
57
+ kvsIdentifier = { name: this.#persistStateKvsName };
58
+ }
59
+ else if (this.#persistStateKvsId) {
60
+ kvsIdentifier = { id: this.#persistStateKvsId };
61
+ }
62
+ this.#keyValueStore = await KeyValueStore.open(kvsIdentifier, {
63
+ configuration: serviceLocator.getConfiguration(),
64
+ });
65
+ await this.loadSavedState();
66
+ // Register for persist state events
67
+ const eventManager = serviceLocator.getEventManager();
68
+ eventManager.on("persistState" /* EventType.PERSIST_STATE */, this.persistState);
69
+ return this.currentValue;
70
+ }
71
+ /**
72
+ * Clean up resources used by the recoverable state.
73
+ *
74
+ * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
75
+ * and persists the current state one last time.
76
+ */
77
+ async teardown() {
78
+ if (!this.#persistenceEnabled || !this.persistState) {
79
+ return;
80
+ }
81
+ const eventManager = serviceLocator.getEventManager();
82
+ eventManager.off("persistState" /* EventType.PERSIST_STATE */, this.persistState);
83
+ await this.persistState();
84
+ }
85
+ /**
86
+ * Get the current state.
87
+ */
88
+ get currentValue() {
89
+ if (this.#state === null) {
90
+ throw new Error('Recoverable state has not yet been loaded');
91
+ }
92
+ return this.#state;
93
+ }
94
+ /**
95
+ * Reset the state to the default values and clear any persisted state.
96
+ *
97
+ * Resets the current state to the default state and, if persistence is enabled,
98
+ * clears the persisted state from the KeyValueStore.
99
+ */
100
+ async reset() {
101
+ this.#state = this.#deserialize(this.#serialize(this.#defaultState));
102
+ if (this.#persistenceEnabled) {
103
+ if (this.#keyValueStore === null) {
104
+ throw new Error('Recoverable state has not yet been initialized');
105
+ }
106
+ await this.#keyValueStore.setValue(this.#persistStateKey, null);
107
+ }
108
+ }
109
+ /**
110
+ * Persist the current state to the KeyValueStore.
111
+ *
112
+ * This method is typically called in response to a PERSIST_STATE event, but can also be called
113
+ * directly when needed.
114
+ *
115
+ * @param eventData Optional data associated with a PERSIST_STATE event
116
+ */
117
+ async persistState(eventData) {
118
+ this.#log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
119
+ if (this.#keyValueStore === null || this.#state === null) {
120
+ throw new Error('Recoverable state has not yet been initialized');
121
+ }
122
+ if (this.#persistenceEnabled) {
123
+ await this.#keyValueStore.setValue(this.#persistStateKey, this.#serialize(this.#state), {
124
+ contentType: 'text/plain', // HACK - the result is expected to be JSON, but we do this to avoid the implicit JSON.parse in `KeyValueStore.getValue`
125
+ });
126
+ }
127
+ }
128
+ /**
129
+ * Load the saved state from the KeyValueStore
130
+ */
131
+ async loadSavedState() {
132
+ if (this.#keyValueStore === null) {
133
+ throw new Error('Recoverable state has not yet been initialized');
134
+ }
135
+ const storedState = await this.#keyValueStore.getValue(this.#persistStateKey);
136
+ if (storedState === null || storedState === undefined) {
137
+ this.#state = this.#deserialize(this.#serialize(this.#defaultState));
138
+ }
139
+ else {
140
+ this.#state = this.#deserialize(storedState);
141
+ }
142
+ }
143
+ }
package/request.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { BinaryLike } from 'node:crypto';
2
- import type { Dictionary } from '@crawlee/types';
2
+ import type { AllowedHttpMethods, Dictionary } from '@crawlee/types';
3
3
  import type { EnqueueLinksOptions } from './enqueue_links/enqueue_links.js';
4
- import type { AllowedHttpMethods } from './typedefs.js';
4
+ import type { SkippedRequestReason } from './enqueue_links/shared.js';
5
5
  export declare enum RequestState {
6
6
  UNPROCESSED = 0,
7
7
  BEFORE_NAV = 1,
@@ -43,7 +43,8 @@ export declare enum RequestState {
43
43
  * ```
44
44
  * @category Sources
45
45
  */
46
- export declare class Request<UserData extends Dictionary = Dictionary> {
46
+ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
47
+ #private;
47
48
  /** Request ID */
48
49
  id?: string;
49
50
  /** URL of the web page to crawl. */
@@ -74,9 +75,12 @@ export declare class Request<UserData extends Dictionary = Dictionary> {
74
75
  errorMessages: string[];
75
76
  /** Object with HTTP headers. Key is header name, value is the value. */
76
77
  headers?: Record<string, string>;
77
- /** Private store for the custom user data assigned to the request. */
78
- private _userData;
79
- /** Custom user data assigned to the request. */
78
+ /**
79
+ * Custom user data assigned to the request.
80
+ *
81
+ * All data stored in `userData` must be JSON-serializable.
82
+ * Storing non-serializable values (e.g. functions, symbols) may result in unexpected results.
83
+ */
80
84
  userData: UserData;
81
85
  /**
82
86
  * ISO datetime string that indicates the time when the request has been processed.
@@ -87,14 +91,40 @@ export declare class Request<UserData extends Dictionary = Dictionary> {
87
91
  * `Request` parameters including the URL, HTTP method and headers, and others.
88
92
  */
89
93
  constructor(options: RequestOptions<UserData>);
90
- /** Tells the crawler processing this request to skip the navigation and process the request directly. */
94
+ /**
95
+ * Converts the Crawlee Request object to a `fetch` API Request object.
96
+ * @returns The native `fetch` API Request object.
97
+ */
98
+ intoFetchAPIRequest(): Request;
99
+ /**
100
+ * Tells the crawler processing this request to skip the navigation and process the request directly.
101
+ *
102
+ * When this is set to `true`, the crawling context will not contain the results of the navigation
103
+ * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
104
+ * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
105
+ */
91
106
  get skipNavigation(): boolean;
92
- /** Tells the crawler processing this request to skip the navigation and process the request directly. */
107
+ /**
108
+ * Tells the crawler processing this request to skip the navigation and process the request directly.
109
+ *
110
+ * When this is set to `true`, the crawling context will not contain the results of the navigation
111
+ * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
112
+ * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
113
+ */
93
114
  set skipNavigation(value: boolean);
94
- /** Indicates the number of times the crawling of the request has rotated the session due to a session or a proxy error. */
95
- get sessionRotationCount(): number;
96
- /** Indicates the number of times the crawling of the request has rotated the session due to a session or a proxy error. */
97
- set sessionRotationCount(value: number);
115
+ /**
116
+ * Depth of the request in the current crawl tree.
117
+ * Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
118
+ */
119
+ get crawlDepth(): number;
120
+ /**
121
+ * Depth of the request in the current crawl tree.
122
+ * Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
123
+ */
124
+ set crawlDepth(value: number);
125
+ /** ID of a session to use for this request. When set, the crawler will fetch this session from the session pool instead of creating a new one. */
126
+ get sessionId(): string | undefined;
127
+ set sessionId(value: string | undefined);
98
128
  /** shortcut for getting `request.userData.label` */
99
129
  get label(): string | undefined;
100
130
  /** shortcut for setting `request.userData.label` */
@@ -107,6 +137,14 @@ export declare class Request<UserData extends Dictionary = Dictionary> {
107
137
  get state(): RequestState;
108
138
  /** Describes the request's current lifecycle state. */
109
139
  set state(value: RequestState);
140
+ /**
141
+ * Reason for skipping this request.
142
+ */
143
+ get skippedReason(): SkippedRequestReason | undefined;
144
+ /**
145
+ * Reason for skipping this request.
146
+ */
147
+ set skippedReason(value: SkippedRequestReason | undefined);
110
148
  private get enqueueStrategy();
111
149
  private set enqueueStrategy(value);
112
150
  /**
@@ -124,7 +162,7 @@ export declare class Request<UserData extends Dictionary = Dictionary> {
124
162
  */
125
163
  pushErrorMessage(errorOrMessage: unknown, options?: PushErrorMessageOptions): void;
126
164
  /** @internal */
127
- static computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey, }: ComputeUniqueKeyOptions): string;
165
+ static computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey, alwaysEnqueue, }: ComputeUniqueKeyOptions): string;
128
166
  /** @internal */
129
167
  static hashPayload(payload: BinaryLike): string;
130
168
  }
@@ -145,7 +183,7 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
145
183
  * The `keepUrlFragment` option determines whether URL hash fragment is included in the `uniqueKey` or not.
146
184
  *
147
185
  * The `useExtendedUniqueKey` options determines whether method and payload are included in the `uniqueKey`,
148
- * producing a `uniqueKey` in the following format: `METHOD(payloadHash):normalizedUrl`. This is useful
186
+ * producing a `uniqueKey` in the following format: `METHOD|payloadHash|normalizedUrl`. This is useful
149
187
  * when requests point to the same URL, but with different methods and payloads. For example: form submits.
150
188
  *
151
189
  * Pass an arbitrary non-empty text value to the `uniqueKey` property
@@ -169,6 +207,9 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
169
207
  /**
170
208
  * Custom user data assigned to the request. Use this to save any request related data to the
171
209
  * request's scope, keeping them accessible on retries, failures etc.
210
+ *
211
+ * All data stored in `userData` must be JSON-serializable.
212
+ * Storing non-serializable values (e.g. functions, symbols) may result in unexpected results.
172
213
  */
173
214
  userData?: UserData;
174
215
  /**
@@ -190,17 +231,45 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
190
231
  * @default false
191
232
  */
192
233
  useExtendedUniqueKey?: boolean;
234
+ /**
235
+ * If `true` then a random value is included in the `uniqueKey` computation, ensuring the request
236
+ * is always enqueued even if a request with the same URL (and method/payload) is already present
237
+ * in the queue. Cannot be used together with a custom `uniqueKey`.
238
+ * @default false
239
+ */
240
+ alwaysEnqueue?: boolean;
193
241
  /**
194
242
  * The `true` value indicates that the request will not be automatically retried on error.
195
243
  * @default false
196
244
  */
197
245
  noRetry?: boolean;
246
+ /**
247
+ * ID of a session from the crawler's `SessionPool` to use for this request.
248
+ * When set, the crawler will fetch this session from the pool instead of creating a new one.
249
+ */
250
+ sessionId?: string;
198
251
  /**
199
252
  * If set to `true` then the crawler processing this request evaluates
200
253
  * the `requestHandler` immediately without prior browser navigation.
254
+ *
255
+ * When enabled, the crawling context will not contain the results of the navigation
256
+ * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
257
+ * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
201
258
  * @default false
202
259
  */
203
260
  skipNavigation?: boolean;
261
+ /**
262
+ * Depth of the request in the current crawl tree.
263
+ * Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
264
+ * @default 0
265
+ */
266
+ crawlDepth?: number;
267
+ /**
268
+ * Reason for skipping this request.
269
+ * This is used to provide more information about why the request was skipped.
270
+ * @internal
271
+ */
272
+ skippedReason?: SkippedRequestReason;
204
273
  /**
205
274
  * Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`.
206
275
  */
@@ -227,15 +296,15 @@ interface ComputeUniqueKeyOptions {
227
296
  payload?: string | Buffer;
228
297
  keepUrlFragment?: boolean;
229
298
  useExtendedUniqueKey?: boolean;
299
+ alwaysEnqueue?: boolean;
230
300
  }
231
301
  export type Source = (Partial<RequestOptions> & {
232
302
  requestsFromUrl?: string;
233
303
  regex?: RegExp;
234
- }) | Request;
304
+ }) | CrawleeRequest;
235
305
  /** @internal */
236
306
  export interface InternalSource {
237
307
  requestsFromUrl: string;
238
308
  regex?: RegExp;
239
309
  }
240
- export {};
241
- //# sourceMappingURL=request.d.ts.map
310
+ export { CrawleeRequest as Request };
package/request.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import crypto from 'node:crypto';
2
2
  import util from 'node:util';
3
3
  import ow from 'ow';
4
- import { normalizeUrl } from '@apify/utilities';
5
- import { log as defaultLog } from './log.js';
4
+ import { cryptoRandomObjectId, normalizeUrl } from '@apify/utilities';
5
+ import { serviceLocator } from './service_locator.js';
6
6
  import { keys } from './typedefs.js';
7
7
  // new properties on the Request object breaks serialization
8
- const log = defaultLog.child({ prefix: 'Request' });
9
8
  const requestOptionalPredicates = {
10
9
  id: ow.optional.string,
11
10
  loadedUrl: ow.optional.string.url,
@@ -14,7 +13,7 @@ const requestOptionalPredicates = {
14
13
  payload: ow.optional.any(ow.string, ow.uint8Array),
15
14
  noRetry: ow.optional.boolean,
16
15
  retryCount: ow.optional.number,
17
- sessionRotationCount: ow.optional.number,
16
+ sessionId: ow.optional.string,
18
17
  maxRetries: ow.optional.number,
19
18
  errorMessages: ow.optional.array.ofType(ow.string),
20
19
  headers: ow.optional.object,
@@ -23,7 +22,9 @@ const requestOptionalPredicates = {
23
22
  handledAt: ow.optional.any(ow.string.date, ow.date),
24
23
  keepUrlFragment: ow.optional.boolean,
25
24
  useExtendedUniqueKey: ow.optional.boolean,
25
+ alwaysEnqueue: ow.optional.boolean,
26
26
  skipNavigation: ow.optional.boolean,
27
+ crawlDepth: ow.optional.number.greaterThanOrEqual(0),
27
28
  state: ow.optional.number.greaterThanOrEqual(0).lessThanOrEqual(6),
28
29
  };
29
30
  export var RequestState;
@@ -68,7 +69,7 @@ export var RequestState;
68
69
  * ```
69
70
  * @category Sources
70
71
  */
71
- export class Request {
72
+ class CrawleeRequest {
72
73
  /** Request ID */
73
74
  id;
74
75
  /** URL of the web page to crawl. */
@@ -100,8 +101,13 @@ export class Request {
100
101
  /** Object with HTTP headers. Key is header name, value is the value. */
101
102
  headers;
102
103
  /** Private store for the custom user data assigned to the request. */
103
- _userData = {};
104
- /** Custom user data assigned to the request. */
104
+ #userData = {};
105
+ /**
106
+ * Custom user data assigned to the request.
107
+ *
108
+ * All data stored in `userData` must be JSON-serializable.
109
+ * Storing non-serializable values (e.g. functions, symbols) may result in unexpected results.
110
+ */
105
111
  userData = {};
106
112
  /**
107
113
  * ISO datetime string that indicates the time when the request has been processed.
@@ -130,57 +136,64 @@ export class Request {
130
136
  ow(value, `RequestOptions.${prop}`, predicate);
131
137
  }
132
138
  });
133
- const { id, url, loadedUrl, uniqueKey, payload, noRetry = false, retryCount = 0, sessionRotationCount = 0, maxRetries, errorMessages = [], headers = {}, userData = {}, label, handledAt, keepUrlFragment = false, useExtendedUniqueKey = false, skipNavigation, enqueueStrategy, } = options;
139
+ const { id, url, loadedUrl, uniqueKey, payload, noRetry = false, retryCount = 0, sessionId, maxRetries, errorMessages = [], headers = {}, userData = {}, label, handledAt, keepUrlFragment = false, useExtendedUniqueKey = false, alwaysEnqueue = false, skipNavigation, enqueueStrategy, crawlDepth, } = options;
134
140
  let { method = 'GET' } = options;
135
141
  method = method.toUpperCase();
136
142
  if (method === 'GET' && payload)
137
143
  throw new Error('Request with GET method cannot have a payload.');
144
+ if (uniqueKey && alwaysEnqueue) {
145
+ throw new Error('`alwaysEnqueue` cannot be used together with a custom `uniqueKey`.');
146
+ }
138
147
  this.id = id;
139
148
  this.url = url;
140
149
  this.loadedUrl = loadedUrl;
141
150
  this.uniqueKey =
142
- uniqueKey || Request.computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey });
151
+ uniqueKey ||
152
+ CrawleeRequest.computeUniqueKey({
153
+ url,
154
+ method,
155
+ payload,
156
+ keepUrlFragment,
157
+ useExtendedUniqueKey,
158
+ alwaysEnqueue,
159
+ });
143
160
  this.method = method;
144
161
  this.payload = payload;
145
162
  this.noRetry = noRetry;
146
163
  this.retryCount = retryCount;
147
- this.sessionRotationCount = sessionRotationCount;
148
164
  this.errorMessages = [...errorMessages];
149
165
  this.headers = { ...headers };
150
166
  this.handledAt = handledAt instanceof Date ? handledAt.toISOString() : handledAt;
151
167
  if (label) {
152
168
  userData.label = label;
153
169
  }
170
+ this.#userData = { __crawlee: {}, ...userData };
171
+ // `userData` must stay an enumerable own accessor — serialization in the storages relies on it
154
172
  Object.defineProperties(this, {
155
- _userData: {
156
- value: { __crawlee: {}, ...userData },
157
- enumerable: false,
158
- writable: true,
159
- },
160
173
  userData: {
161
- get: () => this._userData,
174
+ get: () => this.#userData,
162
175
  set: (value) => {
163
176
  Object.defineProperties(value, {
164
177
  __crawlee: {
165
- value: this._userData.__crawlee,
178
+ value: this.#userData.__crawlee,
166
179
  enumerable: false,
167
180
  writable: true,
168
181
  },
169
182
  toJSON: {
170
183
  value: () => {
171
- if (Object.keys(this._userData.__crawlee).length > 0) {
184
+ if (Object.keys(this.#userData.__crawlee).length > 0) {
172
185
  return {
173
- ...this._userData,
174
- __crawlee: this._userData.__crawlee,
186
+ ...this.#userData,
187
+ __crawlee: this.#userData.__crawlee,
175
188
  };
176
189
  }
177
- return this._userData;
190
+ return this.#userData;
178
191
  },
179
192
  enumerable: false,
180
193
  writable: true,
181
194
  },
182
195
  });
183
- this._userData = value;
196
+ this.#userData = value;
184
197
  },
185
198
  enumerable: true,
186
199
  },
@@ -191,16 +204,43 @@ export class Request {
191
204
  this.skipNavigation = skipNavigation;
192
205
  if (maxRetries != null)
193
206
  this.maxRetries = maxRetries;
207
+ if (crawlDepth != null)
208
+ this.userData.__crawlee.crawlDepth ??= crawlDepth;
209
+ if (sessionId)
210
+ this.sessionId = sessionId;
194
211
  // If it's already set, don't override it (for instance when fetching from storage)
195
212
  if (enqueueStrategy) {
196
213
  this.enqueueStrategy ??= enqueueStrategy;
197
214
  }
198
215
  }
199
- /** Tells the crawler processing this request to skip the navigation and process the request directly. */
216
+ /**
217
+ * Converts the Crawlee Request object to a `fetch` API Request object.
218
+ * @returns The native `fetch` API Request object.
219
+ */
220
+ intoFetchAPIRequest() {
221
+ return new Request(this.url, {
222
+ method: this.method,
223
+ headers: this.headers,
224
+ body: this.payload,
225
+ });
226
+ }
227
+ /**
228
+ * Tells the crawler processing this request to skip the navigation and process the request directly.
229
+ *
230
+ * When this is set to `true`, the crawling context will not contain the results of the navigation
231
+ * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
232
+ * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
233
+ */
200
234
  get skipNavigation() {
201
235
  return this.userData.__crawlee?.skipNavigation ?? false;
202
236
  }
203
- /** Tells the crawler processing this request to skip the navigation and process the request directly. */
237
+ /**
238
+ * Tells the crawler processing this request to skip the navigation and process the request directly.
239
+ *
240
+ * When this is set to `true`, the crawling context will not contain the results of the navigation
241
+ * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
242
+ * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
243
+ */
204
244
  set skipNavigation(value) {
205
245
  if (!this.userData.__crawlee) {
206
246
  this.userData.__crawlee = { skipNavigation: value };
@@ -209,18 +249,28 @@ export class Request {
209
249
  this.userData.__crawlee.skipNavigation = value;
210
250
  }
211
251
  }
212
- /** Indicates the number of times the crawling of the request has rotated the session due to a session or a proxy error. */
213
- get sessionRotationCount() {
214
- return this.userData.__crawlee?.sessionRotationCount ?? 0;
252
+ /**
253
+ * Depth of the request in the current crawl tree.
254
+ * Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
255
+ */
256
+ get crawlDepth() {
257
+ return this.userData.__crawlee?.crawlDepth ?? 0;
215
258
  }
216
- /** Indicates the number of times the crawling of the request has rotated the session due to a session or a proxy error. */
217
- set sessionRotationCount(value) {
218
- if (!this.userData.__crawlee) {
219
- this.userData.__crawlee = { sessionRotationCount: value };
220
- }
221
- else {
222
- this.userData.__crawlee.sessionRotationCount = value;
223
- }
259
+ /**
260
+ * Depth of the request in the current crawl tree.
261
+ * Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
262
+ */
263
+ set crawlDepth(value) {
264
+ this.userData.__crawlee ??= {};
265
+ this.userData.__crawlee.crawlDepth = value;
266
+ }
267
+ /** ID of a session to use for this request. When set, the crawler will fetch this session from the session pool instead of creating a new one. */
268
+ get sessionId() {
269
+ return this.userData.__crawlee?.sessionId;
270
+ }
271
+ set sessionId(value) {
272
+ this.userData.__crawlee ??= {};
273
+ this.userData.__crawlee.sessionId = value;
224
274
  }
225
275
  /** shortcut for getting `request.userData.label` */
226
276
  get label() {
@@ -256,6 +306,23 @@ export class Request {
256
306
  this.userData.__crawlee.state = value;
257
307
  }
258
308
  }
309
+ /**
310
+ * Reason for skipping this request.
311
+ */
312
+ get skippedReason() {
313
+ return this.userData.__crawlee?.skippedReason;
314
+ }
315
+ /**
316
+ * Reason for skipping this request.
317
+ */
318
+ set skippedReason(value) {
319
+ if (!this.userData.__crawlee) {
320
+ this.userData.__crawlee = { skippedReason: value };
321
+ }
322
+ else {
323
+ this.userData.__crawlee.skippedReason = value;
324
+ }
325
+ }
259
326
  get enqueueStrategy() {
260
327
  return this.userData.__crawlee?.enqueueStrategy;
261
328
  }
@@ -318,23 +385,32 @@ export class Request {
318
385
  this.errorMessages.push(message);
319
386
  }
320
387
  /** @internal */
321
- static computeUniqueKey({ url, method = 'GET', payload, keepUrlFragment = false, useExtendedUniqueKey = false, }) {
388
+ static computeUniqueKey({ url, method = 'GET', payload, keepUrlFragment = false, useExtendedUniqueKey = false, alwaysEnqueue = false, }) {
322
389
  const normalizedMethod = method.toUpperCase();
323
390
  const normalizedUrl = normalizeUrl(url, keepUrlFragment) || url; // It returns null when url is invalid, causing weird errors.
391
+ let uniqueKey;
324
392
  if (!useExtendedUniqueKey) {
325
393
  if (normalizedMethod !== 'GET' && payload) {
326
- log.warningOnce(`We've encountered a ${normalizedMethod} Request with a payload. ` +
394
+ serviceLocator
395
+ .getLogger()
396
+ .warningOnce(`We've encountered a ${normalizedMethod} Request with a payload. ` +
327
397
  'This is fine. Just letting you know that if your requests point to the same URL ' +
328
398
  'and differ only in method and payload, you should see the "useExtendedUniqueKey" option of Request constructor.');
329
399
  }
330
- return normalizedUrl;
400
+ uniqueKey = normalizedUrl;
401
+ }
402
+ else {
403
+ const payloadHash = payload ? CrawleeRequest.hashPayload(payload) : '';
404
+ uniqueKey = `${normalizedMethod}|${payloadHash}|${normalizedUrl}`;
405
+ }
406
+ if (alwaysEnqueue) {
407
+ uniqueKey = `${cryptoRandomObjectId(17)}|${uniqueKey}`;
331
408
  }
332
- const payloadHash = payload ? Request.hashPayload(payload) : '';
333
- return `${normalizedMethod}(${payloadHash}):${normalizedUrl}`;
409
+ return uniqueKey;
334
410
  }
335
411
  /** @internal */
336
412
  static hashPayload(payload) {
337
413
  return crypto.createHash('sha256').update(payload).digest('base64').replace(/[+/=]/g, '').substring(0, 8);
338
414
  }
339
415
  }
340
- //# sourceMappingURL=request.js.map
416
+ export { CrawleeRequest as Request };