@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlee/core",
3
- "version": "4.0.0-beta.2",
3
+ "version": "4.0.0-beta.200",
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
6
  "node": ">=22.0.0"
@@ -8,6 +8,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,28 +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.2",
57
- "@crawlee/types": "4.0.0-beta.2",
58
- "@crawlee/utils": "4.0.0-beta.2",
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.0.1",
56
+ "@crawlee/fs-storage": "4.0.0-beta.200",
57
+ "@crawlee/http-client": "4.0.0-beta.200",
58
+ "@crawlee/types": "4.0.0-beta.200",
59
+ "@crawlee/utils": "4.0.0-beta.200",
59
60
  "@sapphire/async-queue": "^1.5.5",
61
+ "@standard-schema/spec": "^1.0.0",
60
62
  "@vladfrangu/async_event_emitter": "^2.4.6",
63
+ "content-type": "^1.0.5",
61
64
  "csv-stringify": "^6.5.2",
62
- "fs-extra": "^11.3.0",
63
- "got-scraping": "^4.1.1",
64
65
  "json5": "^2.2.3",
65
- "minimatch": "^10.0.1",
66
- "ow": "^2.0.0",
67
- "stream-json": "^1.9.1",
68
- "tldts": "^7.0.6",
69
- "tough-cookie": "^5.1.2",
66
+ "mime-types": "^3.0.1",
67
+ "stream-json": "^3.7.0",
70
68
  "tslib": "^2.8.1",
71
- "type-fest": "^4.41.0"
69
+ "type-fest": "^4.41.0",
70
+ "zod": "^4.5.4"
72
71
  },
73
72
  "lerna": {
74
73
  "command": {
@@ -77,5 +76,5 @@
77
76
  }
78
77
  }
79
78
  },
80
- "gitHead": "0a8cbc26ed71ee063e03766cdbd9b40acd7950e6"
79
+ "gitHead": "471663956b78edb995e824dd906776a28cc04535"
81
80
  }
@@ -1,8 +1,6 @@
1
- import type { Request } from './request.js';
1
+ import type { ProxyInfo } from '@crawlee/types';
2
2
  export interface ProxyConfigurationFunction {
3
- (sessionId: string | number, options?: {
4
- request?: Request;
5
- }): string | null | Promise<string | null>;
3
+ (): string | null | Promise<string | null>;
6
4
  }
7
5
  export interface ProxyConfigurationOptions {
8
6
  /**
@@ -10,120 +8,38 @@ export interface ProxyConfigurationOptions {
10
8
  * Custom proxies are not compatible with Apify Proxy and an attempt to use both
11
9
  * configuration options will cause an error to be thrown on initialize.
12
10
  */
13
- proxyUrls?: string[];
11
+ proxyUrls?: (string | null)[];
14
12
  /**
15
- * Custom function that allows you to generate the new proxy URL dynamically. It gets the `sessionId` as a parameter and an optional parameter with the `Request` object when applicable.
13
+ * Custom function that allows you to generate the new proxy URL dynamically.
16
14
  * Can return either stringified proxy URL or `null` if the proxy should not be used. Can be asynchronous.
17
15
  *
18
16
  * This function is used to generate the URL when {@link ProxyConfiguration.newUrl} or {@link ProxyConfiguration.newProxyInfo} is called.
19
17
  */
20
18
  newUrlFunction?: ProxyConfigurationFunction;
21
19
  /**
22
- * An array of custom proxy URLs to be rotated stratified in tiers.
23
- * This is a more advanced version of `proxyUrls` that allows you to define a hierarchy of proxy URLs
24
- * If everything goes well, all the requests will be sent through the first proxy URL in the list.
25
- * Whenever the crawler encounters a problem with the current proxy on the given domain, it will switch to the higher tier for this domain.
26
- * The crawler probes lower-level proxies at intervals to check if it can make the tier downshift.
27
- *
28
- * This feature is useful when you have a set of proxies with different performance characteristics (speed, price, antibot performance etc.) and you want to use the best one for each domain.
29
- *
30
- * Use `null` as a proxy URL to disable the proxy for the given tier.
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
31
24
  */
32
- tieredProxyUrls?: (string | null)[][];
33
- }
34
- export interface TieredProxy {
35
- proxyUrl: string | null;
36
- proxyTier?: number;
25
+ validateRequired?: boolean;
37
26
  }
