@crawlee/core 4.0.0-beta.27 → 4.0.0-beta.271

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 (265) hide show
  1. package/README.md +15 -15
  2. package/byte-utils.d.ts +17 -0
  3. package/byte-utils.js +42 -0
  4. package/configuration.d.ts +77 -235
  5. package/configuration.js +159 -227
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +45 -18
  9. package/errors.js +58 -27
  10. package/events/event-manager.d.ts +78 -0
  11. package/events/{event_manager.js → event-manager.js} +12 -13
  12. package/events/index.d.ts +3 -3
  13. package/events/index.js +2 -3
  14. package/events/local-event-manager.d.ts +32 -0
  15. package/events/local-event-manager.js +101 -0
  16. package/events/system-info.d.ts +38 -0
  17. package/events/system-info.js +1 -0
  18. package/index.d.ts +9 -12
  19. package/index.js +10 -11
  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 +77 -1
  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 +35 -0
  35. package/memory-storage/resource-clients/dataset.js +108 -0
  36. package/memory-storage/resource-clients/key-value-store.d.ts +54 -0
  37. package/memory-storage/resource-clients/key-value-store.js +179 -0
  38. package/memory-storage/resource-clients/request-queue.d.ts +55 -0
  39. package/memory-storage/resource-clients/request-queue.js +413 -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 +23 -23
  45. package/proxy-configuration.d.ts +118 -0
  46. package/proxy-configuration.js +141 -0
  47. package/recoverable-state.d.ts +177 -0
  48. package/recoverable-state.js +268 -0
  49. package/request.d.ts +48 -101
  50. package/request.js +139 -249
  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 +39 -0
  56. package/storages/batched-adds.js +81 -0
  57. package/storages/dataset.d.ts +105 -58
  58. package/storages/dataset.js +292 -150
  59. package/storages/index.d.ts +11 -12
  60. package/storages/index.js +7 -12
  61. package/storages/key-value-store-codec.d.ts +32 -0
  62. package/storages/key-value-store-codec.js +108 -0
  63. package/storages/{key_value_store.d.ts → key-value-store.d.ts} +169 -72
  64. package/storages/key-value-store.js +767 -0
  65. package/storages/request-dedup-cache.d.ts +20 -0
  66. package/storages/request-dedup-cache.js +48 -0
  67. package/storages/{request_list.d.ts → request-list.d.ts} +33 -173
  68. package/storages/{request_list.js → request-list.js} +276 -255
  69. package/storages/request-loader.d.ts +127 -0
  70. package/storages/request-loader.js +34 -0
  71. package/storages/request-manager-tandem.d.ts +82 -0
  72. package/storages/request-manager-tandem.js +200 -0
  73. package/storages/request-manager.d.ts +119 -0
  74. package/storages/request-manager.js +1 -0
  75. package/storages/{request_provider.d.ts → request-queue.d.ts} +127 -159
  76. package/storages/request-queue.js +871 -0
  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 +270 -0
  82. package/storages/transaction.js +296 -0
  83. package/storages/utils.d.ts +59 -11
  84. package/storages/utils.js +76 -16
  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 -285
  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 -111
  120. package/cookie_utils.js.map +0 -1
  121. package/crawlers/context_pipeline.d.ts +0 -61
  122. package/crawlers/context_pipeline.d.ts.map +0 -1
  123. package/crawlers/context_pipeline.js +0 -99
  124. package/crawlers/context_pipeline.js.map +0 -1
  125. package/crawlers/crawler_commons.d.ts +0 -191
  126. package/crawlers/crawler_commons.d.ts.map +0 -1
  127. package/crawlers/crawler_commons.js +0 -108
  128. package/crawlers/crawler_commons.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 -60
  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 -55
  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/internals/types.d.ts +0 -8
  146. package/crawlers/internals/types.d.ts.map +0 -1
  147. package/crawlers/internals/types.js +0 -2
  148. package/crawlers/internals/types.js.map +0 -1
  149. package/crawlers/statistics.d.ts +0 -213
  150. package/crawlers/statistics.d.ts.map +0 -1
  151. package/crawlers/statistics.js +0 -349
  152. package/crawlers/statistics.js.map +0 -1
  153. package/enqueue_links/enqueue_links.d.ts +0 -254
  154. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  155. package/enqueue_links/enqueue_links.js +0 -268
  156. package/enqueue_links/enqueue_links.js.map +0 -1
  157. package/enqueue_links/index.d.ts +0 -3
  158. package/enqueue_links/index.d.ts.map +0 -1
  159. package/enqueue_links/index.js +0 -3
  160. package/enqueue_links/index.js.map +0 -1
  161. package/enqueue_links/shared.d.ts +0 -84
  162. package/enqueue_links/shared.d.ts.map +0 -1
  163. package/enqueue_links/shared.js +0 -219
  164. package/enqueue_links/shared.js.map +0 -1
  165. package/errors.d.ts.map +0 -1
  166. package/errors.js.map +0 -1
  167. package/events/event_manager.d.ts +0 -52
  168. package/events/event_manager.d.ts.map +0 -1
  169. package/events/event_manager.js.map +0 -1
  170. package/events/index.d.ts.map +0 -1
  171. package/events/index.js.map +0 -1
  172. package/events/local_event_manager.d.ts +0 -27
  173. package/events/local_event_manager.d.ts.map +0 -1
  174. package/events/local_event_manager.js +0 -75
  175. package/events/local_event_manager.js.map +0 -1
  176. package/index.d.ts.map +0 -1
  177. package/index.js.map +0 -1
  178. package/log.d.ts.map +0 -1
  179. package/log.js.map +0 -1
  180. package/proxy_configuration.d.ts +0 -169
  181. package/proxy_configuration.d.ts.map +0 -1
  182. package/proxy_configuration.js +0 -247
  183. package/proxy_configuration.js.map +0 -1
  184. package/recoverable_state.d.ts +0 -123
  185. package/recoverable_state.d.ts.map +0 -1
  186. package/recoverable_state.js +0 -140
  187. package/recoverable_state.js.map +0 -1
  188. package/request.d.ts.map +0 -1
  189. package/request.js.map +0 -1
  190. package/router.d.ts +0 -134
  191. package/router.d.ts.map +0 -1
  192. package/router.js +0 -164
  193. package/router.js.map +0 -1
  194. package/serialization.d.ts.map +0 -1
  195. package/serialization.js.map +0 -1
  196. package/session_pool/consts.d.ts +0 -4
  197. package/session_pool/consts.d.ts.map +0 -1
  198. package/session_pool/consts.js +0 -4
  199. package/session_pool/consts.js.map +0 -1
  200. package/session_pool/errors.d.ts +0 -8
  201. package/session_pool/errors.d.ts.map +0 -1
  202. package/session_pool/errors.js +0 -12
  203. package/session_pool/errors.js.map +0 -1
  204. package/session_pool/events.d.ts +0 -3
  205. package/session_pool/events.d.ts.map +0 -1
  206. package/session_pool/events.js +0 -3
  207. package/session_pool/events.js.map +0 -1
  208. package/session_pool/index.d.ts +0 -6
  209. package/session_pool/index.d.ts.map +0 -1
  210. package/session_pool/index.js +0 -6
  211. package/session_pool/index.js.map +0 -1
  212. package/session_pool/session.d.ts +0 -186
  213. package/session_pool/session.d.ts.map +0 -1
  214. package/session_pool/session.js +0 -278
  215. package/session_pool/session.js.map +0 -1
  216. package/session_pool/session_pool.d.ts +0 -258
  217. package/session_pool/session_pool.d.ts.map +0 -1
  218. package/session_pool/session_pool.js +0 -387
  219. package/session_pool/session_pool.js.map +0 -1
  220. package/storages/access_checking.d.ts +0 -13
  221. package/storages/access_checking.d.ts.map +0 -1
  222. package/storages/access_checking.js +0 -14
  223. package/storages/access_checking.js.map +0 -1
  224. package/storages/dataset.d.ts.map +0 -1
  225. package/storages/dataset.js.map +0 -1
  226. package/storages/index.d.ts.map +0 -1
  227. package/storages/index.js.map +0 -1
  228. package/storages/key_value_store.d.ts.map +0 -1
  229. package/storages/key_value_store.js +0 -512
  230. package/storages/key_value_store.js.map +0 -1
  231. package/storages/request_list.d.ts.map +0 -1
  232. package/storages/request_list.js.map +0 -1
  233. package/storages/request_list_adapter.d.ts +0 -58
  234. package/storages/request_list_adapter.d.ts.map +0 -1
  235. package/storages/request_list_adapter.js +0 -81
  236. package/storages/request_list_adapter.js.map +0 -1
  237. package/storages/request_manager_tandem.d.ts +0 -68
  238. package/storages/request_manager_tandem.d.ts.map +0 -1
  239. package/storages/request_manager_tandem.js +0 -124
  240. package/storages/request_manager_tandem.js.map +0 -1
  241. package/storages/request_provider.d.ts.map +0 -1
  242. package/storages/request_provider.js +0 -591
  243. package/storages/request_provider.js.map +0 -1
  244. package/storages/request_queue.d.ts +0 -128
  245. package/storages/request_queue.d.ts.map +0 -1
  246. package/storages/request_queue.js +0 -320
  247. package/storages/request_queue.js.map +0 -1
  248. package/storages/request_queue_v2.d.ts +0 -87
  249. package/storages/request_queue_v2.d.ts.map +0 -1
  250. package/storages/request_queue_v2.js +0 -438
  251. package/storages/request_queue_v2.js.map +0 -1
  252. package/storages/sitemap_request_list.d.ts +0 -250
  253. package/storages/sitemap_request_list.d.ts.map +0 -1
  254. package/storages/sitemap_request_list.js +0 -431
  255. package/storages/sitemap_request_list.js.map +0 -1
  256. package/storages/storage_manager.d.ts +0 -62
  257. package/storages/storage_manager.d.ts.map +0 -1
  258. package/storages/storage_manager.js +0 -105
  259. package/storages/storage_manager.js.map +0 -1
  260. package/storages/utils.d.ts.map +0 -1
  261. package/storages/utils.js.map +0 -1
  262. package/typedefs.d.ts.map +0 -1
  263. package/typedefs.js.map +0 -1
  264. package/validators.d.ts.map +0 -1
  265. package/validators.js.map +0 -1
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@crawlee/core",
3
- "version": "4.0.0-beta.27",
3
+ "version": "4.0.0-beta.271",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
- "node": ">=22.0.0"
6
+ "node": ">=22.13.0"
7
7
  },
