@crawlee/core 4.0.0-beta.2 → 4.0.0-beta.200

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 (259) hide show
  1. package/README.md +17 -13
  2. package/byte_utils.d.ts +17 -0
  3. package/byte_utils.js +42 -0
  4. package/configuration.d.ts +88 -234
  5. package/configuration.js +162 -230
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +43 -10
  9. package/errors.js +57 -12
  10. package/events/event_manager.d.ts +35 -9
  11. package/events/event_manager.js +12 -13
  12. package/events/index.d.ts +1 -1
  13. package/events/index.js +0 -1
  14. package/events/local_event_manager.d.ts +15 -5
  15. package/events/local_event_manager.js +39 -42
  16. package/events/system_info.d.ts +38 -0
  17. package/events/system_info.js +1 -0
  18. package/index.d.ts +8 -11
  19. package/index.js +9 -10
  20. package/internal.d.ts +8 -0
  21. package/internal.js +9 -0
  22. package/iterables.d.ts +79 -0
  23. package/iterables.js +134 -0
  24. package/log.d.ts +81 -3
  25. package/log.js +134 -1
  26. package/memory-storage/consts.d.ts +4 -0
  27. package/memory-storage/consts.js +4 -0
  28. package/memory-storage/index.d.ts +1 -0
  29. package/memory-storage/index.js +1 -0
  30. package/memory-storage/memory-storage.d.ts +43 -0
  31. package/memory-storage/memory-storage.js +158 -0
  32. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  33. package/memory-storage/resource-clients/common/base-client.js +6 -0
  34. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  35. package/memory-storage/resource-clients/dataset.js +106 -0
  36. package/memory-storage/resource-clients/key-value-store.d.ts +56 -0
  37. package/memory-storage/resource-clients/key-value-store.js +180 -0
  38. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  39. package/memory-storage/resource-clients/request-queue.js +414 -0
  40. package/memory-storage/utils.d.ts +16 -0
  41. package/memory-storage/utils.js +41 -0
  42. package/owned_or_injected.d.ts +58 -0
  43. package/owned_or_injected.js +98 -0
  44. package/package.json +19 -20
  45. package/proxy_configuration.d.ts +29 -155
  46. package/proxy_configuration.js +38 -183
  47. package/recoverable_state.d.ts +177 -0
  48. package/recoverable_state.js +268 -0
  49. package/request.d.ts +62 -81
  50. package/request.js +125 -220
  51. package/serialization.d.ts +0 -1
  52. package/serialization.js +18 -18
  53. package/service_locator.d.ts +168 -0
  54. package/service_locator.js +255 -0
  55. package/storages/batched_adds.d.ts +37 -0
  56. package/storages/batched_adds.js +73 -0
  57. package/storages/dataset.d.ts +120 -56
  58. package/storages/dataset.js +299 -148
  59. package/storages/index.d.ts +9 -8
  60. package/storages/index.js +5 -8
  61. package/storages/key_value_store.d.ts +192 -65
  62. package/storages/key_value_store.js +453 -193
  63. package/storages/key_value_store_codec.d.ts +32 -0
  64. package/storages/key_value_store_codec.js +113 -0
  65. package/storages/request_dedup_cache.d.ts +22 -0
  66. package/storages/request_dedup_cache.js +48 -0
  67. package/storages/request_list.d.ts +55 -137
  68. package/storages/request_list.js +272 -245
  69. package/storages/request_loader.d.ts +127 -0
  70. package/storages/request_loader.js +36 -0
  71. package/storages/request_manager.d.ts +119 -0
  72. package/storages/request_manager.js +1 -0
  73. package/storages/request_manager_tandem.d.ts +94 -0
  74. package/storages/request_manager_tandem.js +200 -0
  75. package/storages/request_queue.d.ts +293 -48
  76. package/storages/request_queue.js +766 -216
  77. package/storages/storage_instance_manager.d.ts +86 -0
  78. package/storages/storage_instance_manager.js +256 -0
  79. package/storages/storage_stats.d.ts +48 -0
  80. package/storages/storage_stats.js +29 -0
  81. package/storages/transaction.d.ts +271 -0
  82. package/storages/transaction.js +296 -0
  83. package/storages/utils.d.ts +59 -11
  84. package/storages/utils.js +75 -15
  85. package/system-info/cpu-info.d.ts +67 -0
  86. package/system-info/cpu-info.js +216 -0
  87. package/system-info/memory-info.d.ts +31 -0
  88. package/system-info/memory-info.js +115 -0
  89. package/system-info/ps-tree.d.ts +17 -0
  90. package/system-info/ps-tree.js +144 -0
  91. package/system-info/runtime.d.ts +14 -0
  92. package/system-info/runtime.js +80 -0
  93. package/typedefs.d.ts +0 -6
  94. package/typedefs.js +0 -1
  95. package/url.d.ts +9 -0
  96. package/url.js +11 -0
  97. package/validators.d.ts +23 -18
  98. package/validators.js +14 -18
  99. package/autoscaling/autoscaled_pool.d.ts +0 -300
  100. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  101. package/autoscaling/autoscaled_pool.js +0 -533
  102. package/autoscaling/autoscaled_pool.js.map +0 -1
  103. package/autoscaling/index.d.ts +0 -4
  104. package/autoscaling/index.d.ts.map +0 -1
  105. package/autoscaling/index.js +0 -4
  106. package/autoscaling/index.js.map +0 -1
  107. package/autoscaling/snapshotter.d.ts +0 -189
  108. package/autoscaling/snapshotter.d.ts.map +0 -1
  109. package/autoscaling/snapshotter.js +0 -292
  110. package/autoscaling/snapshotter.js.map +0 -1
  111. package/autoscaling/system_status.d.ts +0 -181
  112. package/autoscaling/system_status.d.ts.map +0 -1
  113. package/autoscaling/system_status.js +0 -169
  114. package/autoscaling/system_status.js.map +0 -1
  115. package/configuration.d.ts.map +0 -1
  116. package/configuration.js.map +0 -1
  117. package/cookie_utils.d.ts +0 -43
  118. package/cookie_utils.d.ts.map +0 -1
  119. package/cookie_utils.js +0 -113
  120. package/cookie_utils.js.map +0 -1
  121. package/crawlers/crawler_commons.d.ts +0 -199
  122. package/crawlers/crawler_commons.d.ts.map +0 -1
  123. package/crawlers/crawler_commons.js +0 -116
  124. package/crawlers/crawler_commons.js.map +0 -1
  125. package/crawlers/crawler_extension.d.ts +0 -12
  126. package/crawlers/crawler_extension.d.ts.map +0 -1
  127. package/crawlers/crawler_extension.js +0 -14
  128. package/crawlers/crawler_extension.js.map +0 -1
  129. package/crawlers/crawler_utils.d.ts +0 -10
  130. package/crawlers/crawler_utils.d.ts.map +0 -1
  131. package/crawlers/crawler_utils.js +0 -12
  132. package/crawlers/crawler_utils.js.map +0 -1
  133. package/crawlers/error_snapshotter.d.ts +0 -59
  134. package/crawlers/error_snapshotter.d.ts.map +0 -1
  135. package/crawlers/error_snapshotter.js +0 -118
  136. package/crawlers/error_snapshotter.js.map +0 -1
  137. package/crawlers/error_tracker.d.ts +0 -54
  138. package/crawlers/error_tracker.d.ts.map +0 -1
  139. package/crawlers/error_tracker.js +0 -309
  140. package/crawlers/error_tracker.js.map +0 -1
  141. package/crawlers/index.d.ts +0 -7
  142. package/crawlers/index.d.ts.map +0 -1
  143. package/crawlers/index.js +0 -7
  144. package/crawlers/index.js.map +0 -1
  145. package/crawlers/statistics.d.ts +0 -204
  146. package/crawlers/statistics.d.ts.map +0 -1
  147. package/crawlers/statistics.js +0 -346
  148. package/crawlers/statistics.js.map +0 -1
  149. package/enqueue_links/enqueue_links.d.ts +0 -242
  150. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  151. package/enqueue_links/enqueue_links.js +0 -250
  152. package/enqueue_links/enqueue_links.js.map +0 -1
  153. package/enqueue_links/index.d.ts +0 -3
  154. package/enqueue_links/index.d.ts.map +0 -1
  155. package/enqueue_links/index.js +0 -3
  156. package/enqueue_links/index.js.map +0 -1
  157. package/enqueue_links/shared.d.ts +0 -67
  158. package/enqueue_links/shared.d.ts.map +0 -1
  159. package/enqueue_links/shared.js +0 -190
  160. package/enqueue_links/shared.js.map +0 -1
  161. package/errors.d.ts.map +0 -1
  162. package/errors.js.map +0 -1
  163. package/events/event_manager.d.ts.map +0 -1
  164. package/events/event_manager.js.map +0 -1
  165. package/events/index.d.ts.map +0 -1
  166. package/events/index.js.map +0 -1
  167. package/events/local_event_manager.d.ts.map +0 -1
  168. package/events/local_event_manager.js.map +0 -1
  169. package/http_clients/base-http-client.d.ts +0 -134
  170. package/http_clients/base-http-client.d.ts.map +0 -1
  171. package/http_clients/base-http-client.js +0 -33
  172. package/http_clients/base-http-client.js.map +0 -1
  173. package/http_clients/form-data-like.d.ts +0 -67
  174. package/http_clients/form-data-like.d.ts.map +0 -1
  175. package/http_clients/form-data-like.js +0 -5
  176. package/http_clients/form-data-like.js.map +0 -1
  177. package/http_clients/got-scraping-http-client.d.ts +0 -15
  178. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  179. package/http_clients/got-scraping-http-client.js +0 -69
  180. package/http_clients/got-scraping-http-client.js.map +0 -1
  181. package/http_clients/index.d.ts +0 -3
  182. package/http_clients/index.d.ts.map +0 -1
  183. package/http_clients/index.js +0 -3
  184. package/http_clients/index.js.map +0 -1
  185. package/index.d.ts.map +0 -1
  186. package/index.js.map +0 -1
  187. package/log.d.ts.map +0 -1
  188. package/log.js.map +0 -1
  189. package/proxy_configuration.d.ts.map +0 -1
  190. package/proxy_configuration.js.map +0 -1
  191. package/request.d.ts.map +0 -1
  192. package/request.js.map +0 -1
  193. package/router.d.ts +0 -134
  194. package/router.d.ts.map +0 -1
  195. package/router.js +0 -164
  196. package/router.js.map +0 -1
  197. package/serialization.d.ts.map +0 -1
  198. package/serialization.js.map +0 -1
  199. package/session_pool/consts.d.ts +0 -4
  200. package/session_pool/consts.d.ts.map +0 -1
  201. package/session_pool/consts.js +0 -4
  202. package/session_pool/consts.js.map +0 -1
  203. package/session_pool/errors.d.ts +0 -8
  204. package/session_pool/errors.d.ts.map +0 -1
  205. package/session_pool/errors.js +0 -12
  206. package/session_pool/errors.js.map +0 -1
  207. package/session_pool/events.d.ts +0 -3
  208. package/session_pool/events.d.ts.map +0 -1
  209. package/session_pool/events.js +0 -3
  210. package/session_pool/events.js.map +0 -1
  211. package/session_pool/index.d.ts +0 -6
  212. package/session_pool/index.d.ts.map +0 -1
  213. package/session_pool/index.js +0 -6
  214. package/session_pool/index.js.map +0 -1
  215. package/session_pool/session.d.ts +0 -199
  216. package/session_pool/session.d.ts.map +0 -1
  217. package/session_pool/session.js +0 -271
  218. package/session_pool/session.js.map +0 -1
  219. package/session_pool/session_pool.d.ts +0 -251
  220. package/session_pool/session_pool.d.ts.map +0 -1
  221. package/session_pool/session_pool.js +0 -375
  222. package/session_pool/session_pool.js.map +0 -1
  223. package/storages/access_checking.d.ts +0 -13
  224. package/storages/access_checking.d.ts.map +0 -1
  225. package/storages/access_checking.js +0 -14
  226. package/storages/access_checking.js.map +0 -1
  227. package/storages/dataset.d.ts.map +0 -1
  228. package/storages/dataset.js.map +0 -1
  229. package/storages/index.d.ts.map +0 -1
  230. package/storages/index.js.map +0 -1
  231. package/storages/key_value_store.d.ts.map +0 -1
  232. package/storages/key_value_store.js.map +0 -1
  233. package/storages/request_list.d.ts.map +0 -1
  234. package/storages/request_list.js.map +0 -1
  235. package/storages/request_provider.d.ts +0 -307
  236. package/storages/request_provider.d.ts.map +0 -1
  237. package/storages/request_provider.js +0 -555
  238. package/storages/request_provider.js.map +0 -1
  239. package/storages/request_queue.d.ts.map +0 -1
  240. package/storages/request_queue.js.map +0 -1
  241. package/storages/request_queue_v2.d.ts +0 -87
  242. package/storages/request_queue_v2.d.ts.map +0 -1
  243. package/storages/request_queue_v2.js +0 -438
  244. package/storages/request_queue_v2.js.map +0 -1
  245. package/storages/sitemap_request_list.d.ts +0 -245
  246. package/storages/sitemap_request_list.d.ts.map +0 -1
  247. package/storages/sitemap_request_list.js +0 -430
  248. package/storages/sitemap_request_list.js.map +0 -1
  249. package/storages/storage_manager.d.ts +0 -58
  250. package/storages/storage_manager.d.ts.map +0 -1
  251. package/storages/storage_manager.js +0 -105
  252. package/storages/storage_manager.js.map +0 -1
  253. package/storages/utils.d.ts.map +0 -1
  254. package/storages/utils.js.map +0 -1
  255. package/tsconfig.build.tsbuildinfo +0 -1
  256. package/typedefs.d.ts.map +0 -1
  257. package/typedefs.js.map +0 -1
  258. package/validators.d.ts.map +0 -1
  259. package/validators.js.map +0 -1