38
27
  /**
39
- * The main purpose of the ProxyInfo object is to provide information
40
- * about the current proxy connection used by the crawler for the request.
41
- * Outside of crawlers, you can get this object by calling {@link ProxyConfiguration.newProxyInfo}.
28
+ * Minimal contract that any object passed to a crawler as its `proxyConfiguration`
29
+ * option must satisfy.
42
30
  *
43
- * **Example usage:**
44
- *
45
- * ```javascript
46
- * const proxyConfiguration = new ProxyConfiguration({
47
- * proxyUrls: ['...', '...'] // List of Proxy URLs to rotate
48
- * });
49
- *
50
- * // Getting proxyInfo object by calling class method directly
51
- * const proxyInfo = await proxyConfiguration.newProxyInfo();
52
- *
53
- * // In crawler
54
- * const crawler = new CheerioCrawler({
55
- * // ...
56
- * proxyConfiguration,
57
- * requestHandler({ proxyInfo }) {
58
- * // Getting used proxy URL
59
- * const proxyUrl = proxyInfo.url;
60
- *
61
- * // Getting ID of used Session
62
- * const sessionIdentifier = proxyInfo.sessionId;
63
- * }
64
- * })
65
- *
66
- * ```
67
- */
68
- export interface ProxyInfo {
69
- /**
70
- * The identifier of used {@link Session}, if used.
71
- */
72
- sessionId?: string;
73
- /**
74
- * The URL of the proxy.
75
- */
76
- url: string;
77
- /**
78
- * Username for the proxy.
79
- */
80
- username?: string;
81
- /**
82
- * User's password for the proxy.
83
- */
84
- password: string;
85
- /**
86
- * Hostname of your proxy.
87
- */
88
- hostname: string;
89
- /**
90
- * Proxy port.
91
- */
92
- port: number | string;
93
- /**
94
- * Proxy tier for the current proxy, if applicable (only for `tieredProxyUrls`).
95
- */
96
- proxyTier?: number;
97
- }
98
- interface TieredProxyOptions {
99
- request?: Request;
100
- proxyTier?: number;
101
- }
102
- /**
103
- * Internal class for tracking the proxy tier history for a specific domain.
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. *
104
34
  *
105
- * Predicts the best proxy tier for the next request based on the error history for different proxy tiers.
35
+ * @category Scaling
106
36
  */