8
8
  "type": "module",
9
9
  "exports": {
10
10
  ".": "./index.js",
11
+ "./internal": "./internal.js",
11
12
  "./package.json": "./package.json"
12
13
  },
13
14
  "keywords": [
@@ -38,7 +39,7 @@
38
39
  },
39
40
  "homepage": "https://crawlee.dev",
40
41
  "scripts": {
41
- "build": "yarn clean && yarn compile && yarn copy",
42
+ "build": "pnpm clean && pnpm compile && pnpm copy",
42
43
  "clean": "rimraf ./dist",
43
44
  "compile": "tsc -p tsconfig.build.json",
44
45
  "copy": "tsx ../../scripts/copy.ts"
@@ -47,27 +48,26 @@
47
48
  "access": "public"
48
49
  },
49
50
  "dependencies": {
50
- "@apify/consts": "^2.41.0",
51
- "@apify/datastructures": "^2.0.3",
52
- "@apify/log": "^2.5.18",
53
- "@apify/pseudo_url": "^2.0.59",
54
- "@apify/timeout": "^0.3.2",
55
- "@apify/utilities": "^2.15.5",
56
- "@crawlee/memory-storage": "4.0.0-beta.27",
57
- "@crawlee/types": "4.0.0-beta.27",
58
- "@crawlee/utils": "4.0.0-beta.27",
51
+ "@apify/consts": "^3.0.1",
52
+ "@apify/datastructures": "^3.0.1",
53
+ "@apify/log": "^3.0.1",
54
+ "@apify/timeout": "^1.0.1",
55
+ "@apify/utilities": "^3.1.0",
56
+ "@crawlee/fs-storage": "4.0.0-beta.271",
57
+ "@crawlee/http-client": "4.0.0-beta.271",
58
+ "@crawlee/types": "4.0.0-beta.271",
59
+ "@crawlee/utils": "4.0.0-beta.271",
59
60
  "@sapphire/async-queue": "^1.5.5",
60
- "@vladfrangu/async_event_emitter": "^2.4.6",
61
- "csv-stringify": "^6.5.2",
62
- "fs-extra": "^11.3.0",
61
+ "@standard-schema/spec": "^1.1.0",
62
+ "@vladfrangu/async_event_emitter": "^2.4.7",
63
+ "content-type": "^3.1.1",
64
+ "csv-stringify": "^6.9.0",
63
65
  "json5": "^2.2.3",
64
- "minimatch": "^10.0.1",
65
- "ow": "^2.0.0",
66
- "stream-json": "^1.9.1",
67
- "tldts": "^7.0.6",
68
- "tough-cookie": "^6.0.0",
69
- "tslib": "^2.8.1",
70
- "type-fest": "^4.41.0"
66
+ "mime-types": "^3.0.2",
67
+ "stream-json": "^3.8.0",
68
+ "tslib": "^2.9.1",
69
+ "type-fest": "^4.41.0",
70
+ "zod": "^4.6.7"
71
71
  },