@@ -0,0 +1,177 @@
1
+ import type { Configuration } from './configuration.js';
2
+ import type { CrawleeLogger } from './log.js';
3
+ import { KeyValueStore } from './storages/key_value_store.js';
4
+ import type { Awaitable } from '@crawlee/types';
5
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
6
+ /**
7
+ * One direction of the conversion between the state model and its persisted form - either a plain function, or a
8
+ * [Standard Schema](https://standardschema.dev) whose validated output is the result.
9
+ *
10
+ * A schema that fails to validate makes {@link RecoverableState} throw a {@link StateValidationError}. Zod
11
+ * codecs work directly, as their validation *is* the decode direction; use `(state) => codec.encode(state)` for the
12
+ * other one.
13
+ */
14
+ export type StateConversion<TFrom, TTo> = ((value: TFrom) => Awaitable<TTo>) | StandardSchemaV1<TFrom, TTo>;
15
+ /**
16
+ * A {@link StateConversion} for a caller that cannot await one - {@link Statistics}, whose `toJSON()` is
17
+ * synchronous, being the reason this exists.
18
+ *
19
+ * Only the function arm can be narrowed here: a Standard Schema is free to validate asynchronously, so a schema
20
+ * that does is rejected when it runs rather than when it is passed.
21
+ */
22
+ export type SyncStateConversion<TFrom, TTo> = ((value: TFrom) => TTo) | StandardSchemaV1<TFrom, TTo>;
23
+ /**
24
+ * Applies a {@link SyncStateConversion}, throwing a {@link StateValidationError} for a schema that rejects
25
+ * the value.
26
+ *
27
+ * @internal
28
+ */
29
+ export declare function convertStateSync<TFrom, TTo>(conversion: SyncStateConversion<TFrom, TTo>, value: TFrom, persistStateKey: string): TTo;
30
+ export interface RecoverableStatePersistenceOptions {
31
+ /**
32
+ * The key under which the state is stored in the KeyValueStore
33
+ */
34
+ persistStateKey: string;
35
+ /**
36
+ * Flag to enable or disable state persistence
37
+ */
38
+ persistenceEnabled?: boolean;
39
+ /**
40
+ * The KeyValueStore to persist into, defaulting to the default store. Accepts a pending
41
+ * {@link KeyValueStore.open} so that callers do not have to be async to point at a specific store.
42
+ */
43
+ keyValueStore?: KeyValueStore | PromiseLike<KeyValueStore>;
44
+ /**
45
+ * Time limit for a single load or save of the state, in milliseconds.
46
+ * @default 60_000
47
+ */
48
+ persistenceTimeoutMillis?: number;
49
+ }
50
+ /**
51
+ * The fields of {@link RecoverableStateOptions}, without the constraint tying `contentType` to the conversions.
52
+ */
53
+ export interface RecoverableStateBaseOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> extends RecoverableStatePersistenceOptions {
54
+ /**
55
+ * The state used when no persisted state is found, and the state {@link RecoverableState.reset} restores.
56
+ *
57
+ * A plain value is deep-copied with `structuredClone` each time it is used, so pass a factory for a state
58
+ * that `structuredClone` cannot rebuild - one holding class instances, say, or one derived from a schema.
59
+ */
60
+ defaultState: TStateModel | (() => TStateModel);
61
+ /**
62
+ * A logger instance for logging operations related to state persistence
63
+ */
64
+ logger?: CrawleeLogger;
65
+ /**
66
+ * Configuration instance to use when opening the KeyValueStore
67
+ */
68
+ configuration?: Configuration;
69
+ /**
70
+ * Optional conversion of the state to a plain JSON-serializable value before it is persisted.
71
+ * If not provided, the state is persisted as is.
72
+ *
73
+ * With {@link RecoverableStateBaseOptions.contentType} set, it has to produce what
74
+ * {@link KeyValueStore.setValue} accepts alongside an explicit content type - a `string`, a `Buffer` or a
75
+ * stream.
76
+ */
77
+ serialize?: StateConversion<TStateModel, TPersistedState>;
78
+ /**
79
+ * Optional conversion of a persisted value back to the state model, and the place to validate a record before
80
+ * trusting it. If not provided, the persisted value is used as is.
81
+ *
82
+ * With {@link RecoverableStateBaseOptions.contentType} set, it receives a `Readable` of the record bytes
83
+ * instead of a parsed value.
84
+ */
85
+ deserialize?: StateConversion<TPersistedState, TStateModel>;
86
+ /**
87
+ * Content type of the persisted record. Setting it hands the record encoding over to
88
+ * {@link RecoverableStateBaseOptions.serialize} and {@link RecoverableStateBaseOptions.deserialize}, both of
89
+ * which are then required - the default JSON codec is bypassed in both directions. Meant for a state too large
90
+ * for `JSON.stringify`, which `serialize` can then stream out instead.
91
+ */
92
+ contentType?: string;
93
+ }
94
+ /**
95
+ * Options for configuring the RecoverableState
96
+ */
97
+ export type RecoverableStateOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> = RecoverableStateBaseOptions<TStateModel, TPersistedState> & ({
98
+ contentType?: undefined;
99
+ } | Required<Pick<RecoverableStateBaseOptions<TStateModel, TPersistedState>, 'serialize' | 'deserialize' | 'contentType'>>);
100
+ /**
101
+ * A class for managing persistent recoverable state using a plain JavaScript object.
102
+ *
103
+ * This class facilitates state persistence to a `KeyValueStore`, allowing data to be saved and retrieved
104
+ * across migrations or restarts. It manages the loading, saving, and resetting of state data,
105
+ * with optional persistence capabilities.
106
+ *
107
+ * The state is represented by a plain JavaScript object that can be serialized to and deserialized from JSON.
108
+ * The class automatically hooks into the event system to persist state when needed.
109
+ */
110
+ export declare class RecoverableState<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> {
111
+ #private;
112
+ /**
113
+ * Initialize a new recoverable state object.
114
+ *
115
+ * @param options Configuration options for the recoverable state
116
+ */
117
+ constructor(options: RecoverableStateOptions<TStateModel, TPersistedState>);
118
+ /**
119
+ * Initialize the recoverable state.
120
+ *
121
+ * If persistence is enabled, this method loads the saved state and registers the object to listen for
122
+ * PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
123
+ * is no record to restore.
124
+ *
125
+ * Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
126
+ * listener is registered again. The record is not reloaded: the in-memory state is what the teardown wrote, and
127
+ * reloading it would only drop whatever the deserialization leaves out.
128
+ *
129
+ * @returns The loaded state object
130
+ */
131
+ initialize(): Promise<TStateModel>;
132
+ /**
133
+ * Clean up resources used by the recoverable state.
134
+ *
135
+ * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
136
+ * and persists the current state one last time, warning rather than throwing if that write fails - cleanup
137
+ * runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
138
+ * state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
139
+ * persistence window.
140
+ */
141
+ teardown(): Promise<void>;
142
+ /**
143
+ * Get the current state.
144
+ *
145
+ * Throws until the state has been established, by either {@link RecoverableState.initialize} or the
146
+ * synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
147
+ * constructor gets a usable state right away.
148
+ */
149
+ get currentValue(): TStateModel;
150
+ /**
151
+ * Reset the in-memory state to the default values, leaving any persisted record alone.
152
+ *
153
+ * Use {@link RecoverableState.resetStore} to clear the persisted record as well.
154
+ */
155
+ reset(): void;
156
+ /**
157
+ * Clear the persisted state record, leaving the in-memory state alone.
158
+ *
159
+ * This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
160
+ * from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
161
+ * one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
162
+ * or {@link RecoverableState.teardown} before clearing the record.
163
+ *
164
+ * A no-op if persistence is disabled.
165
+ */
166
+ resetStore(): Promise<void>;
167
+ /**
168
+ * Persist the current state to the KeyValueStore.
169
+ *
170
+ * This method is typically called in response to a PERSIST_STATE event, but can also be called
171
+ * directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
172
+ * there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
173
+ *
174
+ * @param eventData Optional data associated with a PERSIST_STATE event
175
+ */
176
+ persistState(eventData?: Record<string, unknown>): Promise<void>;
177
+ }
@@ -0,0 +1,268 @@
1
+ import { Readable } from 'node:stream';
2
+ import { addTimeoutToPromise, storage as timeoutStorage } from '@apify/timeout';
3
+ import { StateValidationError } from './errors.js';
4
+ import { EventType } from './events/event_manager.js';
5
+ import { serviceLocator } from './service_locator.js';
6
+ import { KeyValueStore } from './storages/key_value_store.js';
7
+ const DEFAULT_PERSISTENCE_TIMEOUT_MILLIS = 60_000;
8
+ /**
9
+ * Applies a {@link SyncStateConversion}, throwing a {@link StateValidationError} for a schema that rejects
10
+ * the value.
11
+ *
12
+ * @internal
13
+ */
14
+ export function convertStateSync(conversion, value, persistStateKey) {
15
+ if (typeof conversion === 'function') {
16
+ return conversion(value);
17
+ }
18
+ const result = conversion['~standard'].validate(value);
19
+ if ('then' in result) {
20
+ throw new Error(`The state conversion for '${persistStateKey}' validated asynchronously, which this caller cannot await.`);
21
+ }
22
+ if (result.issues) {
23
+ throw new StateValidationError(persistStateKey, result.issues);
24
+ }
25
+ return result.value;
26
+ }
27
+ /**
28
+ * A class for managing persistent recoverable state using a plain JavaScript object.
29
+ *
30
+ * This class facilitates state persistence to a `KeyValueStore`, allowing data to be saved and retrieved
31
+ * across migrations or restarts. It manages the loading, saving, and resetting of state data,
32
+ * with optional persistence capabilities.
33
+ *
34
+ * The state is represented by a plain JavaScript object that can be serialized to and deserialized from JSON.
35
+ * The class automatically hooks into the event system to persist state when needed.
36
+ */
37
+ export class RecoverableState {
38
+ #defaultState;
39
+ #state = null;
40
+ #initialized = false;
41
+ #recordLoaded = false;
42
+ #listening = false;
43
+ #persistenceEnabled;
44
+ #persistStateKey;
45
+ #persistenceTimeoutMillis;
46
+ #configuration;
47
+ #keyValueStore;
48
+ #log;
49
+ #serialize;
50
+ #deserialize;
51
+ #contentType;
52
+ #persistStateQuietly;
53
+ /**
54
+ * Initialize a new recoverable state object.
55
+ *
56
+ * @param options Configuration options for the recoverable state
57
+ */
58
+ constructor(options) {
59
+ const { defaultState } = options;
60
+ this.#defaultState =
61
+ typeof defaultState === 'function'
62
+ ? defaultState
63
+ : () => structuredClone(defaultState);
64
+ this.#persistStateKey = options.persistStateKey;
65
+ this.#persistenceEnabled = options.persistenceEnabled ?? false;
66
+ this.#persistenceTimeoutMillis = options.persistenceTimeoutMillis ?? DEFAULT_PERSISTENCE_TIMEOUT_MILLIS;
67
+ this.#configuration = options.configuration;
68
+ this.#keyValueStore = options.keyValueStore ?? null;
69
+ this.#log = options.logger ?? serviceLocator.getLogger().child({ prefix: 'RecoverableState' });
70
+ this.#contentType = options.contentType;
71
+ if (this.#contentType !== undefined && (options.serialize === undefined || options.deserialize === undefined)) {
72
+ throw new Error(`A 'contentType' for the state persisted under key '${this.#persistStateKey}' requires both 'serialize' and 'deserialize' - the record is no longer JSON the default codec can handle.`);
73
+ }
74
+ this.#serialize = this.#toConversion(options.serialize);
75
+ this.#deserialize = this.#toConversion(options.deserialize);
76
+ // A pending open() may reject before anything here awaits it. Observe the rejection so it surfaces on
77
+ // first use rather than as an unhandled rejection - most immediately when persistence is disabled and
78
+ // nothing ever awaits the store.
79
+ if (this.#keyValueStore !== null) {
80
+ Promise.resolve(this.#keyValueStore).then(undefined, () => { });
81
+ }
82
+ // The automatic persists, where a rejection has nowhere useful to go - the event manager does not catch
83
+ // listener errors, and throwing from teardown would bury the outcome of the work it cleans up after.
84
+ this.#persistStateQuietly = async (eventData) => this.persistState(eventData).catch((error) => this.#log.warning(`Failed to persist the state under key '${this.#persistStateKey}'.`, { error }));
85
+ }
86
+ /** Normalizes a conversion option into a function. Absent conversions pass the value through unchanged. */
87
+ #toConversion(conversion) {
88
+ if (conversion === undefined) {
89
+ return async (value) => value;
90
+ }
91
+ if (typeof conversion === 'function') {
92
+ return async (value) => conversion(value);
93
+ }
94
+ return async (value) => {
95
+ const result = await conversion['~standard'].validate(value);
96
+ if (result.issues) {
97
+ throw new StateValidationError(this.#persistStateKey, result.issues);
98
+ }
99
+ return result.value;
100
+ };
101
+ }
102
+ /**
103
+ * Initialize the recoverable state.
104
+ *
105
+ * If persistence is enabled, this method loads the saved state and registers the object to listen for
106
+ * PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
107
+ * is no record to restore.
108
+ *
109
+ * Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
110
+ * listener is registered again. The record is not reloaded: the in-memory state is what the teardown wrote, and
111
+ * reloading it would only drop whatever the deserialization leaves out.
112
+ *
113
+ * @returns The loaded state object
114
+ */
115
+ async initialize() {
116
+ if (this.#initialized) {
117
+ return this.currentValue;
118
+ }
119
+ if (this.#persistenceEnabled) {
120
+ await this.#openKeyValueStore();
121
+ serviceLocator.getEventManager().on(EventType.PERSIST_STATE, this.#persistStateQuietly);
122
+ this.#listening = true;
123
+ }
124
+ // Flipped before the record is loaded, so that a caller catching a `StateValidationError` is left with a
125
+ // fully wired object running on the default state rather than a half-initialized one.
126
+ this.#initialized = true;
127
+ this.#state ??= this.#defaultState();
128
+ if (!this.#recordLoaded) {
129
+ this.#recordLoaded = true;
130
+ await this.#loadSavedState();
131
+ }
132
+ return this.currentValue;
133
+ }
134
+ /**
135
+ * Clean up resources used by the recoverable state.
136
+ *
137
+ * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
138
+ * and persists the current state one last time, warning rather than throwing if that write fails - cleanup
139
+ * runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
140
+ * state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
141
+ * persistence window.
142
+ */
143
+ async teardown() {
144
+ this.#initialized = false;
145
+ if (!this.#persistenceEnabled) {
146
+ return;
147
+ }
148
+ serviceLocator.getEventManager().off(EventType.PERSIST_STATE, this.#persistStateQuietly);
149
+ this.#listening = false;
150
+ await this.#persistStateQuietly();
151
+ }
152
+ /**
153
+ * Get the current state.
154
+ *
155
+ * Throws until the state has been established, by either {@link RecoverableState.initialize} or the
156
+ * synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
157
+ * constructor gets a usable state right away.
158
+ */
159
+ get currentValue() {
160
+ if (this.#state === null) {
161
+ throw new Error('Recoverable state has not yet been loaded - call initialize() or reset() first');
162
+ }
163
+ return this.#state;
164
+ }
165
+ /**
166
+ * Reset the in-memory state to the default values, leaving any persisted record alone.
167
+ *
168
+ * Use {@link RecoverableState.resetStore} to clear the persisted record as well.
169
+ */
170
+ reset() {
171
+ this.#state = this.#defaultState();
172
+ }
173
+ /**
174
+ * Clear the persisted state record, leaving the in-memory state alone.
175
+ *
176
+ * This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
177
+ * from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
178
+ * one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
179
+ * or {@link RecoverableState.teardown} before clearing the record.
180
+ *
181
+ * A no-op if persistence is disabled.
182
+ */
183
+ async resetStore() {
184
+ if (this.#listening) {
185
+ throw new Error(`Cannot clear the state persisted under key '${this.#persistStateKey}' while it is still being persisted periodically - the next PERSIST_STATE event would write it straight back. Use reset() to reset the state itself, or teardown() before clearing the record.`);
186
+ }
187
+ if (!this.#persistenceEnabled) {
188
+ return;
189
+ }
190
+ const keyValueStore = await this.#openKeyValueStore();
191
+ await this.#withTimeout(async () => keyValueStore.setValue(this.#persistStateKey, null), 'Clearing the persisted state');
192
+ }
193
+ /**
194
+ * Persist the current state to the KeyValueStore.
195
+ *
196
+ * This method is typically called in response to a PERSIST_STATE event, but can also be called
197
+ * directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
198
+ * there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
199
+ *
200
+ * @param eventData Optional data associated with a PERSIST_STATE event
201
+ */
202
+ async persistState(eventData) {
203
+ if (!this.#persistenceEnabled || this.#state === null) {
204
+ return;
205
+ }
206
+ const keyValueStore = await this.#resolveKeyValueStore();
207
+ if (keyValueStore === null) {
208
+ return;
209
+ }
210
+ this.#log.debug(`Persisting state of the RecoverableState (eventData=${JSON.stringify(eventData)}).`);
211
+ const serializedState = await this.#serialize(this.currentValue);
212
+ await this.#withTimeout(async () => this.#contentType === undefined
213
+ ? keyValueStore.setValue(this.#persistStateKey, serializedState)
214
+ : keyValueStore.setValue(this.#persistStateKey, serializedState, {
215
+ contentType: this.#contentType,
216
+ }), 'Persisting the state');
217
+ }
218
+ /** Falls back to the default store when none was supplied - persistence has to write somewhere. */
219
+ async #openKeyValueStore() {
220
+ this.#keyValueStore ??= KeyValueStore.open(null, {
221
+ configuration: this.#configuration ?? serviceLocator.getConfiguration(),
222
+ });
223
+ return (await this.#resolveKeyValueStore());
224
+ }
225
+ /** Awaits a store handed over as a pending `open()`, keeping the resolved instance for later calls. */
226
+ async #resolveKeyValueStore() {
227
+ if (this.#keyValueStore === null) {
228
+ return null;
229
+ }
230
+ this.#keyValueStore = await this.#keyValueStore;
231
+ return this.#keyValueStore;
232
+ }
233
+ /**
234
+ * Load the saved state from the KeyValueStore. Leaves the current state alone if there is no record to load.
235
+ */
236
+ async #loadSavedState() {
237
+ if (!this.#persistenceEnabled) {
238
+ return;
239
+ }
240
+ const keyValueStore = await this.#resolveKeyValueStore();
241
+ if (keyValueStore === null) {
242
+ return;
243
+ }
244
+ // With a content type, the record is whatever `serialize` produced, so the codec's parse is skipped and
245
+ // `deserialize` gets the bytes as a stream - the shape a streaming parser wants.
246
+ // TODO: read the record as a stream instead of buffering it and wrapping (https://github.com/apify/crawlee/issues/2929).
247
+ const storedState = await this.#withTimeout(async () => {
248
+ if (this.#contentType === undefined) {
249
+ return keyValueStore.getValue(this.#persistStateKey);
250
+ }
251
+ const record = await keyValueStore.getRecord(this.#persistStateKey);
252
+ if (record === null) {
253
+ return null;
254
+ }
255
+ return Readable.from(Buffer.isBuffer(record.value) ? record.value : Buffer.from(record.value));
256
+ }, 'Loading the persisted state');
257
+ if (storedState === null || storedState === undefined) {
258
+ return;
259
+ }
260
+ this.#state = await this.#deserialize(storedState);
261
+ }
262
+ async #withTimeout(operation, description) {
263
+ // `@apify/timeout` shares one `AbortController` across nested frames and `KeyValueStore` checks it on
264
+ // every operation, so a teardown-time persist running inside an already-expired request handler timeout
265
+ // would be aborted before it started. Hence a fresh timeout context.
266
+ return timeoutStorage.exit(async () => addTimeoutToPromise(operation, this.#persistenceTimeoutMillis, `${description} under key '${this.#persistStateKey}' timed out after ${this.#persistenceTimeoutMillis / 1000} seconds.`));
267
+ }
268
+ }
package/request.d.ts CHANGED
@@ -1,20 +1,12 @@
1
1
  import type { BinaryLike } from 'node:crypto';
