@crawlee/core 4.0.0-beta.14 → 4.0.0-beta.140

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 (287) hide show
  1. package/README.md +14 -14
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +269 -0
  5. package/autoscaling/concurrency_system.js +365 -0
  6. package/autoscaling/cpu_load_signal.d.ts +43 -0
  7. package/autoscaling/cpu_load_signal.js +47 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  9. package/autoscaling/event_loop_load_signal.js +60 -0
  10. package/autoscaling/index.d.ts +6 -1
  11. package/autoscaling/index.js +6 -1
  12. package/autoscaling/load_signal.d.ts +100 -0
  13. package/autoscaling/load_signal.js +105 -0
  14. package/autoscaling/memory_load_signal.d.ts +47 -0
  15. package/autoscaling/memory_load_signal.js +106 -0
  16. package/autoscaling/snapshotter.d.ts +58 -163
  17. package/autoscaling/snapshotter.js +45 -263
  18. package/autoscaling/storage_backend_load_signal.d.ts +56 -0
  19. package/autoscaling/storage_backend_load_signal.js +73 -0
  20. package/autoscaling/system_status.d.ts +67 -89
  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 +3 -2
  29. package/cookie_utils.js +18 -7
  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 -126
  33. package/crawlers/crawler_commons.js +1 -108
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +7 -8
  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 +187 -63
  43. package/crawlers/statistics.js +354 -164
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +60 -153
  47. package/enqueue_links/enqueue_links.js +38 -229
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +49 -30
  51. package/enqueue_links/shared.js +94 -68
  52. package/errors.d.ts +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +12 -13
  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 +39 -13
  60. package/http.d.ts +9 -0
  61. package/http.js +28 -0
  62. package/index.d.ts +7 -5
  63. package/index.js +8 -4
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +78 -1
  67. package/log.js +106 -1
  68. package/memory-storage/consts.d.ts +4 -0
  69. package/memory-storage/consts.js +4 -0
  70. package/memory-storage/index.d.ts +1 -0
  71. package/memory-storage/index.js +1 -0
  72. package/memory-storage/memory-storage.d.ts +44 -0
  73. package/memory-storage/memory-storage.js +160 -0
  74. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  75. package/memory-storage/resource-clients/common/base-client.js +6 -0
  76. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  77. package/memory-storage/resource-clients/dataset.js +106 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +199 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +407 -0
  82. package/memory-storage/utils.d.ts +16 -0
  83. package/memory-storage/utils.js +41 -0
  84. package/owned_or_injected.d.ts +58 -0
  85. package/owned_or_injected.js +98 -0
  86. package/package.json +13 -12
  87. package/proxy_configuration.d.ts +22 -128
  88. package/proxy_configuration.js +32 -144
  89. package/recoverable_state.d.ts +83 -51
  90. package/recoverable_state.js +163 -72
  91. package/request.d.ts +57 -16
  92. package/request.js +130 -69
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +15 -15
  97. package/service_locator.d.ts +165 -0
  98. package/service_locator.js +253 -0
  99. package/session_pool/consts.d.ts +1 -2
  100. package/session_pool/consts.js +1 -2
  101. package/session_pool/errors.d.ts +0 -1
  102. package/session_pool/errors.js +0 -1
  103. package/session_pool/fingerprint.d.ts +9 -0
  104. package/session_pool/fingerprint.js +30 -0
  105. package/session_pool/index.d.ts +0 -2
  106. package/session_pool/index.js +0 -2
  107. package/session_pool/session.d.ts +35 -88
  108. package/session_pool/session.js +101 -159
  109. package/session_pool/session_pool.d.ts +74 -91
  110. package/session_pool/session_pool.js +175 -165
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +109 -56
  114. package/storages/dataset.js +283 -149
  115. package/storages/index.d.ts +9 -9
  116. package/storages/index.js +7 -9
  117. package/storages/key_value_store.d.ts +183 -48
  118. package/storages/key_value_store.js +445 -171
  119. package/storages/key_value_store_codec.d.ts +32 -0
  120. package/storages/key_value_store_codec.js +113 -0
  121. package/storages/request_dedup_cache.d.ts +22 -0
  122. package/storages/request_dedup_cache.js +48 -0
  123. package/storages/request_list.d.ts +52 -109
  124. package/storages/request_list.js +183 -152
  125. package/storages/request_loader.d.ts +101 -0
  126. package/storages/request_loader.js +1 -0
  127. package/storages/request_manager.d.ts +33 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +48 -19
  130. package/storages/request_manager_tandem.js +118 -45
  131. package/storages/request_queue.d.ts +290 -47
  132. package/storages/request_queue.js +762 -216
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +45 -89
  134. package/storages/sitemap_request_loader.js +438 -0
  135. package/storages/storage_instance_manager.d.ts +87 -0
  136. package/storages/storage_instance_manager.js +256 -0
  137. package/storages/storage_stats.d.ts +48 -0
  138. package/storages/storage_stats.js +29 -0
  139. package/storages/throttling_request_manager.d.ts +239 -0
  140. package/storages/throttling_request_manager.js +646 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +59 -11
  144. package/storages/utils.js +75 -15
  145. package/system-info/cpu-info.d.ts +67 -0
  146. package/system-info/cpu-info.js +216 -0
  147. package/system-info/memory-info.d.ts +31 -0
  148. package/system-info/memory-info.js +115 -0
  149. package/system-info/ps-tree.d.ts +17 -0
  150. package/system-info/ps-tree.js +144 -0
  151. package/system-info/runtime.d.ts +14 -0
  152. package/system-info/runtime.js +80 -0
  153. package/typedefs.d.ts +0 -6
  154. package/typedefs.js +0 -1
  155. package/url.d.ts +9 -0
  156. package/url.js +11 -0
  157. package/validators.d.ts +22 -18
  158. package/validators.js +13 -18
  159. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  160. package/autoscaling/autoscaled_pool.js.map +0 -1
  161. package/autoscaling/index.d.ts.map +0 -1
  162. package/autoscaling/index.js.map +0 -1
  163. package/autoscaling/snapshotter.d.ts.map +0 -1
  164. package/autoscaling/snapshotter.js.map +0 -1
  165. package/autoscaling/system_status.d.ts.map +0 -1
  166. package/autoscaling/system_status.js.map +0 -1
  167. package/configuration.d.ts.map +0 -1
  168. package/configuration.js.map +0 -1
  169. package/cookie_utils.d.ts.map +0 -1
  170. package/cookie_utils.js.map +0 -1
  171. package/crawlers/context_pipeline.d.ts.map +0 -1
  172. package/crawlers/context_pipeline.js.map +0 -1
  173. package/crawlers/crawler_commons.d.ts.map +0 -1
  174. package/crawlers/crawler_commons.js.map +0 -1
  175. package/crawlers/crawler_utils.d.ts +0 -10
  176. package/crawlers/crawler_utils.d.ts.map +0 -1
  177. package/crawlers/crawler_utils.js +0 -12
  178. package/crawlers/crawler_utils.js.map +0 -1
  179. package/crawlers/error_snapshotter.d.ts.map +0 -1
  180. package/crawlers/error_snapshotter.js.map +0 -1
  181. package/crawlers/error_tracker.d.ts.map +0 -1
  182. package/crawlers/error_tracker.js.map +0 -1
  183. package/crawlers/index.d.ts.map +0 -1
  184. package/crawlers/index.js.map +0 -1
  185. package/crawlers/internals/types.d.ts.map +0 -1
  186. package/crawlers/internals/types.js.map +0 -1
  187. package/crawlers/statistics.d.ts.map +0 -1
  188. package/crawlers/statistics.js.map +0 -1
  189. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  190. package/enqueue_links/enqueue_links.js.map +0 -1
  191. package/enqueue_links/index.d.ts.map +0 -1
  192. package/enqueue_links/index.js.map +0 -1
  193. package/enqueue_links/shared.d.ts.map +0 -1
  194. package/enqueue_links/shared.js.map +0 -1
  195. package/errors.d.ts.map +0 -1
  196. package/errors.js.map +0 -1
  197. package/events/event_manager.d.ts.map +0 -1
  198. package/events/event_manager.js.map +0 -1
  199. package/events/index.d.ts.map +0 -1
  200. package/events/index.js.map +0 -1
  201. package/events/local_event_manager.d.ts.map +0 -1
  202. package/events/local_event_manager.js.map +0 -1
  203. package/http_clients/base-http-client.d.ts +0 -140
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -40
  206. package/http_clients/base-http-client.js.map +0 -1
  207. package/http_clients/form-data-like.d.ts +0 -67
  208. package/http_clients/form-data-like.d.ts.map +0 -1
  209. package/http_clients/form-data-like.js +0 -5
  210. package/http_clients/form-data-like.js.map +0 -1
  211. package/http_clients/got-scraping-http-client.d.ts +0 -20
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -85
  214. package/http_clients/got-scraping-http-client.js.map +0 -1
  215. package/http_clients/index.d.ts +0 -3
  216. package/http_clients/index.d.ts.map +0 -1
  217. package/http_clients/index.js +0 -3
  218. package/http_clients/index.js.map +0 -1
  219. package/index.d.ts.map +0 -1
  220. package/index.js.map +0 -1
  221. package/log.d.ts.map +0 -1
  222. package/log.js.map +0 -1
  223. package/proxy_configuration.d.ts.map +0 -1
  224. package/proxy_configuration.js.map +0 -1
  225. package/recoverable_state.d.ts.map +0 -1
  226. package/recoverable_state.js.map +0 -1
  227. package/request.d.ts.map +0 -1
  228. package/request.js.map +0 -1
  229. package/router.d.ts.map +0 -1
  230. package/router.js.map +0 -1
  231. package/serialization.d.ts.map +0 -1
  232. package/serialization.js.map +0 -1
  233. package/session_pool/consts.d.ts.map +0 -1
  234. package/session_pool/consts.js.map +0 -1
  235. package/session_pool/errors.d.ts.map +0 -1
  236. package/session_pool/errors.js.map +0 -1
  237. package/session_pool/events.d.ts +0 -3
  238. package/session_pool/events.d.ts.map +0 -1
  239. package/session_pool/events.js +0 -3
  240. package/session_pool/events.js.map +0 -1
  241. package/session_pool/index.d.ts.map +0 -1
  242. package/session_pool/index.js.map +0 -1
  243. package/session_pool/session.d.ts.map +0 -1
  244. package/session_pool/session.js.map +0 -1
  245. package/session_pool/session_pool.d.ts.map +0 -1
  246. package/session_pool/session_pool.js.map +0 -1
  247. package/storages/access_checking.d.ts +0 -13
  248. package/storages/access_checking.d.ts.map +0 -1
  249. package/storages/access_checking.js +0 -14
  250. package/storages/access_checking.js.map +0 -1
  251. package/storages/dataset.d.ts.map +0 -1
  252. package/storages/dataset.js.map +0 -1
  253. package/storages/index.d.ts.map +0 -1
  254. package/storages/index.js.map +0 -1
  255. package/storages/key_value_store.d.ts.map +0 -1
  256. package/storages/key_value_store.js.map +0 -1
  257. package/storages/request_list.d.ts.map +0 -1
  258. package/storages/request_list.js.map +0 -1
  259. package/storages/request_list_adapter.d.ts +0 -58
  260. package/storages/request_list_adapter.d.ts.map +0 -1
  261. package/storages/request_list_adapter.js +0 -81
  262. package/storages/request_list_adapter.js.map +0 -1
  263. package/storages/request_manager_tandem.d.ts.map +0 -1
  264. package/storages/request_manager_tandem.js.map +0 -1
  265. package/storages/request_provider.d.ts +0 -371
  266. package/storages/request_provider.d.ts.map +0 -1
  267. package/storages/request_provider.js +0 -585
  268. package/storages/request_provider.js.map +0 -1
  269. package/storages/request_queue.d.ts.map +0 -1
  270. package/storages/request_queue.js.map +0 -1
  271. package/storages/request_queue_v2.d.ts +0 -87
  272. package/storages/request_queue_v2.d.ts.map +0 -1
  273. package/storages/request_queue_v2.js +0 -438
  274. package/storages/request_queue_v2.js.map +0 -1
  275. package/storages/sitemap_request_list.d.ts.map +0 -1
  276. package/storages/sitemap_request_list.js +0 -430
  277. package/storages/sitemap_request_list.js.map +0 -1
  278. package/storages/storage_manager.d.ts +0 -58
  279. package/storages/storage_manager.d.ts.map +0 -1
  280. package/storages/storage_manager.js +0 -105
  281. package/storages/storage_manager.js.map +0 -1
  282. package/storages/utils.d.ts.map +0 -1
  283. package/storages/utils.js.map +0 -1
  284. package/typedefs.d.ts.map +0 -1
  285. package/typedefs.js.map +0 -1
  286. package/validators.d.ts.map +0 -1
  287. package/validators.js.map +0 -1