107
- declare class ProxyTierTracker {
108
- private histogram;
109
- private currentTier;
110
- constructor(tieredProxyUrls: (string | null)[][]);
37
+ export interface IProxyConfiguration {
111
38
  /**
112
- * Processes a single step of the algorithm and updates the current tier prediction based on the error history.
39
+ * Creates a new {@link ProxyInfo} object describing the proxy to use.
40
+ * Returns `undefined` when no proxy should be used.
113
41
  */
114
- private processStep;
115
- /**
116
- * Increases the error score for the given proxy tier. This raises the chance of picking a different proxy tier for the subsequent requests.
117
- *
118
- * 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).
119
- * @param tier The proxy tier to mark as problematic.
120
- */
121
- addError(tier: number): void;
122
- /**
123
- * Returns the best proxy tier for the next request based on the error history for different proxy tiers.
124
- * @returns The proxy tier prediction
125
- */
126
- predictTier(): number;
42
+ newProxyInfo(): Promise<ProxyInfo | undefined>;
127
43
  }
128
44
  /**
129
45
  * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
@@ -153,16 +69,9 @@ declare class ProxyTierTracker {
153
69
  * ```
154
70
  * @category Scaling
155
71
  */
156
- export declare class ProxyConfiguration {
157
- isManInTheMiddle: boolean;
158
- protected nextCustomUrlIndex: number;
159
- protected proxyUrls?: string[];
160
- protected tieredProxyUrls?: (string | null)[][];
161
- protected usedProxyUrls: Map<string, string>;
162
- protected newUrlFunction?: ProxyConfigurationFunction;
163
- // @ts-ignore optional peer dependency or compatibility with es2022
164
- protected log: import("@apify/log").Log;
165
- protected domainTiers: Map<string, ProxyTierTracker>;
72
+ export declare class ProxyConfiguration implements IProxyConfiguration {
73
+ #private;
74
+ readonly isManInTheMiddle = false;
166
75
  /**
167
76
  * Creates a {@link ProxyConfiguration} instance based on the provided options. Proxy servers are used to prevent target websites from
168
77
  * blocking your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -190,57 +99,22 @@ export declare class ProxyConfiguration {
190
99
  * the currently used proxy via the requestHandler parameter `proxyInfo`.
191
100
  * Use it if you want to work with a rich representation of a proxy URL.
192
101
  * If you need the URL string only, use {@link ProxyConfiguration.newUrl}.
193
- * @param [sessionId]
194
- * Represents the identifier of user {@link Session} that can be managed by the {@link SessionPool} or
195
- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.
196
- * When the provided sessionId is a number, it's converted to a string. Property sessionId of
197
- * {@link ProxyInfo} is always returned as a type string.
198
102
  *
199
- * All the HTTP requests going through the proxy with the same session identifier
200
- * will use the same target proxy server (i.e. the same IP address).
201
- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.
202
103
  * @return Represents information about used proxy and its configuration.
203
104
  */
204
- newProxyInfo(sessionId?: string | number, options?: TieredProxyOptions): Promise<ProxyInfo | undefined>;
205
- /**
206
- * Given a session identifier and a request / proxy tier, this function returns a new proxy URL based on the provided configuration options.
207
- * @param _sessionId Session identifier
208
- * @param options Options for the tiered proxy rotation
209
- * @returns An object with the proxy URL and the proxy tier used.
210
- */
211
- protected _handleTieredUrl(_sessionId: string, options?: TieredProxyOptions): TieredProxy;
212
- /**
213
- * Given a `Request` object, this function returns the tier of the proxy that should be used for the request.
214
- *
215
- * This returns `null` if `tieredProxyUrls` option is not set.
216
- */
217
- protected predictProxyTier(request: Request): number | null;
105
+ newProxyInfo(): Promise<ProxyInfo | undefined>;
218
106
  /**
219
- * Returns a new proxy URL based on provided configuration options and the `sessionId` parameter.
220
- * @param [sessionId]
221
- * Represents the identifier of user {@link Session} that can be managed by the {@link SessionPool} or
222
- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.
223
- * When the provided sessionId is a number, it's converted to a string.
107
+ * Returns a new proxy URL based on provided configuration options.
224
108
  *
225
- * All the HTTP requests going through the proxy with the same session identifier
226
- * will use the same target proxy server (i.e. the same IP address).
227
- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.
228
109
  * @return A string with a proxy URL, including authentication credentials and port number.
229
110
  * For example, `http://bob:password123@proxy.example.com:8000`
230
111
  */
231
- newUrl(sessionId?: string | number, options?: TieredProxyOptions): Promise<string | undefined>;
232
- /**
233
- * Handles custom url rotation with session
234
- */
235
- protected _handleCustomUrl(sessionId?: string): string;
112
+ newUrl(): Promise<string | undefined>;
113
+ private handleProxyUrlsList;
236
114
  /**
237
115
  * Calls the custom newUrlFunction and checks format of its return value
238
116
  */
239
- protected _callNewUrlFunction(sessionId?: string, options?: {
240
- request?: Request;
241
- }): Promise<string | null>;
242
- protected _throwCannotCombineCustomMethods(): never;
243
- protected _throwNoOptionsProvided(): never;
117
+ private callNewUrlFunction;
118
+ private throwCannotCombineCustomMethods;
119
+ private throwNoOptionsProvided;
244
120
  }
245
- export {};
246
- //# sourceMappingURL=proxy_configuration.d.ts.map
@@ -1,55 +1,12 @@
1
- import ow from 'ow';
2
- import log from '@apify/log';
3
- import { cryptoRandomObjectId } from '@apify/utilities';
4
- /**
5
- * Internal class for tracking the proxy tier history for a specific domain.
6
- *
7
- * Predicts the best proxy tier for the next request based on the error history for different proxy tiers.
8
- */
9
- class ProxyTierTracker {
10
- histogram;
11
- currentTier;
12
- constructor(tieredProxyUrls) {
13
- this.histogram = tieredProxyUrls.map(() => 0);
14
- this.currentTier = 0;
15
- }
16
- /**
17
- * Processes a single step of the algorithm and updates the current tier prediction based on the error history.
18
- */
19
- processStep() {
20
- this.histogram.forEach((x, i) => {
21
- if (this.currentTier === i)
22
- return;
23
- if (x > 0)
24
- this.histogram[i]--;
25
- });
26
- const left = this.currentTier > 0 ? this.histogram[this.currentTier - 1] : Infinity;
27
- const right = this.currentTier < this.histogram.length - 1 ? this.histogram[this.currentTier + 1] : Infinity;
28
- if (this.histogram[this.currentTier] > Math.min(left, right)) {
29
- this.currentTier = left <= right ? this.currentTier - 1 : this.currentTier + 1;
30
- }
31
- else if (this.histogram[this.currentTier] === left) {
32
- this.currentTier--;
33
- }
34
- }
35
- /**
36
- * Increases the error score for the given proxy tier. This raises the chance of picking a different proxy tier for the subsequent requests.
37
- *
38
- * 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).
39
- * @param tier The proxy tier to mark as problematic.
40
- */
41
- addError(tier) {
42
- this.histogram[tier] += 10;
43
- }
44
- /**
45
- * Returns the best proxy tier for the next request based on the error history for different proxy tiers.
46
- * @returns The proxy tier prediction
47
- */
48
- predictTier() {
49
- this.processStep();
50
- return this.currentTier;
51
- }
52
- }
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
+ });
53
10
  /**
54
11
  * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
55
12
  * your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -80,13 +37,9 @@ class ProxyTierTracker {
80
37
  */