2
- import type { Dictionary } from '@crawlee/types';
3
- import type { EnqueueLinksOptions } from './enqueue_links/enqueue_links.js';
4
- import type { AllowedHttpMethods } from './typedefs.js';
5
- export declare enum RequestState {
6
- UNPROCESSED = 0,
7
- BEFORE_NAV = 1,
8
- AFTER_NAV = 2,
9
- REQUEST_HANDLER = 3,
10
- DONE = 4,
11
- ERROR_HANDLER = 5,
12
- ERROR = 6,
13
- SKIPPED = 7
14
- }
2
+ import type { AllowedHttpMethods, Dictionary, RequestSchema } from '@crawlee/types';
3
+ import type { EnqueueStrategy } from '@crawlee/utils';
4
+ /** The `strategy` option accepted by {@link ExtractLinksOptions} and {@link EnqueueUrlsOptions}. */
5
+ export type EnqueueStrategyOption = EnqueueStrategy | 'all' | 'same-domain' | 'same-hostname' | 'same-origin';
15
6
  /**
16
- * Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata.
17
- * The `Request` object also stores information about errors that occurred during processing of the request.
7
+ * Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata, together
8
+ * with the processing state a request queue keeps about it (`retryCount`, `errorMessages`, `handledAt`, ...).
9
+ * Inside a crawler, requests are {@link CrawlingRequest}s, which add the crawler's own per-request settings.
18
10
  *
19
11
  * Each `Request` instance has the `uniqueKey` property, which can be either specified
20
12
  * manually in the constructor or generated automatically from the URL. Two requests with the same `uniqueKey`
@@ -30,21 +22,16 @@ export declare enum RequestState {
30
22
  * const request = new Request({
31
23
  * url: 'http://www.example.com',
32
24
  * headers: { Accept: 'application/json' },
25
+ * userData: { foo: 'bar' },
33
26
  * });
34
27
  *
35
- * ...
36
- *
37
- * request.userData.foo = 'bar';
38
- * request.pushErrorMessage(new Error('Request failed!'));
39
- *
40
- * ...
41
- *
42
- * const foo = request.userData.foo;
28
+ * await requestQueue.addRequest(request);
43
29
  * ```
44
30
  * @category Sources
45
31
  */