@@ -1,54 +1,12 @@
1
- import ow from 'ow';
2
- import log from '@apify/log';
3
- /**
4
- * Internal class for tracking the proxy tier history for a specific domain.
5
- *
6
- * Predicts the best proxy tier for the next request based on the error history for different proxy tiers.
7
- */
8
- class ProxyTierTracker {
9
- histogram;
10
- currentTier;
11
- constructor(tieredProxyUrls) {
12
- this.histogram = tieredProxyUrls.map(() => 0);
13
- this.currentTier = 0;
14
- }
15
- /**
16
- * Processes a single step of the algorithm and updates the current tier prediction based on the error history.
17
- */
18
- processStep() {
19
- this.histogram.forEach((x, i) => {
20
- if (this.currentTier === i)
21
- return;
22
- if (x > 0)
23
- this.histogram[i]--;
24
- });
25
- const left = this.currentTier > 0 ? this.histogram[this.currentTier - 1] : Infinity;
26
- const right = this.currentTier < this.histogram.length - 1 ? this.histogram[this.currentTier + 1] : Infinity;
27
- if (this.histogram[this.currentTier] > Math.min(left, right)) {
28
- this.currentTier = left <= right ? this.currentTier - 1 : this.currentTier + 1;
29
- }
30
- else if (this.histogram[this.currentTier] === left) {
31
- this.currentTier--;
32
- }
33
- }
34
- /**
35
- * Increases the error score for the given proxy tier. This raises the chance of picking a different proxy tier for the subsequent requests.
36
- *
37
- * The error score is increased by 10 for the given tier. This means that this tier will be disadvantaged for the next 10 requests (every new request prediction decreases the error score by 1).
38
- * @param tier The proxy tier to mark as problematic.
39
- */
40
- addError(tier) {
41
- this.histogram[tier] += 10;
42
- }
43
- /**
44
- * Returns the best proxy tier for the next request based on the error history for different proxy tiers.
45
- * @returns The proxy tier prediction
46
- */
47
- predictTier() {
48
- this.processStep();
49
- return this.currentTier;
50
- }
51
- }
1
+ import { z } from 'zod';
2
+ import { parseArgument, schemas } from './validators.js';
3
+ const proxyConfigurationOptionsSchema = z.strictObject({
4
+ proxyUrls: z
5
+ .array(z.union([z.url(), z.null()]))
6
+ .nonempty()
7
+ .optional(),
8
+ newUrlFunction: schemas.anyFunction.optional(),
9
+ });
52
10
  /**
53
11
  * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
54
12
  * your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -79,13 +37,9 @@ class ProxyTierTracker {
79
37
  */