81
38
  export class ProxyConfiguration {
82
39
  isManInTheMiddle = false;
83
- nextCustomUrlIndex = 0;
84
- proxyUrls;
85
- tieredProxyUrls;
86
- usedProxyUrls = new Map();
87
- newUrlFunction;
88
- log = log.child({ prefix: 'ProxyConfiguration' });
89
- domainTiers = new Map();
40
+ #nextCustomUrlIndex = 0;
41
+ #proxyUrls;
42
+ #newUrlFunction;
90
43
  /**
91
44
  * Creates a {@link ProxyConfiguration} instance based on the provided options. Proxy servers are used to prevent target websites from
92
45
  * blocking your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -108,20 +61,21 @@ export class ProxyConfiguration {
108
61
  * ```
109
62
  */
110
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`.
111
67
  const { validateRequired, ...rest } = options;
112
- ow(rest, ow.object.exactShape({
113
- proxyUrls: ow.optional.array.nonEmpty.ofType(ow.string.url),
114
- newUrlFunction: ow.optional.function,
115
- tieredProxyUrls: ow.optional.array.nonEmpty.ofType(ow.array.nonEmpty.ofType(ow.any(ow.string.url, ow.null))),
116
- }));
117
- const { proxyUrls, newUrlFunction, tieredProxyUrls } = options;
118
- if ([proxyUrls, newUrlFunction, tieredProxyUrls].filter((x) => x).length > 1)
119
- this._throwCannotCombineCustomMethods();
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();
120
75
  if (!proxyUrls && !newUrlFunction && validateRequired)
121
- this._throwNoOptionsProvided();
122
- this.proxyUrls = proxyUrls;
123
- this.newUrlFunction = newUrlFunction;
124
- this.tieredProxyUrls = tieredProxyUrls;
76
+ this.throwNoOptionsProvided();
77
+ this.#proxyUrls = proxyUrls;
78
+ this.#newUrlFunction = newUrlFunction;
125
79
  }
126
80
  /**
127
81
  * This function creates a new {@link ProxyInfo} info object.
@@ -129,140 +83,42 @@ export class ProxyConfiguration {
129
83
  * the currently used proxy via the requestHandler parameter `proxyInfo`.
130
84
  * Use it if you want to work with a rich representation of a proxy URL.
131
85
  * If you need the URL string only, use {@link ProxyConfiguration.newUrl}.
132
- * @param [sessionId]
133
- * Represents the identifier of user {@link Session} that can be managed by the {@link SessionPool} or
134
- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.
135
- * When the provided sessionId is a number, it's converted to a string. Property sessionId of
136
- * {@link ProxyInfo} is always returned as a type string.
137
86
  *
138
- * All the HTTP requests going through the proxy with the same session identifier
139
- * will use the same target proxy server (i.e. the same IP address).
140
- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.
141
87
  * @return Represents information about used proxy and its configuration.
142
88
  */
143
- async newProxyInfo(sessionId, options) {
144
- if (typeof sessionId === 'number')
145
- sessionId = `${sessionId}`;
146
- let url;
147
- let tier;
148
- if (this.tieredProxyUrls) {
149
- const { proxyUrl, proxyTier } = this._handleTieredUrl(sessionId ?? cryptoRandomObjectId(6), options);
150
- url = proxyUrl ?? undefined;
151
- tier = proxyTier;
152
- }
153
- else {
154
- url = await this.newUrl(sessionId, options);
155
- }
89
+ async newProxyInfo() {
90
+ const url = await this.newUrl();
156
91
  if (!url)
157
92
  return undefined;
158
93
  const { username, password, port, hostname } = new URL(url);
159
94
  return {
160
- sessionId,
161
95
  url,
162
96
  username: decodeURIComponent(username),
163
97
  password: decodeURIComponent(password),
164
98
  hostname,
165
99
  port: port,
166
- proxyTier: tier,
167
100
  };
168
101
  }
169
102
  /**
170
- * Given a session identifier and a request / proxy tier, this function returns a new proxy URL based on the provided configuration options.
171
- * @param _sessionId Session identifier
172
- * @param options Options for the tiered proxy rotation
173
- * @returns An object with the proxy URL and the proxy tier used.
174
- */
175
- _handleTieredUrl(_sessionId, options) {
176
- if (!this.tieredProxyUrls)
177
- throw new Error('Tiered proxy URLs are not set');
178
- if (!options || (!options?.request && options?.proxyTier === undefined)) {
179
- const allProxyUrls = this.tieredProxyUrls.flat();
180
- return {
181
- proxyUrl: allProxyUrls[this.nextCustomUrlIndex++ % allProxyUrls.length],
182
- };
183
- }
184
- let tierPrediction = options.proxyTier;
185
- if (typeof tierPrediction !== 'number') {
186
- tierPrediction = this.predictProxyTier(options.request);
187
- }
188
- const proxyTier = this.tieredProxyUrls[tierPrediction];
189
- return {
190
- proxyUrl: proxyTier[this.nextCustomUrlIndex++ % proxyTier.length],
191
- proxyTier: tierPrediction,
192
- };
193
- }
194
- /**
195
- * Given a `Request` object, this function returns the tier of the proxy that should be used for the request.
196
- *
197
- * This returns `null` if `tieredProxyUrls` option is not set.
198
- */
199
- predictProxyTier(request) {
200
- if (!this.tieredProxyUrls)
201
- return null;
202
- const domain = new URL(request.url).hostname;
203
- if (!this.domainTiers.has(domain)) {
204
- this.domainTiers.set(domain, new ProxyTierTracker(this.tieredProxyUrls));
205
- }
206
- request.userData.__crawlee ??= {};
207
- const tracker = this.domainTiers.get(domain);
208
- if (typeof request.userData.__crawlee.lastProxyTier === 'number') {
209
- tracker.addError(request.userData.__crawlee.lastProxyTier);
210
- }
211
- const tierPrediction = tracker.predictTier();
212
- if (typeof request.userData.__crawlee.lastProxyTier === 'number' &&
213
- request.userData.__crawlee.lastProxyTier !== tierPrediction) {
214
- log.debug(`Changing proxy tier for domain "${domain}" from ${request.userData.__crawlee.lastProxyTier} to ${tierPrediction}.`);
215
- }
216
- request.userData.__crawlee.lastProxyTier = tierPrediction;
217
- request.userData.__crawlee.forefront = true;
218
- return tierPrediction;
219
- }
220
- /**
221
- * Returns a new proxy URL based on provided configuration options and the `sessionId` parameter.
222
- * @param [sessionId]
223
- * Represents the identifier of user {@link Session} that can be managed by the {@link SessionPool} or
224
- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.
225
- * When the provided sessionId is a number, it's converted to a string.
103
+ * Returns a new proxy URL based on provided configuration options.
226
104
  *
227
- * All the HTTP requests going through the proxy with the same session identifier
228
- * will use the same target proxy server (i.e. the same IP address).
229
- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.
230
105
  * @return A string with a proxy URL, including authentication credentials and port number.
231
106
  * For example, `http://bob:password123@proxy.example.com:8000`
232
107
  */
233
- async newUrl(sessionId, options) {
234
- if (typeof sessionId === 'number')
235
- sessionId = `${sessionId}`;
236
- if (this.newUrlFunction) {
237
- return (await this._callNewUrlFunction(sessionId, { request: options?.request })) ?? undefined;
238
- }
239
- if (this.tieredProxyUrls) {
240
- return this._handleTieredUrl(sessionId ?? cryptoRandomObjectId(6), options).proxyUrl ?? undefined;
108
+ async newUrl() {
109
+ if (this.#newUrlFunction) {
110
+ return (await this.callNewUrlFunction()) ?? undefined;
241
111
  }
242
- return this._handleCustomUrl(sessionId);
112
+ return this.handleProxyUrlsList() ?? undefined;
243
113
  }
244
- /**
245
- * Handles custom url rotation with session
246
- */
247
- _handleCustomUrl(sessionId) {
248
- let customUrlToUse;
249
- if (!sessionId) {
250
- return this.proxyUrls[this.nextCustomUrlIndex++ % this.proxyUrls.length];
251
- }
252
- if (this.usedProxyUrls.has(sessionId)) {
253
- customUrlToUse = this.usedProxyUrls.get(sessionId);
254
- }
255
- else {
256
- customUrlToUse = this.proxyUrls[this.nextCustomUrlIndex++ % this.proxyUrls.length];
257
- this.usedProxyUrls.set(sessionId, customUrlToUse);
258
- }
259
- return customUrlToUse;
114
+ handleProxyUrlsList() {
115
+ return this.#proxyUrls[this.#nextCustomUrlIndex++ % this.#proxyUrls.length];
260
116
  }
261
117
  /**
262
118
  * Calls the custom newUrlFunction and checks format of its return value
263
119
  */
264
- async _callNewUrlFunction(sessionId, options) {
265
- const proxyUrl = await this.newUrlFunction(sessionId, options);
120
+ async callNewUrlFunction() {
121
+ const proxyUrl = await this.#newUrlFunction();
266
122
  try {
267
123
  if (proxyUrl) {
268
124
  new URL(proxyUrl); // eslint-disable-line no-new
@@ -273,11 +129,10 @@ export class ProxyConfiguration {
273
129
  throw new Error(`The provided newUrlFunction did not return a valid URL.\nCause: ${err.message}`);
274
130
  }
275
131
  }
276
- _throwCannotCombineCustomMethods() {
132
+ throwCannotCombineCustomMethods() {
277
133
  throw new Error('Cannot combine custom proxies "options.proxyUrls" with custom generating function "options.newUrlFunction".');
278
134
  }
279
- _throwNoOptionsProvided() {
135
+ throwNoOptionsProvided() {
280
136
  throw new Error('One of "options.proxyUrls" or "options.newUrlFunction" needs to be provided.');
281
137
  }
282
138
  }
283
- //# sourceMappingURL=proxy_configuration.js.map