46
- export declare class Request<UserData extends Dictionary = Dictionary> {
47
- /** Request ID */
32
+ declare class CrawleeRequest<UserData extends Dictionary = Dictionary> {
33
+ #private;
34
+ /** Storage-assigned request ID. Only present on requests that went through a {@link RequestQueue}. */
48
35
  id?: string;
49
36
  /** URL of the web page to crawl. */
50
37
  url: string;
@@ -74,9 +61,12 @@ export declare class Request<UserData extends Dictionary = Dictionary> {
74
61
  errorMessages: string[];
75
62
  /** Object with HTTP headers. Key is header name, value is the value. */
76
63
  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. */
64
+ /**
65
+ * Custom user data assigned to the request.
66
+ *
67
+ * All data stored in `userData` must be JSON-serializable.
68
+ * Storing non-serializable values (e.g. functions, symbols) may result in unexpected results.
69
+ */
80
70
  userData: UserData;
81
71
  /**
82
72
  * ISO datetime string that indicates the time when the request has been processed.
@@ -85,48 +75,27 @@ export declare class Request<UserData extends Dictionary = Dictionary> {
85
75
  handledAt?: string;
86
76
  /**
87
77
  * `Request` parameters including the URL, HTTP method and headers, and others.
78
+ *
79
+ * Processing state (`retryCount`, `errorMessages`, `handledAt`, `loadedUrl`, `id`) is not an option;
80
+ * requests coming back from a storage are rebuilt with {@link Request.fromSchema}.
88
81
  */
89
82
  constructor(options: RequestOptions<UserData>);
90
- /** Tells the crawler processing this request to skip the navigation and process the request directly. */
91
- get skipNavigation(): boolean;
92
- /** Tells the crawler processing this request to skip the navigation and process the request directly. */
93
- 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);
83
+ /**
84
+ * Rebuilds a request from its stored form, including the processing state a
85
+ * {@link RequestOptions} object cannot carry. Subclasses get instances of themselves.
86
+ */
87
+ static fromSchema<UserData extends Dictionary = Dictionary>(schema: RequestSchema): CrawleeRequest<UserData>;
88
+ /**
89
+ * Converts the Crawlee Request object to a `fetch` API Request object.
90
+ * @returns The native `fetch` API Request object.
91
+ */
92
+ intoFetchAPIRequest(): Request;
98
93
  /** shortcut for getting `request.userData.label` */
99
94
  get label(): string | undefined;
100
95
  /** shortcut for setting `request.userData.label` */
101
96
  set label(value: string | undefined);
102
- /** Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`. */
103
- get maxRetries(): number | undefined;
104
- /** Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`. */
105
- set maxRetries(value: number | undefined);
106
- /** Describes the request's current lifecycle state. */
107
- get state(): RequestState;
108
- /** Describes the request's current lifecycle state. */
109
- set state(value: RequestState);
110
- private get enqueueStrategy();
111
- private set enqueueStrategy(value);
112
- /**
113
- * Stores information about an error that occurred during processing of this request.
114
- *
115
- * You should always use Error instances when throwing errors in JavaScript.
116
- *
117
- * Nevertheless, to improve the debugging experience when using third party libraries
118
- * that may not always throw an Error instance, the function performs a type
119
- * inspection of the passed argument and attempts to extract as much information
120
- * as possible, since just throwing a bad type error makes any debugging rather difficult.
121
- *
122
- * @param errorOrMessage Error object or error message to be stored in the request.
123
- * @param [options]
124
- */
125
- pushErrorMessage(errorOrMessage: unknown, options?: PushErrorMessageOptions): void;
126
- protected _computeUniqueKey(options: ComputeUniqueKeyOptions): string;
127
- protected _hashPayload(payload: BinaryLike): string;
128
97
  /** @internal */
129
- static computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey, }: ComputeUniqueKeyOptions): string;
98
+ static computeUniqueKey({ url, method, payload, keepUrlFragment, useExtendedUniqueKey, alwaysEnqueue, }: ComputeUniqueKeyOptions): string;
130
99
  /** @internal */