80
38
  export class ProxyConfiguration {
81
39
  isManInTheMiddle = false;
82
- nextCustomUrlIndex = 0;
83
- proxyUrls;
84
- tieredProxyUrls;
85
- usedProxyUrls = new Map();
86
- newUrlFunction;
87
- log = log.child({ prefix: 'ProxyConfiguration' });
88
- domainTiers = new Map();
40
+ #nextCustomUrlIndex = 0;
41
+ #proxyUrls;
42
+ #newUrlFunction;
89
43
  /**
90
44
  * Creates a {@link ProxyConfiguration} instance based on the provided options. Proxy servers are used to prevent target websites from
91
45
  * blocking your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -108,19 +62,17 @@ export class ProxyConfiguration {
108
62
  */
109
63
  constructor(options = {}) {
110
64
  const { validateRequired, ...rest } = options;
111
- ow(rest, ow.object.exactShape({
112
- proxyUrls: ow.optional.array.nonEmpty.ofType(ow.any(ow.string.url, ow.null)),
113
- newUrlFunction: ow.optional.function,
114
- tieredProxyUrls: ow.optional.array.nonEmpty.ofType(ow.array.nonEmpty.ofType(ow.any(ow.string.url, ow.null))),
115
- }));
116
- const { proxyUrls, newUrlFunction, tieredProxyUrls } = options;
117
- if ([proxyUrls, newUrlFunction, tieredProxyUrls].filter((x) => x).length > 1)
118
- this._throwCannotCombineCustomMethods();
65
+ if ('tieredProxyUrls' in rest) {
66
+ throw new Error('The `tieredProxyUrls` option has been removed in Crawlee v4. ' +
67
+ 'See the v4 upgrading guide for the recommended migration to named sessions.');
68
+ }
69
+ const { proxyUrls, newUrlFunction } = parseArgument(rest, proxyConfigurationOptionsSchema);
70
+ if (proxyUrls && newUrlFunction)
71
+ this.throwCannotCombineCustomMethods();
119
72
  if (!proxyUrls && !newUrlFunction && validateRequired)
120
- this._throwNoOptionsProvided();
121
- this.proxyUrls = proxyUrls;
122
- this.newUrlFunction = newUrlFunction;
123
- this.tieredProxyUrls = tieredProxyUrls;
73
+ this.throwNoOptionsProvided();
74
+ this.#proxyUrls = proxyUrls;
75
+ this.#newUrlFunction = newUrlFunction;
124
76
  }
125
77
  /**
126
78
  * This function creates a new {@link ProxyInfo} info object.
@@ -132,16 +84,7 @@ export class ProxyConfiguration {
132
84
  * @return Represents information about used proxy and its configuration.
133
85
  */
134
86
  async newProxyInfo(options) {
135
- let url;
136
- let tier;
137
- if (this.tieredProxyUrls) {
138
- const { proxyUrl, proxyTier } = this._handleTieredUrl(options);
139
- url = proxyUrl ?? undefined;
140
- tier = proxyTier;
141
- }
142
- else {
143
- url = await this.newUrl(options);
144
- }
87
+ const url = await this.newUrl(options);
145
88
  if (!url)
146
89
  return undefined;
147
90
  const { username, password, port, hostname } = new URL(url);
@@ -151,59 +94,8 @@ export class ProxyConfiguration {
151
94
  password: decodeURIComponent(password),
152
95
  hostname,
153
96
  port: port,
154
- proxyTier: tier,
155
- };
156
- }
157
- /**
158
- * Given a request / proxy tier, this function returns a new proxy URL based on the provided configuration options.
159
- * @param options Options for the tiered proxy rotation
160
- * @returns An object with the proxy URL and the proxy tier used.
161
- */
162
- _handleTieredUrl(options) {
163
- if (!this.tieredProxyUrls)
164
- throw new Error('Tiered proxy URLs are not set');
165
- if (!options || (!options?.request && options?.proxyTier === undefined)) {
166
- const allProxyUrls = this.tieredProxyUrls.flat();
167
- return {
168
- proxyUrl: allProxyUrls[this.nextCustomUrlIndex++ % allProxyUrls.length],
169
- };
170
- }
171
- let tierPrediction = options.proxyTier;
172
- if (typeof tierPrediction !== 'number') {
173
- tierPrediction = this.predictProxyTier(options.request);
174
- }
175
- const proxyTier = this.tieredProxyUrls[tierPrediction];
176
- return {
177
- proxyUrl: proxyTier[this.nextCustomUrlIndex++ % proxyTier.length],
178
- proxyTier: tierPrediction,
179
97
  };
180
98
  }
181
- /**
182
- * Given a `Request` object, this function returns the tier of the proxy that should be used for the request.
183
- *
184
- * This returns `null` if `tieredProxyUrls` option is not set.
185
- */
186
- predictProxyTier(request) {
187
- if (!this.tieredProxyUrls)
188
- return null;
189
- const domain = new URL(request.url).hostname;
190
- if (!this.domainTiers.has(domain)) {
191
- this.domainTiers.set(domain, new ProxyTierTracker(this.tieredProxyUrls));
192
- }
193
- request.userData.__crawlee ??= {};
194
- const tracker = this.domainTiers.get(domain);
195
- if (typeof request.userData.__crawlee.lastProxyTier === 'number') {
196
- tracker.addError(request.userData.__crawlee.lastProxyTier);
197
- }
198
- const tierPrediction = tracker.predictTier();
199
- if (typeof request.userData.__crawlee.lastProxyTier === 'number' &&
200
- request.userData.__crawlee.lastProxyTier !== tierPrediction) {
201
- log.debug(`Changing proxy tier for domain "${domain}" from ${request.userData.__crawlee.lastProxyTier} to ${tierPrediction}.`);
202
- }
203
- request.userData.__crawlee.lastProxyTier = tierPrediction;
204
- request.userData.__crawlee.forefront = true;
205
- return tierPrediction;
206
- }
207
99
  /**
208
100
  * Returns a new proxy URL based on provided configuration options.
209
101
  *
@@ -211,22 +103,19 @@ export class ProxyConfiguration {
211
103
  * For example, `http://bob:password123@proxy.example.com:8000`
212
104
  */
213
105
  async newUrl(options) {
214
- if (this.newUrlFunction) {
215
- return (await this._callNewUrlFunction({ request: options?.request })) ?? undefined;
216
- }
217
- if (this.tieredProxyUrls) {
218
- return this._handleTieredUrl(options).proxyUrl ?? undefined;
106
+ if (this.#newUrlFunction) {
107
+ return (await this.callNewUrlFunction({ request: options?.request })) ?? undefined;
219
108
  }
220
- return this._handleProxyUrlsList() ?? undefined;
109
+ return this.handleProxyUrlsList() ?? undefined;
221
110
  }
222
- _handleProxyUrlsList() {
223
- return this.proxyUrls[this.nextCustomUrlIndex++ % this.proxyUrls.length];
111
+ handleProxyUrlsList() {
112
+ return this.#proxyUrls[this.#nextCustomUrlIndex++ % this.#proxyUrls.length];
224
113
  }
225
114
  /**
226
115
  * Calls the custom newUrlFunction and checks format of its return value
227
116
  */
228
- async _callNewUrlFunction(options) {
229
- const proxyUrl = await this.newUrlFunction(options);
117
+ async callNewUrlFunction(options) {
118
+ const proxyUrl = await this.#newUrlFunction(options);
230
119
  try {
231
120
  if (proxyUrl) {
232
121
  new URL(proxyUrl); // eslint-disable-line no-new
@@ -237,11 +126,10 @@ export class ProxyConfiguration {
237
126
  throw new Error(`The provided newUrlFunction did not return a valid URL.\nCause: ${err.message}`);
238
127
  }
239
128
  }
240
- _throwCannotCombineCustomMethods() {
129
+ throwCannotCombineCustomMethods() {
241
130
  throw new Error('Cannot combine custom proxies "options.proxyUrls" with custom generating function "options.newUrlFunction".');
242
131
  }
243
- _throwNoOptionsProvided() {
132
+ throwNoOptionsProvided() {
244
133
  throw new Error('One of "options.proxyUrls" or "options.newUrlFunction" needs to be provided.');
245
134
  }
246
135
  }
247
- //# sourceMappingURL=proxy_configuration.js.map
@@ -1,5 +1,31 @@
1
- import { Configuration } from '@crawlee/core';
2
- import type { Log } from '@apify/log';
1
+ import type { Configuration, CrawleeLogger } from '@crawlee/core';
2
+ import { KeyValueStore } from '@crawlee/core';
3
+ import type { Awaitable } from '@crawlee/types';
4
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
5
+ /**
6
+ * One direction of the conversion between the state model and its persisted form - either a plain function, or a
7
+ * [Standard Schema](https://standardschema.dev) whose validated output is the result.
8
+ *
9
+ * A schema that fails to validate makes {@link RecoverableState} throw a {@link StateValidationError}. Zod
10
+ * codecs work directly, as their validation *is* the decode direction; use `(state) => codec.encode(state)` for the
11
+ * other one.
12
+ */
13
+ export type StateConversion<TFrom, TTo> = ((value: TFrom) => Awaitable<TTo>) | StandardSchemaV1<TFrom, TTo>;
14
+ /**
15
+ * A {@link StateConversion} for a caller that cannot await one - {@link Statistics}, whose `toJSON()` is
16
+ * synchronous, being the reason this exists.
17
+ *
18
+ * Only the function arm can be narrowed here: a Standard Schema is free to validate asynchronously, so a schema
19
+ * that does is rejected when it runs rather than when it is passed.
20
+ */
21
+ export type SyncStateConversion<TFrom, TTo> = ((value: TFrom) => TTo) | StandardSchemaV1<TFrom, TTo>;
22
+ /**
23
+ * Applies a {@link SyncStateConversion}, throwing a {@link StateValidationError} for a schema that rejects
24
+ * the value.
25
+ *
26
+ * @internal
27
+ */
28
+ export declare function convertStateSync<TFrom, TTo>(conversion: SyncStateConversion<TFrom, TTo>, value: TFrom, persistStateKey: string): TTo;
3
29
  export interface RecoverableStatePersistenceOptions {
4
30
  /**
5
31
  * The key under which the state is stored in the KeyValueStore
@@ -10,44 +36,45 @@ export interface RecoverableStatePersistenceOptions {
10
36
  */
11
37
  persistenceEnabled?: boolean;
12
38
  /**
13
- * The name of the KeyValueStore to use for persistence.
14
- * If neither a name nor an id are supplied, the default store will be used.
39
+ * The KeyValueStore to persist into, defaulting to the default store. Accepts a pending
40
+ * {@link KeyValueStore.open} so that callers do not have to be async to point at a specific store.
15
41
  */
16
- persistStateKvsName?: string;
42
+ keyValueStore?: KeyValueStore | PromiseLike<KeyValueStore>;
17
43
  /**
18
- * The identifier of the KeyValueStore to use for persistence.
19
- * If neither a name nor an id are supplied, the default store will be used.
44
+ * Time limit for a single load or save of the state, in milliseconds.
45
+ * @default 60_000
20
46
  */
21
- persistStateKvsId?: string;
47
+ persistenceTimeoutMillis?: number;
22
48
  }
23
49
  /**
24
50
  * Options for configuring the RecoverableState
25
51
  */
26
- export interface RecoverableStateOptions<TStateModel = Record<string, unknown>> extends RecoverableStatePersistenceOptions {
52
+ export interface RecoverableStateOptions<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> extends RecoverableStatePersistenceOptions {
27
53
  /**
28
- * The default state used if no persisted state is found.
29
- * A deep copy is made each time the state is used.
54
+ * The state used when no persisted state is found, and the state {@link RecoverableState.reset} restores.
55
+ *
56
+ * A plain value is deep-copied with `structuredClone` each time it is used, so pass a factory for a state
57
+ * that `structuredClone` cannot rebuild - one holding class instances, say, or one derived from a schema.
30
58
  */
31
- defaultState: TStateModel;
59
+ defaultState: TStateModel | (() => TStateModel);
32
60
  /**
33
61
  * A logger instance for logging operations related to state persistence
34
62
  */
35
- logger?: Log;
63
+ logger?: CrawleeLogger;
36
64
  /**
37
- * Configuration instance to use
65
+ * Configuration instance to use when opening the KeyValueStore
38
66
  */
39
- config?: Configuration;
67
+ configuration?: Configuration;
40
68
  /**
41
- * Optional function to transform the state to a JSON string before persistence.
42
- * If not provided, JSON.stringify will be used.
69
+ * Optional conversion of the state to a plain JSON-serializable value before it is persisted.
70
+ * If not provided, the state is persisted as is.
43
71
  */
44
- serialize?: (state: TStateModel) => string;
72
+ serialize?: StateConversion<TStateModel, TPersistedState>;
45
73
  /**
46
- * Optional function to transform a JSON-serialized object back to the state model.
47
- * If not provided, JSON.parse is used.
48
- * It is advisable to perform validation in this function and to throw an exception if it fails.
74
+ * Optional conversion of a persisted value back to the state model, and the place to validate a record before
75
+ * trusting it. If not provided, the persisted value is used as is.
49
76
  */
50
- deserialize?: (serializedState: string) => TStateModel;
77
+ deserialize?: StateConversion<TPersistedState, TStateModel>;
51
78
  }
52
79
  /**
53
80
  * A class for managing persistent recoverable state using a plain JavaScript object.
@@ -59,29 +86,23 @@ export interface RecoverableStateOptions<TStateModel = Record<string, unknown>>
59
86
  * The state is represented by a plain JavaScript object that can be serialized to and deserialized from JSON.
60
87
  * The class automatically hooks into the event system to persist state when needed.
61
88
  */
62
- export declare class RecoverableState<TStateModel = Record<string, unknown>> {
63
- private readonly defaultState;
64
- private state;
65
- private readonly persistenceEnabled;
66
- private readonly persistStateKey;
67
- private readonly persistStateKvsName?;
68
- private readonly persistStateKvsId?;
69
- private keyValueStore;
70
- private readonly log;
71
- private readonly config;
72
- private readonly serialize;
73
- private readonly deserialize;
89
+ export declare class RecoverableState<TStateModel = Record<string, unknown>, TPersistedState = TStateModel> {
90
+ #private;
74
91
  /**
75
92
  * Initialize a new recoverable state object.
76
93
  *
77
94
  * @param options Configuration options for the recoverable state
78
95
  */
79
- constructor(options: RecoverableStateOptions<TStateModel>);
96
+ constructor(options: RecoverableStateOptions<TStateModel, TPersistedState>);
80
97
  /**
81
98
  * Initialize the recoverable state.
82
99
  *
83
- * This method must be called before using the recoverable state. It loads the saved state
84
- * if persistence is enabled and registers the object to listen for PERSIST_STATE events.
100
+ * If persistence is enabled, this method loads the saved state and registers the object to listen for
101
+ * PERSIST_STATE events. A state established beforehand by {@link RecoverableState.reset} survives if there
102
+ * is no record to restore.
103
+ *
104
+ * Calling this again after a {@link RecoverableState.teardown} starts a new persistence window - the
105
+ * listener is registered again and the record reloaded.
85
106
  *
86
107
  * @returns The loaded state object
87
108
  */
@@ -90,34 +111,45 @@ export declare class RecoverableState<TStateModel = Record<string, unknown>> {
90
111
  * Clean up resources used by the recoverable state.
91
112
  *
92
113
  * If persistence is enabled, this method deregisters the object from PERSIST_STATE events
93
- * and persists the current state one last time.
114
+ * and persists the current state one last time, warning rather than throwing if that write fails - cleanup
115
+ * runs when the work is already done, and failing it would bury whatever the caller was doing. The in-memory
116
+ * state is left alone, and {@link RecoverableState.initialize} can be called again to open a new
117
+ * persistence window.
94
118
  */
95
119
  teardown(): Promise<void>;
96
120
  /**
97
121
  * Get the current state.
122
+ *
123
+ * Throws until the state has been established, by either {@link RecoverableState.initialize} or the
124
+ * synchronous {@link RecoverableState.reset} - the latter being how a caller that cannot await in its
125
+ * constructor gets a usable state right away.
98
126
  */
99
127
  get currentValue(): TStateModel;
100
128
  /**
101
- * Reset the state to the default values and clear any persisted state.
129
+ * Reset the in-memory state to the default values, leaving any persisted record alone.
102
130
  *
103
- * Resets the current state to the default state and, if persistence is enabled,
104
- * clears the persisted state from the KeyValueStore.
131
+ * Use {@link RecoverableState.resetStore} to clear the persisted record as well.
105
132
  */
106
- reset(): Promise<void>;
133
+ reset(): void;
134
+ /**
135
+ * Clear the persisted state record, leaving the in-memory state alone.
136
+ *
137
+ * This is a between-lifecycles operation - its point is to stop the next {@link RecoverableState.initialize}
138
+ * from restoring the record, so it throws while PERSIST_STATE events are still being handled, where the next
139
+ * one would write the record straight back. Use {@link RecoverableState.reset} to reset the state itself,
140
+ * or {@link RecoverableState.teardown} before clearing the record.
141
+ *
142
+ * A no-op if persistence is disabled or no KeyValueStore is available yet.
143
+ */
144
+ resetStore(): Promise<void>;
107
145
  /**
108
146
  * Persist the current state to the KeyValueStore.
109
147
  *
110
148
  * This method is typically called in response to a PERSIST_STATE event, but can also be called
111
- * directly when needed.
149
+ * directly when needed. It is a no-op if persistence is disabled, if no KeyValueStore is available yet, or if
150
+ * there is no state to write. A failed write only rejects here - the periodic and teardown ones warn instead.
112
151
  *
113
152
  * @param eventData Optional data associated with a PERSIST_STATE event
114
153
  */
115
- persistState(eventData?: {
116
- isMigrating: boolean;
117
- }): Promise<void>;
118
- /**
119
- * Load the saved state from the KeyValueStore
120
- */
121
- private loadSavedState;
154
+ persistState(eventData?: Record<string, unknown>): Promise<void>;
122
155
  }
123
- //# sourceMappingURL=recoverable_state.d.ts.map