72
72
  "lerna": {
73
73
  "command": {
@@ -76,5 +76,5 @@
76
76
  }
77
77
  }
78
78
  },
79
- "gitHead": "9d140cc3d54fd41b95cac5aec50eb0767a7480f7"
79
+ "gitHead": "49e67f1babcf06460323acae1039eb432fc43a67"
80
80
  }
@@ -0,0 +1,118 @@
1
+ import type { ProxyInfo } from '@crawlee/types';
2
+ export interface ProxyConfigurationFunction {
3
+ (): string | null | Promise<string | null>;
4
+ }
5
+ export interface ProxyConfigurationOptions {
6
+ /**
7
+ * An array of custom proxy URLs to be rotated.
8
+ * Custom proxies are not compatible with Apify Proxy and an attempt to use both
9
+ * configuration options will cause an error to be thrown on initialize.
10
+ */
11
+ proxyUrls?: (string | null)[];
12
+ /**
13
+ * Custom function that allows you to generate the new proxy URL dynamically.
14
+ * Can return either stringified proxy URL or `null` if the proxy should not be used. Can be asynchronous.
15
+ *
16
+ * This function is used to generate the URL when {@link ProxyConfiguration.newUrl} or {@link ProxyConfiguration.newProxyInfo} is called.
17
+ */
18
+ newUrlFunction?: ProxyConfigurationFunction;
19
+ /**
20
+ * When truthy, the constructor throws unless one of `proxyUrls` / `newUrlFunction` was given. Falsy by
21
+ * default, so a bare `ProxyConfiguration` can be constructed. Set by the Apify SDK, which builds the options
22
+ * object itself; declared here only so that it stays type-checkable.
23
+ * @internal
24
+ */
25
+ validateRequired?: boolean;
26
+ }
27
+ /**
28
+ * Minimal contract that any object passed to a crawler as its `proxyConfiguration`
29
+ * option must satisfy.
30
+ *
31
+ * Implement this interface to plug a custom proxy-provisioning strategy into any Crawlee
32
+ * crawler — for example a remote proxy service or a thin wrapper around the built-in
33
+ * `ProxyConfiguration` with different rotation rules. *
34
+ *
35
+ * @category Scaling
36
+ */
37
+ export interface IProxyConfiguration {
38
+ /**
39
+ * Creates a new {@link ProxyInfo} object describing the proxy to use.
40
+ * Returns `undefined` when no proxy should be used.
41
+ *
42
+ * @param proxyInfo A previously created `ProxyInfo`, e.g. one restored with a persisted session. Implementations
43
+ * should return an equivalent `ProxyInfo` that is usable in the current environment, or the argument itself when
44
+ * there is nothing to refresh.
45
+ */
46
+ newProxyInfo(proxyInfo?: ProxyInfo): Promise<ProxyInfo | undefined>;
47
+ }
48
+ /**
49
+ * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
50
+ * your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
51
+ * them to use the selected proxies for all connections. You can get information about the currently used proxy by inspecting
52
+ * the {@link ProxyInfo} property in your crawler's page function. There, you can inspect the proxy's URL and other attributes.
53
+ *
54
+ * If you want to use your own proxies, use the {@link ProxyConfigurationOptions.proxyUrls} option. Your list of proxy URLs will
55
+ * be rotated by the configuration if this option is provided.
56
+ *
57
+ * **Example usage:**
58
+ *
59
+ * ```javascript
60
+ *
61
+ * const proxyConfiguration = new ProxyConfiguration({
62
+ * proxyUrls: ['...', '...'],
63
+ * });
64
+ *
65
+ * const crawler = new CheerioCrawler({
66
+ * // ...
67
+ * proxyConfiguration,
68
+ * requestHandler({ proxyInfo }) {
69
+ * const usedProxyUrl = proxyInfo.url; // Getting the proxy URL
70
+ * }
71
+ * })
72
+ *
73
+ * ```
74
+ * @category Scaling
75
+ */
76
+ export declare class ProxyConfiguration implements IProxyConfiguration {
77
+ #private;
78
+ readonly isManInTheMiddle = false;
79
+ /**
80
+ * Creates a {@link ProxyConfiguration} instance based on the provided options. Proxy servers are used to prevent target websites from
81
+ * blocking your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
82
+ * them to use the selected proxies for all connections.
83
+ *
84
+ * ```javascript
85
+ * const proxyConfiguration = new ProxyConfiguration({
86
+ * proxyUrls: ['http://user:pass@proxy-1.com', 'http://user:pass@proxy-2.com'],
87
+ * });
88
+ *
89
+ * const crawler = new CheerioCrawler({
90
+ * // ...
91
+ * proxyConfiguration,
92
+ * requestHandler({ proxyInfo }) {
93
+ * const usedProxyUrl = proxyInfo.url; // Getting the proxy URL
94
+ * }
95
+ * })
96
+ *
97
+ * ```
98
+ */
99
+ constructor(options?: ProxyConfigurationOptions);
100
+ /**
101
+ * This function creates a new {@link ProxyInfo} info object.
102
+ * It is used by CheerioCrawler and PuppeteerCrawler to generate proxy URLs and also to allow the user to inspect
103
+ * the currently used proxy via the requestHandler parameter `proxyInfo`.
104
+ * Use it if you want to work with a rich representation of a proxy URL.
105
+ * If you need the URL string only, use {@link ProxyConfiguration.newUrl}.
106
+ *
107
+ * @param proxyInfo A previously created `ProxyInfo`, returned unchanged.
108
+ * @return Represents information about used proxy and its configuration.
109
+ */
110
+ newProxyInfo(proxyInfo?: ProxyInfo): Promise<ProxyInfo | undefined>;
111
+ /**
112
+ * Returns a new proxy URL based on provided configuration options.
113
+ *
114
+ * @return A string with a proxy URL, including authentication credentials and port number.
115
+ * For example, `http://bob:password123@proxy.example.com:8000`
116
+ */
117
+ newUrl(): Promise<string | undefined>;
118
+ }
@@ -0,0 +1,141 @@
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
+ });
10
+ /**
11
+ * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
12
+ * your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
13
+ * them to use the selected proxies for all connections. You can get information about the currently used proxy by inspecting
14
+ * the {@link ProxyInfo} property in your crawler's page function. There, you can inspect the proxy's URL and other attributes.
15
+ *
16
+ * If you want to use your own proxies, use the {@link ProxyConfigurationOptions.proxyUrls} option. Your list of proxy URLs will
17
+ * be rotated by the configuration if this option is provided.
18
+ *
19
+ * **Example usage:**
20
+ *
21
+ * ```javascript
22
+ *
23
+ * const proxyConfiguration = new ProxyConfiguration({
24
+ * proxyUrls: ['...', '...'],
25
+ * });
26
+ *
27
+ * const crawler = new CheerioCrawler({
28
+ * // ...
29
+ * proxyConfiguration,
30
+ * requestHandler({ proxyInfo }) {
31
+ * const usedProxyUrl = proxyInfo.url; // Getting the proxy URL
32
+ * }
33
+ * })
34
+ *
35
+ * ```
36
+ * @category Scaling
37
+ */
38
+ export class ProxyConfiguration {
39
+ isManInTheMiddle = false;
40
+ #nextCustomUrlIndex = 0;
41
+ #proxyUrls;
42
+ #newUrlFunction;
43
+ /**
44
+ * Creates a {@link ProxyConfiguration} instance based on the provided options. Proxy servers are used to prevent target websites from
45
+ * blocking your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
46
+ * them to use the selected proxies for all connections.
47
+ *
48
+ * ```javascript
49
+ * const proxyConfiguration = new ProxyConfiguration({
50
+ * proxyUrls: ['http://user:pass@proxy-1.com', 'http://user:pass@proxy-2.com'],
51
+ * });
52
+ *
53
+ * const crawler = new CheerioCrawler({
54
+ * // ...
55
+ * proxyConfiguration,
56
+ * requestHandler({ proxyInfo }) {
57
+ * const usedProxyUrl = proxyInfo.url; // Getting the proxy URL
58
+ * }
59
+ * })
60
+ *
61
+ * ```
62
+ */
63
+ constructor(options = {}) {
64
+ // `validateRequired` is destructured off before the strict-object parse on purpose: the Apify SDK passes it
65
+ // through a computed key (`['validateRequired' as string]: false`), and leaving it in `rest` would make
66
+ // `Actor.createProxyConfiguration()` fail the `z.strictObject` check with a `ZodError`.
67
+ const { validateRequired, ...rest } = options;
68
+ if ('tieredProxyUrls' in rest) {
69
+ throw new Error('The `tieredProxyUrls` option has been removed in Crawlee v4. ' +
70
+ 'See the v4 upgrading guide for the recommended migration to named sessions.');
71
+ }
72
+ const { proxyUrls, newUrlFunction } = parseArgument(rest, proxyConfigurationOptionsSchema);
73
+ if (proxyUrls && newUrlFunction)
74
+ this.#throwCannotCombineCustomMethods();
75
+ if (!proxyUrls && !newUrlFunction && validateRequired)
76
+ this.#throwNoOptionsProvided();
77
+ this.#proxyUrls = proxyUrls;
78
+ this.#newUrlFunction = newUrlFunction;
79
+ }
80
+ /**
81
+ * This function creates a new {@link ProxyInfo} info object.
82
+ * It is used by CheerioCrawler and PuppeteerCrawler to generate proxy URLs and also to allow the user to inspect
83
+ * the currently used proxy via the requestHandler parameter `proxyInfo`.
84
+ * Use it if you want to work with a rich representation of a proxy URL.
85
+ * If you need the URL string only, use {@link ProxyConfiguration.newUrl}.
86
+ *
87
+ * @param proxyInfo A previously created `ProxyInfo`, returned unchanged.
88
+ * @return Represents information about used proxy and its configuration.
89
+ */
90
+ async newProxyInfo(proxyInfo) {
91
+ if (proxyInfo)
92
+ return proxyInfo;
93
+ const url = await this.newUrl();
94
+ if (!url)
95
+ return undefined;
96
+ const { username, password, port, hostname } = new URL(url);
97
+ return {
98
+ url,
99
+ username: decodeURIComponent(username),
100
+ password: decodeURIComponent(password),
101
+ hostname,
102
+ port: port,
103
+ };
104
+ }
105
+ /**
106
+ * Returns a new proxy URL based on provided configuration options.
107
+ *
108
+ * @return A string with a proxy URL, including authentication credentials and port number.
109
+ * For example, `http://bob:password123@proxy.example.com:8000`
110
+ */
111
+ async newUrl() {
112
+ if (this.#newUrlFunction) {
113
+ return (await this.#callNewUrlFunction()) ?? undefined;
114
+ }
115
+ return this.#handleProxyUrlsList() ?? undefined;
116
+ }
117
+ #handleProxyUrlsList() {
118
+ return this.#proxyUrls[this.#nextCustomUrlIndex++ % this.#proxyUrls.length];
119
+ }
120
+ /**
121
+ * Calls the custom newUrlFunction and checks format of its return value
122
+ */
123
+ async #callNewUrlFunction() {
124
+ const proxyUrl = await this.#newUrlFunction();
125
+ try {
126
+ if (proxyUrl) {
127
+ new URL(proxyUrl); // eslint-disable-line no-new
128
+ }
129
+ return proxyUrl;
130
+ }
131
+ catch (err) {
132
+ throw new Error(`The provided newUrlFunction did not return a valid URL.\nCause: ${err.message}`);
133
+ }
134
+ }
135
+ #throwCannotCombineCustomMethods() {
136
+ throw new Error('Cannot combine custom proxies "options.proxyUrls" with custom generating function "options.newUrlFunction".');
137
+ }
138
+ #throwNoOptionsProvided() {
139
+ throw new Error('One of "options.proxyUrls" or "options.newUrlFunction" needs to be provided.');
140
+ }
141
+ }
@@ -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
+ }