131
100
  static hashPayload(payload: BinaryLike): string;
132
101
  }
@@ -147,7 +116,7 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
147
116
  * The `keepUrlFragment` option determines whether URL hash fragment is included in the `uniqueKey` or not.
148
117
  *
149
118
  * The `useExtendedUniqueKey` options determines whether method and payload are included in the `uniqueKey`,
150
- * producing a `uniqueKey` in the following format: `METHOD(payloadHash):normalizedUrl`. This is useful
119
+ * producing a `uniqueKey` in the following format: `METHOD|payloadHash|normalizedUrl`. This is useful
151
120
  * when requests point to the same URL, but with different methods and payloads. For example: form submits.
152
121
  *
153
122
  * Pass an arbitrary non-empty text value to the `uniqueKey` property
@@ -171,6 +140,9 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
171
140
  /**
172
141
  * Custom user data assigned to the request. Use this to save any request related data to the
173
142
  * request's scope, keeping them accessible on retries, failures etc.
143
+ *
144
+ * All data stored in `userData` must be JSON-serializable.
145
+ * Storing non-serializable values (e.g. functions, symbols) may result in unexpected results.
174
146
  */
175
147
  userData?: UserData;
176
148
  /**
@@ -192,36 +164,45 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
192
164
  * @default false
193
165
  */
194
166
  useExtendedUniqueKey?: boolean;
167
+ /**
168
+ * If `true` then a random value is included in the `uniqueKey` computation, ensuring the request
169
+ * is always enqueued even if a request with the same URL (and method/payload) is already present
170
+ * in the queue. Cannot be used together with a custom `uniqueKey`.
171
+ * @default false
172
+ */
173
+ alwaysEnqueue?: boolean;
195
174
  /**
196
175
  * The `true` value indicates that the request will not be automatically retried on error.
197
176
  * @default false
198
177
  */
199
178
  noRetry?: boolean;
179
+ /**
180
+ * ID of a session from the crawler's `SessionPool` to use for this request.
181
+ * When set, the crawler will fetch this session from the pool instead of creating a new one.
182
+ */
183
+ sessionId?: string;
200
184
  /**
201
185
  * If set to `true` then the crawler processing this request evaluates
202
186
  * the `requestHandler` immediately without prior browser navigation.
187
+ *
188
+ * When enabled, the crawling context will not contain the results of the navigation
189
+ * (e.g. `response`, `body`, `contentType`, `$` or `request.loadedUrl`).
190
+ * Accessing these properties will throw a {@link NavigationSkippedError} at runtime.
203
191
  * @default false
204
192
  */
205
193
  skipNavigation?: boolean;
194
+ /**
195
+ * Depth of the request in the current crawl tree.
196
+ * Note that this is dependent on the crawler setup and might produce unexpected results when used with multiple crawlers.
197
+ * @default 0
198
+ */
199
+ crawlDepth?: number;
206
200
  /**
207
201
  * Maximum number of retries for this request. Allows to override the global `maxRequestRetries` option of `BasicCrawler`.
208
202
  */
209
203
  maxRetries?: number;
210
204
  /** @internal */
211
- id?: string;
212
- /** @internal */
213
- handledAt?: string;
214
- /** @internal */
215
- lockExpiresAt?: Date;
216
- /** @internal */
217
- enqueueStrategy?: EnqueueLinksOptions['strategy'];
218
- }
219
- export interface PushErrorMessageOptions {
220
- /**
221
- * Only push the error message without stack trace when true.
222
- * @default false
223
- */
224
- omitStack?: boolean;
205
+ enqueueStrategy?: EnqueueStrategyOption;
225
206
  }
226
207
  interface ComputeUniqueKeyOptions {
227
208
  url: string;
@@ -229,15 +210,15 @@ interface ComputeUniqueKeyOptions {
229
210
  payload?: string | Buffer;
230
211
  keepUrlFragment?: boolean;
231
212
  useExtendedUniqueKey?: boolean;
213
+ alwaysEnqueue?: boolean;
232
214
  }
233
215
  export type Source = (Partial<RequestOptions> & {
234
216
  requestsFromUrl?: string;
235
217
  regex?: RegExp;
236
- }) | Request;
218
+ }) | CrawleeRequest;
237
219
  /** @internal */
238
220
  export interface InternalSource {
239
221
  requestsFromUrl: string;
240
222
  regex?: RegExp;
241
223
  }
242
- export {};
243
- //# sourceMappingURL=request.d.ts.map
224
+ export { CrawleeRequest as Request };