@crawlee/core 4.0.0-beta.9 → 4.0.0-beta.91

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 (263) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +66 -153
  3. package/autoscaling/autoscaled_pool.js +95 -251
  4. package/autoscaling/client_load_signal.d.ts +59 -0
  5. package/autoscaling/client_load_signal.js +73 -0
  6. package/autoscaling/concurrency_system.d.ts +283 -0
  7. package/autoscaling/concurrency_system.js +350 -0
  8. package/autoscaling/cpu_load_signal.d.ts +44 -0
  9. package/autoscaling/cpu_load_signal.js +46 -0
  10. package/autoscaling/event_loop_load_signal.d.ts +54 -0
  11. package/autoscaling/event_loop_load_signal.js +60 -0
  12. package/autoscaling/index.d.ts +6 -1
  13. package/autoscaling/index.js +6 -1
  14. package/autoscaling/load_signal.d.ts +99 -0
  15. package/autoscaling/load_signal.js +103 -0
  16. package/autoscaling/memory_load_signal.d.ts +56 -0
  17. package/autoscaling/memory_load_signal.js +106 -0
  18. package/autoscaling/snapshotter.d.ts +61 -163
  19. package/autoscaling/snapshotter.js +45 -263
  20. package/autoscaling/system_status.d.ts +63 -83
  21. package/autoscaling/system_status.js +90 -120
  22. package/configuration.d.ts +90 -223
  23. package/configuration.js +164 -222
  24. package/cookie_utils.d.ts +4 -3
  25. package/cookie_utils.js +20 -13
  26. package/crawlers/context_pipeline.d.ts +70 -0
  27. package/crawlers/context_pipeline.js +122 -0
  28. package/crawlers/crawler_commons.d.ts +76 -33
  29. package/crawlers/crawler_commons.js +15 -24
  30. package/crawlers/crawler_utils.d.ts +2 -3
  31. package/crawlers/crawler_utils.js +1 -2
  32. package/crawlers/error_snapshotter.d.ts +3 -3
  33. package/crawlers/error_snapshotter.js +2 -3
  34. package/crawlers/error_tracker.d.ts +2 -2
  35. package/crawlers/error_tracker.js +0 -1
  36. package/crawlers/index.d.ts +1 -2
  37. package/crawlers/index.js +1 -2
  38. package/crawlers/internals/types.d.ts +7 -0
  39. package/crawlers/internals/types.js +1 -0
  40. package/crawlers/statistics.d.ts +28 -23
  41. package/crawlers/statistics.js +38 -34
  42. package/debug.d.ts +36 -0
  43. package/debug.js +70 -0
  44. package/enqueue_links/enqueue_links.d.ts +44 -22
  45. package/enqueue_links/enqueue_links.js +51 -30
  46. package/enqueue_links/index.d.ts +0 -1
  47. package/enqueue_links/index.js +0 -1
  48. package/enqueue_links/shared.d.ts +25 -9
  49. package/enqueue_links/shared.js +69 -38
  50. package/errors.d.ts +53 -4
  51. package/errors.js +70 -5
  52. package/events/event_manager.d.ts +34 -8
  53. package/events/event_manager.js +8 -10
  54. package/events/index.d.ts +0 -1
  55. package/events/index.js +0 -1
  56. package/events/local_event_manager.d.ts +15 -3
  57. package/events/local_event_manager.js +37 -11
  58. package/index.d.ts +6 -3
  59. package/index.js +5 -2
  60. package/log.d.ts +82 -3
  61. package/log.js +102 -1
  62. package/memory-storage/consts.d.ts +4 -0
  63. package/memory-storage/consts.js +4 -0
  64. package/memory-storage/index.d.ts +1 -0
  65. package/memory-storage/index.js +1 -0
  66. package/memory-storage/memory-storage.d.ts +46 -0
  67. package/memory-storage/memory-storage.js +136 -0
  68. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  69. package/memory-storage/resource-clients/common/base-client.js +6 -0
  70. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  71. package/memory-storage/resource-clients/dataset.js +113 -0
  72. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  73. package/memory-storage/resource-clients/key-value-store.js +203 -0
  74. package/memory-storage/resource-clients/request-queue.d.ts +96 -0
  75. package/memory-storage/resource-clients/request-queue.js +421 -0
  76. package/memory-storage/utils.d.ts +17 -0
  77. package/memory-storage/utils.js +42 -0
  78. package/owned_or_injected.d.ts +60 -0
  79. package/owned_or_injected.js +98 -0
  80. package/package.json +12 -10
  81. package/proxy_configuration.d.ts +29 -152
  82. package/proxy_configuration.js +21 -173
  83. package/recoverable_state.d.ts +120 -0
  84. package/recoverable_state.js +143 -0
  85. package/request.d.ts +85 -15
  86. package/request.js +107 -28
  87. package/router.d.ts +144 -19
  88. package/router.js +125 -30
  89. package/serialization.d.ts +0 -1
  90. package/serialization.js +1 -2
  91. package/service_locator.d.ts +156 -0
  92. package/service_locator.js +238 -0
  93. package/session_pool/consts.d.ts +1 -2
  94. package/session_pool/consts.js +1 -2
  95. package/session_pool/errors.d.ts +0 -1
  96. package/session_pool/errors.js +0 -1
  97. package/session_pool/fingerprint.d.ts +9 -0
  98. package/session_pool/fingerprint.js +30 -0
  99. package/session_pool/index.d.ts +0 -2
  100. package/session_pool/index.js +0 -2
  101. package/session_pool/session.d.ts +37 -75
  102. package/session_pool/session.js +49 -102
  103. package/session_pool/session_pool.d.ts +85 -90
  104. package/session_pool/session_pool.js +131 -120
  105. package/storages/access_checking.d.ts +1 -2
  106. package/storages/access_checking.js +5 -2
  107. package/storages/dataset.d.ts +103 -54
  108. package/storages/dataset.js +174 -132
  109. package/storages/index.d.ts +8 -7
  110. package/storages/index.js +6 -7
  111. package/storages/key_value_store.d.ts +167 -39
  112. package/storages/key_value_store.js +274 -127
  113. package/storages/key_value_store_codec.d.ts +32 -0
  114. package/storages/key_value_store_codec.js +113 -0
  115. package/storages/request_dedup_cache.d.ts +23 -0
  116. package/storages/request_dedup_cache.js +48 -0
  117. package/storages/request_list.d.ts +54 -98
  118. package/storages/request_list.js +99 -75
  119. package/storages/request_loader.d.ts +96 -0
  120. package/storages/request_loader.js +1 -0
  121. package/storages/request_manager.d.ts +33 -0
  122. package/storages/request_manager.js +1 -0
  123. package/storages/request_manager_tandem.d.ts +106 -0
  124. package/storages/request_manager_tandem.js +197 -0
  125. package/storages/request_queue.d.ts +290 -47
  126. package/storages/request_queue.js +629 -215
  127. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +28 -24
  128. package/storages/{sitemap_request_list.js → sitemap_request_loader.js} +49 -47
  129. package/storages/storage_instance_manager.d.ts +90 -0
  130. package/storages/storage_instance_manager.js +258 -0
  131. package/storages/storage_stats.d.ts +48 -0
  132. package/storages/storage_stats.js +29 -0
  133. package/storages/utils.d.ts +54 -9
  134. package/storages/utils.js +64 -13
  135. package/system-info/cpu-info.d.ts +67 -0
  136. package/system-info/cpu-info.js +216 -0
  137. package/system-info/memory-info.d.ts +31 -0
  138. package/system-info/memory-info.js +115 -0
  139. package/system-info/ps-tree.d.ts +17 -0
  140. package/system-info/ps-tree.js +144 -0
  141. package/system-info/runtime.d.ts +14 -0
  142. package/system-info/runtime.js +80 -0
  143. package/typedefs.d.ts +0 -6
  144. package/typedefs.js +0 -1
  145. package/validators.d.ts +8 -1
  146. package/validators.js +10 -3
  147. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  148. package/autoscaling/autoscaled_pool.js.map +0 -1
  149. package/autoscaling/index.d.ts.map +0 -1
  150. package/autoscaling/index.js.map +0 -1
  151. package/autoscaling/snapshotter.d.ts.map +0 -1
  152. package/autoscaling/snapshotter.js.map +0 -1
  153. package/autoscaling/system_status.d.ts.map +0 -1
  154. package/autoscaling/system_status.js.map +0 -1
  155. package/configuration.d.ts.map +0 -1
  156. package/configuration.js.map +0 -1
  157. package/cookie_utils.d.ts.map +0 -1
  158. package/cookie_utils.js.map +0 -1
  159. package/crawlers/crawler_commons.d.ts.map +0 -1
  160. package/crawlers/crawler_commons.js.map +0 -1
  161. package/crawlers/crawler_extension.d.ts +0 -12
  162. package/crawlers/crawler_extension.d.ts.map +0 -1
  163. package/crawlers/crawler_extension.js +0 -14
  164. package/crawlers/crawler_extension.js.map +0 -1
  165. package/crawlers/crawler_utils.d.ts.map +0 -1
  166. package/crawlers/crawler_utils.js.map +0 -1
  167. package/crawlers/error_snapshotter.d.ts.map +0 -1
  168. package/crawlers/error_snapshotter.js.map +0 -1
  169. package/crawlers/error_tracker.d.ts.map +0 -1
  170. package/crawlers/error_tracker.js.map +0 -1
  171. package/crawlers/index.d.ts.map +0 -1
  172. package/crawlers/index.js.map +0 -1
  173. package/crawlers/statistics.d.ts.map +0 -1
  174. package/crawlers/statistics.js.map +0 -1
  175. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  176. package/enqueue_links/enqueue_links.js.map +0 -1
  177. package/enqueue_links/index.d.ts.map +0 -1
  178. package/enqueue_links/index.js.map +0 -1
  179. package/enqueue_links/shared.d.ts.map +0 -1
  180. package/enqueue_links/shared.js.map +0 -1
  181. package/errors.d.ts.map +0 -1
  182. package/errors.js.map +0 -1
  183. package/events/event_manager.d.ts.map +0 -1
  184. package/events/event_manager.js.map +0 -1
  185. package/events/index.d.ts.map +0 -1
  186. package/events/index.js.map +0 -1
  187. package/events/local_event_manager.d.ts.map +0 -1
  188. package/events/local_event_manager.js.map +0 -1
  189. package/http_clients/base-http-client.d.ts +0 -134
  190. package/http_clients/base-http-client.d.ts.map +0 -1
  191. package/http_clients/base-http-client.js +0 -33
  192. package/http_clients/base-http-client.js.map +0 -1
  193. package/http_clients/form-data-like.d.ts +0 -67
  194. package/http_clients/form-data-like.d.ts.map +0 -1
  195. package/http_clients/form-data-like.js +0 -5
  196. package/http_clients/form-data-like.js.map +0 -1
  197. package/http_clients/got-scraping-http-client.d.ts +0 -15
  198. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  199. package/http_clients/got-scraping-http-client.js +0 -69
  200. package/http_clients/got-scraping-http-client.js.map +0 -1
  201. package/http_clients/index.d.ts +0 -3
  202. package/http_clients/index.d.ts.map +0 -1
  203. package/http_clients/index.js +0 -3
  204. package/http_clients/index.js.map +0 -1
  205. package/index.d.ts.map +0 -1
  206. package/index.js.map +0 -1
  207. package/log.d.ts.map +0 -1
  208. package/log.js.map +0 -1
  209. package/proxy_configuration.d.ts.map +0 -1
  210. package/proxy_configuration.js.map +0 -1
  211. package/request.d.ts.map +0 -1
  212. package/request.js.map +0 -1
  213. package/router.d.ts.map +0 -1
  214. package/router.js.map +0 -1
  215. package/serialization.d.ts.map +0 -1
  216. package/serialization.js.map +0 -1
  217. package/session_pool/consts.d.ts.map +0 -1
  218. package/session_pool/consts.js.map +0 -1
  219. package/session_pool/errors.d.ts.map +0 -1
  220. package/session_pool/errors.js.map +0 -1
  221. package/session_pool/events.d.ts +0 -3
  222. package/session_pool/events.d.ts.map +0 -1
  223. package/session_pool/events.js +0 -3
  224. package/session_pool/events.js.map +0 -1
  225. package/session_pool/index.d.ts.map +0 -1
  226. package/session_pool/index.js.map +0 -1
  227. package/session_pool/session.d.ts.map +0 -1
  228. package/session_pool/session.js.map +0 -1
  229. package/session_pool/session_pool.d.ts.map +0 -1
  230. package/session_pool/session_pool.js.map +0 -1
  231. package/storages/access_checking.d.ts.map +0 -1
  232. package/storages/access_checking.js.map +0 -1
  233. package/storages/dataset.d.ts.map +0 -1
  234. package/storages/dataset.js.map +0 -1
  235. package/storages/index.d.ts.map +0 -1
  236. package/storages/index.js.map +0 -1
  237. package/storages/key_value_store.d.ts.map +0 -1
  238. package/storages/key_value_store.js.map +0 -1
  239. package/storages/request_list.d.ts.map +0 -1
  240. package/storages/request_list.js.map +0 -1
  241. package/storages/request_provider.d.ts +0 -307
  242. package/storages/request_provider.d.ts.map +0 -1
  243. package/storages/request_provider.js +0 -555
  244. package/storages/request_provider.js.map +0 -1
  245. package/storages/request_queue.d.ts.map +0 -1
  246. package/storages/request_queue.js.map +0 -1
  247. package/storages/request_queue_v2.d.ts +0 -87
  248. package/storages/request_queue_v2.d.ts.map +0 -1
  249. package/storages/request_queue_v2.js +0 -438
  250. package/storages/request_queue_v2.js.map +0 -1
  251. package/storages/sitemap_request_list.d.ts.map +0 -1
  252. package/storages/sitemap_request_list.js.map +0 -1
  253. package/storages/storage_manager.d.ts +0 -58
  254. package/storages/storage_manager.d.ts.map +0 -1
  255. package/storages/storage_manager.js +0 -105
  256. package/storages/storage_manager.js.map +0 -1
  257. package/storages/utils.d.ts.map +0 -1
  258. package/storages/utils.js.map +0 -1
  259. package/tsconfig.build.tsbuildinfo +0 -1
  260. package/typedefs.d.ts.map +0 -1
  261. package/typedefs.js.map +0 -1
  262. package/validators.d.ts.map +0 -1
  263. package/validators.js.map +0 -1
@@ -1,7 +1,8 @@
1
1
  import ow from 'ow';
2
2
  import { getDomain } from 'tldts';
3
- import log from '@apify/log';
4
- import { constructGlobObjectsFromGlobs, constructRegExpObjectsFromPseudoUrls, constructRegExpObjectsFromRegExps, createRequestOptions, createRequests, filterRequestsByPatterns, } from './shared.js';
3
+ import { Request } from '../request.js';
4
+ import { serviceLocator } from '../service_locator.js';
5
+ import { applyRequestTransform, constructGlobObjectsFromGlobs, constructRegExpObjectsFromPseudoUrls, constructRegExpObjectsFromRegExps, createRequestOptions, filterRequestOptionsByPatterns, } from './shared.js';
5
6
  /**
6
7
  * The different enqueueing strategies available.
7
8
  *
@@ -66,7 +67,7 @@ export var EnqueueStrategy;
66
67
  * ```javascript
67
68
  * await enqueueLinks({
68
69
  * urls: aListOfFoundUrls,
69
- * requestQueue,
70
+ * requestManager,
70
71
  * selector: 'a.product-detail',
71
72
  * globs: [
72
73
  * 'https://www.example.com/handbags/*',
@@ -87,11 +88,13 @@ export async function enqueueLinks(options) {
87
88
  }
88
89
  ow(options, ow.object.exactShape({
89
90
  urls: ow.array.ofType(ow.string),
90
- requestQueue: ow.object.hasKeys('fetchNextRequest', 'addRequest'),
91
+ requestManager: ow.object.hasKeys('addRequestsBatched'),
91
92
  robotsTxtFile: ow.optional.object.hasKeys('isAllowed'),
93
+ respectRobotsTxtFile: ow.optional.any(ow.boolean, ow.object.exactShape({ userAgent: ow.optional.string })),
92
94
  onSkippedRequest: ow.optional.function,
93
95
  forefront: ow.optional.boolean,
94
96
  skipNavigation: ow.optional.boolean,
97
+ sessionId: ow.optional.string,
95
98
  limit: ow.optional.number,
96
99
  selector: ow.optional.string,
97
100
  baseUrl: ow.optional.string,
@@ -105,7 +108,9 @@ export async function enqueueLinks(options) {
105
108
  strategy: ow.optional.string.oneOf(Object.values(EnqueueStrategy)),
106
109
  waitForAllRequestsToBeAdded: ow.optional.boolean,
107
110
  }));
108
- const { requestQueue, limit, urls, pseudoUrls, exclude, globs, regexps, transformRequestFunction, forefront, waitForAllRequestsToBeAdded, robotsTxtFile, onSkippedRequest, } = options;
111
+ const { requestManager, limit, urls,
112
+ // oxlint-disable-next-line typescript/no-deprecated -- still accepted for backwards compat
113
+ pseudoUrls, exclude, globs, regexps, transformRequestFunction, forefront, waitForAllRequestsToBeAdded, robotsTxtFile, onSkippedRequest, } = options;
109
114
  const urlExcludePatternObjects = [];
110
115
  const urlPatternObjects = [];
111
116
  if (exclude?.length) {
@@ -119,7 +124,7 @@ export async function enqueueLinks(options) {
119
124
  }
120
125
  }
121
126
  if (pseudoUrls?.length) {
122
- log.deprecated('`pseudoUrls` option is deprecated, use `globs` or `regexps` instead');
127
+ serviceLocator.getLogger().deprecated('`pseudoUrls` option is deprecated, use `globs` or `regexps` instead');
123
128
  urlPatternObjects.push(...constructRegExpObjectsFromPseudoUrls(pseudoUrls));
124
129
  }
125
130
  if (globs?.length) {
@@ -167,44 +172,61 @@ export async function enqueueLinks(options) {
167
172
  break;
168
173
  }
169
174
  }
175
+ async function reportSkippedRequests(skippedRequests, reason) {
176
+ if (onSkippedRequest && skippedRequests.length > 0) {
177
+ await Promise.all(skippedRequests.map((request) => {
178
+ return onSkippedRequest({
179
+ url: request.url,
180
+ reason: request.skippedReason ?? reason,
181
+ });
182
+ }));
183
+ }
184
+ }
170
185
  let requestOptions = createRequestOptions(urls, options);
171
- if (robotsTxtFile) {
186
+ if (robotsTxtFile && options.respectRobotsTxtFile !== false) {
187
+ const robotsUserAgent = typeof options.respectRobotsTxtFile === 'object' ? (options.respectRobotsTxtFile.userAgent ?? '*') : '*';
172
188
  const skippedRequests = [];
173
189
  requestOptions = requestOptions.filter((request) => {
174
- if (robotsTxtFile.isAllowed(request.url)) {
190
+ if (robotsTxtFile.isAllowed(request.url, robotsUserAgent)) {
175
191
  return true;
176
192
  }
177
193
  skippedRequests.push(request);
178
194
  return false;
179
195
  });
180
- if (onSkippedRequest && skippedRequests.length > 0) {
181
- await Promise.all(skippedRequests.map((request) => {
182
- return onSkippedRequest({ url: request.url, reason: 'robotsTxt' });
183
- }));
184
- }
196
+ await reportSkippedRequests(skippedRequests, 'robotsTxt');
185
197
  }
186
- if (transformRequestFunction) {
187
- requestOptions = requestOptions
188
- .map((request) => transformRequestFunction(request))
189
- .filter((r) => !!r);
190
- }
191
- function createFilteredRequests() {
192
- // No user provided patterns means we can skip an extra filtering step
198
+ async function createFilteredRequests() {
199
+ const skippedRequests = [];
200
+ // Step 1: Filter request options by exclude patterns, user patterns (globs/regexps), and strategy patterns.
201
+ // Pattern-level options (label, userData, method, etc.) are merged during this step.
202
+ let filteredOptions;
193
203
  if (urlPatternObjects.length === 0) {
194
- return createRequests(requestOptions, enqueueStrategyPatterns, urlExcludePatternObjects, options.strategy);
204
+ filteredOptions = filterRequestOptionsByPatterns(requestOptions, enqueueStrategyPatterns.length > 0 ? enqueueStrategyPatterns : undefined, urlExcludePatternObjects, options.strategy, (url) => skippedRequests.push(url));
195
205
  }
196
- // Generate requests based on the user patterns first
197
- const generatedRequestsFromUserFilters = createRequests(requestOptions, urlPatternObjects, urlExcludePatternObjects, options.strategy);
198
- // ...then filter them by the enqueue links strategy (making this an AND check)
199
- return filterRequestsByPatterns(generatedRequestsFromUserFilters, enqueueStrategyPatterns);
206
+ else {
207
+ // Filter by user patterns first (with exclude)
208
+ const afterUserPatterns = filterRequestOptionsByPatterns(requestOptions, urlPatternObjects, urlExcludePatternObjects, options.strategy, (url) => skippedRequests.push(url));
209
+ // ...then filter by the enqueue links strategy (making this an AND check)
210
+ filteredOptions = filterRequestOptionsByPatterns(afterUserPatterns, enqueueStrategyPatterns.length > 0 ? enqueueStrategyPatterns : undefined, [], options.strategy, (url) => skippedRequests.push(url));
211
+ }
212
+ await reportSkippedRequests(skippedRequests.map((url) => ({ url })), 'filters');
213
+ // Step 2: Apply transformRequestFunction on request options - it has the highest priority
214
+ if (transformRequestFunction) {
215
+ const skippedByTransform = [];
216
+ filteredOptions = applyRequestTransform(filteredOptions, transformRequestFunction, (r) => skippedByTransform.push(r));
217
+ await reportSkippedRequests(skippedByTransform, 'transform');
218
+ }
219
+ // Step 3: Create Request instances from the final request options
220
+ return filteredOptions.map((opts) => new Request(opts));
200
221
  }
201
- let requests = createFilteredRequests();
202
- if (limit)
203
- requests = requests.slice(0, limit);
204
- const { addedRequests } = await requestQueue.addRequestsBatched(requests, {
222
+ const { addedRequests, requestsOverLimit } = await requestManager.addRequestsBatched(await createFilteredRequests(), {
205
223
  forefront,
206
224
  waitForAllRequestsToBeAdded,
225
+ maxNewRequests: limit,
207
226
  });
227
+ if (requestsOverLimit?.length !== undefined && requestsOverLimit.length > 0) {
228
+ await reportSkippedRequests(requestsOverLimit.map((r) => ({ url: typeof r === 'string' ? r : r.url })), 'enqueueLimit');
229
+ }
208
230
  return { processedRequests: addedRequests, unprocessedRequests: [] };
209
231
  }
210
232
  /**
@@ -247,4 +269,3 @@ export function resolveBaseUrlForEnqueueLinksFiltering({ enqueueStrategy, finalR
247
269
  function ignoreHttpSchema(pattern) {
248
270
  return pattern.replace(/^(https?):\/\//, 'http{s,}://');
249
271
  }
250
- //# sourceMappingURL=enqueue_links.js.map
@@ -1,3 +1,2 @@
1
1
  export * from './enqueue_links.js';
2
2
  export * from './shared.js';
3
- //# sourceMappingURL=index.d.ts.map
@@ -1,3 +1,2 @@
1
1
  export * from './enqueue_links.js';
2
2
  export * from './shared.js';
3
- //# sourceMappingURL=index.js.map
@@ -1,5 +1,5 @@
1
+ import type { Awaitable } from '@crawlee/types';
1
2
  import type { RequestOptions } from '../request.js';
2
- import { Request } from '../request.js';
3
3
  import type { EnqueueLinksOptions } from './enqueue_links.js';
4
4
  export { tryAbsoluteURL } from '@crawlee/utils';
5
5
  export type UrlPatternObject = {
@@ -18,6 +18,11 @@ export type RegExpObject = {
18
18
  regexp: RegExp;
19
19
  } & Pick<RequestOptions, 'method' | 'payload' | 'label' | 'userData' | 'headers'>;
20
20
  export type RegExpInput = RegExp | RegExpObject;
21
+ export type SkippedRequestReason = 'robotsTxt' | 'limit' | 'enqueueLimit' | 'filters' | 'transform' | 'redirect' | 'depth';
22
+ export type SkippedRequestCallback = (args: {
23
+ url: string;
24
+ reason: SkippedRequestReason;
25
+ }) => Awaitable<void>;
21
26
  /**
22
27
  * @ignore
23
28
  */
@@ -45,23 +50,34 @@ export declare function validateGlobPattern(glob: string): string;
45
50
  */
46
51
  export declare function constructRegExpObjectsFromRegExps(regexps: readonly RegExpInput[]): RegExpObject[];
47
52
  /**
53
+ * Filters request options by URL patterns and merges pattern-level options (label, userData, method, payload, headers)
54
+ * from the first matching pattern into each RequestOptions entry.
55
+ *
56
+ * When `includePatterns` is empty/undefined, all options pass through (only exclude filtering applies).
48
57
  * @ignore
49
58
  */
50
- export declare function createRequests(requestOptions: (string | RequestOptions)[], urlPatternObjects?: UrlPatternObject[], excludePatternObjects?: UrlPatternObject[], strategy?: EnqueueLinksOptions['strategy']): Request[];
51
- export declare function filterRequestsByPatterns(requests: Request[], patterns?: UrlPatternObject[]): Request[];
59
+ export declare function filterRequestOptionsByPatterns(requestOptions: RequestOptions[], includePatterns: UrlPatternObject[] | undefined, excludePatterns?: UrlPatternObject[], strategy?: EnqueueLinksOptions['strategy'], onSkippedUrl?: (url: string) => void): RequestOptions[];
52
60
  /**
53
61
  * @ignore
54
62
  */
55
- export declare function createRequestOptions(sources: readonly (string | Record<string, unknown>)[], options?: Pick<EnqueueLinksOptions, 'label' | 'userData' | 'baseUrl' | 'skipNavigation' | 'strategy'>): RequestOptions[];
63
+ export declare function createRequestOptions(sources: readonly (string | Record<string, unknown>)[], options?: Pick<EnqueueLinksOptions, 'label' | 'userData' | 'baseUrl' | 'skipNavigation' | 'sessionId' | 'strategy'>): RequestOptions[];
56
64
  /**
57
- * Takes an Apify {@link RequestOptions} object and changes its attributes in a desired way. This user-function is used
58
- * {@link enqueueLinks} to modify requests before enqueuing them.
65
+ * Takes a {@link RequestOptions} object and changes its attributes in a desired way. This user-function is used
66
+ * by {@link enqueueLinks} to modify request options before they are converted to {@link Request} instances.
59
67
  */
60
68
  export interface RequestTransform {
61
69
  /**
62
70
  * @param original Request options to be modified.
63
- * @returns The modified request options to enqueue.
71
+ * @returns The modified request options to enqueue, `'unchanged'` to keep the original options as-is,
72
+ * or a falsy value / `'skip'` to exclude the request from the queue.
64
73
  */
65
- (original: RequestOptions): RequestOptions | false | undefined | null;
74
+ (original: RequestOptions): RequestOptions | false | undefined | null | 'skip' | 'unchanged';
66
75
  }
67
- //# sourceMappingURL=shared.d.ts.map
76
+ /**
77
+ * Applies a {@link RequestTransform} function to a list of request options.
78
+ * Options for which the transform returns a falsy value are removed from the list.
79
+ * @param onSkipped Called with the original request options when the transform returns a falsy value (i.e. the request is skipped).
80
+ * @ignore
81
+ * @internal
82
+ */
83
+ export declare function applyRequestTransform(requestOptions: RequestOptions[], transformFn: RequestTransform, onSkipped?: (requestOptions: RequestOptions) => void): RequestOptions[];
@@ -1,7 +1,6 @@
1
1
  import { URL } from 'node:url';
2
- import { minimatch } from 'minimatch';
2
+ import { Minimatch } from 'minimatch';
3
3
  import { purlToRegExp } from '@apify/pseudo_url';
4
- import { Request } from '../request.js';
5
4
  export { tryAbsoluteURL } from '@crawlee/utils';
6
5
  const MAX_ENQUEUE_LINKS_CACHE_SIZE = 1000;
7
6
  /**
@@ -110,51 +109,37 @@ export function constructRegExpObjectsFromRegExps(regexps) {
110
109
  });
111
110
  }
112
111
  /**
112
+ * Filters request options by URL patterns and merges pattern-level options (label, userData, method, payload, headers)
113
+ * from the first matching pattern into each RequestOptions entry.
114
+ *
115
+ * When `includePatterns` is empty/undefined, all options pass through (only exclude filtering applies).
113
116
  * @ignore
114
117
  */
115
- export function createRequests(requestOptions, urlPatternObjects, excludePatternObjects = [], strategy) {
118
+ export function filterRequestOptionsByPatterns(requestOptions, includePatterns, excludePatterns = [], strategy, onSkippedUrl) {
119
+ const excludeMatchers = excludePatterns.map(createPatternObjectMatcher);
120
+ const includeMatchers = includePatterns?.length ? includePatterns.map(createPatternObjectMatcher) : undefined;
116
121
  return requestOptions
117
- .map((opts) => ({ url: typeof opts === 'string' ? opts : opts.url, opts }))
118
122
  .filter(({ url }) => {
119
- return !excludePatternObjects.some((excludePatternObject) => {
120
- const { regexp, glob } = excludePatternObject;
121
- return (regexp && url.match(regexp)) || (glob && minimatch(url, glob, { nocase: true }));
122
- });
123
+ const matchesExclude = excludeMatchers.some(({ match }) => match(url));
124
+ if (matchesExclude) {
125
+ onSkippedUrl?.(url);
126
+ }
127
+ return !matchesExclude;
123
128
  })
124
- .map(({ url, opts }) => {
125
- if (!urlPatternObjects || !urlPatternObjects.length) {
126
- return new Request(typeof opts === 'string' ? { url: opts, enqueueStrategy: strategy } : { ...opts });
127
- }
128
- for (const urlPatternObject of urlPatternObjects) {
129
- const { regexp, glob, ...requestRegExpOptions } = urlPatternObject;
130
- if ((regexp && url.match(regexp)) || (glob && minimatch(url, glob, { nocase: true }))) {
131
- const request = typeof opts === 'string'
132
- ? { url: opts, ...requestRegExpOptions, enqueueStrategy: strategy }
133
- : { ...opts, ...requestRegExpOptions, enqueueStrategy: strategy };
134
- return new Request(request);
129
+ .map((opts) => {
130
+ if (!includeMatchers) {
131
+ return { ...opts, enqueueStrategy: strategy };
132
+ }
133
+ for (const { match, glob, regexp, ...patternOptions } of includeMatchers) {
134
+ if (match(opts.url)) {
135
+ return { ...opts, ...patternOptions, enqueueStrategy: strategy };
135
136
  }
136
137
  }
137
138
  // didn't match any positive pattern
139
+ onSkippedUrl?.(opts.url);
138
140
  return null;
139
141
  })
140
- .filter((request) => request);
141
- }
142
- export function filterRequestsByPatterns(requests, patterns) {
143
- if (!patterns?.length) {
144
- return requests;
145
- }
146
- const filtered = [];
147
- for (const request of requests) {
148
- for (const urlPatternObject of patterns) {
149
- const { regexp, glob } = urlPatternObject;
150
- if ((regexp && request.url.match(regexp)) || (glob && minimatch(request.url, glob, { nocase: true }))) {
151
- filtered.push(request);
152
- // Break the pattern loop, as we already matched this request once
153
- break;
154
- }
155
- }
156
- }
157
- return filtered;
142
+ .filter((opts) => opts !== null);
158
143
  }
159
144
  /**
160
145
  * @ignore
@@ -184,7 +169,53 @@ export function createRequestOptions(sources, options = {}) {
184
169
  if (options.skipNavigation) {
185
170
  requestOptions.skipNavigation = true;
186
171
  }
172
+ if (options.sessionId) {
173
+ requestOptions.sessionId = options.sessionId;
174
+ }
187
175
  return requestOptions;
188
176
  });
189
177
  }
190
- //# sourceMappingURL=shared.js.map
178
+ /**
179
+ * @ignore
180
+ */
181
+ function createPatternObjectMatcher(urlPatternObject) {
182
+ const { regexp, glob } = urlPatternObject;
183
+ let match;
184
+ if (regexp) {
185
+ match = (url) => regexp.test(url);
186
+ }
187
+ else if (glob) {
188
+ const m = new Minimatch(glob, { nocase: true });
189
+ match = (url) => m.match(url);
190
+ }
191
+ else {
192
+ match = () => false;
193
+ }
194
+ return { ...urlPatternObject, match };
195
+ }
196
+ /**
197
+ * Applies a {@link RequestTransform} function to a list of request options.
198
+ * Options for which the transform returns a falsy value are removed from the list.
199
+ * @param onSkipped Called with the original request options when the transform returns a falsy value (i.e. the request is skipped).
200
+ * @ignore
201
+ * @internal
202
+ */
203
+ export function applyRequestTransform(requestOptions, transformFn, onSkipped) {
204
+ return requestOptions
205
+ .map((opts) => {
206
+ const transformed = transformFn(opts);
207
+ if (transformed === 'skip') {
208
+ onSkipped?.(opts);
209
+ return null;
210
+ }
211
+ if (transformed === 'unchanged') {
212
+ return opts;
213
+ }
214
+ if (!transformed) {
215
+ onSkipped?.(opts);
216
+ return null;
217
+ }
218
+ return transformed;
219
+ })
220
+ .filter((r) => r !== null);
221
+ }
package/errors.d.ts CHANGED
@@ -14,6 +14,26 @@ export declare class CriticalError extends NonRetryableError {
14
14
  */
15
15
  export declare class MissingRouteError extends CriticalError {
16
16
  }
17
+ /**
18
+ * Thrown when a request's `userData` does not match the {@link RouteSchemas|Standard Schema} registered for its label.
19
+ *
20
+ * As the `userData` does not change between attempts, this error is non-retryable.
21
+ */
22
+ export declare class RequestValidationError extends NonRetryableError {
23
+ readonly label: string | symbol;
24
+ readonly issues: readonly {
25
+ readonly message: string;
26
+ readonly path?: readonly (PropertyKey | {
27
+ key: PropertyKey;
28
+ })[];
29
+ }[];
30
+ constructor(label: string | symbol, issues: readonly {
31
+ readonly message: string;
32
+ readonly path?: readonly (PropertyKey | {
33
+ key: PropertyKey;
34
+ })[];
35
+ }[]);
36
+ }
17
37
  /**
18
38
  * Errors of `RetryRequestError` type will always be retried by the crawler.
19
39
  *
@@ -23,11 +43,40 @@ export declare class RetryRequestError extends Error {
23
43
  constructor(message?: string);
24
44
  }
25
45
  /**
26
- * Errors of `SessionError` type will trigger a session rotation.
46
+ * Errors of `SessionError` type retire the session associated with the request and trigger a regular retry.
27
47
  *
28
- * This error doesn't respect the `maxRequestRetries` option and has a separate limit of `maxSessionRotations`.
48
+ * The retry counts towards the `maxRequestRetries` limit, just like any other error.
29
49
  */
30
- export declare class SessionError extends RetryRequestError {
50
+ export declare class SessionError extends Error {
51
+ constructor(message?: string);
52
+ }
53
+ /**
54
+ * Thrown when a requested session is not found in the referenced SessionPool.
55
+ */
56
+ export declare class MissingSessionError extends Error {
57
+ constructor(sessionId?: string);
58
+ }
59
+ export declare class ContextPipelineInterruptedError extends Error {
31
60
  constructor(message?: string);
32
61
  }
33
- //# sourceMappingURL=errors.d.ts.map
62
+ export declare class ContextPipelineInitializationError extends Error {
63
+ constructor(error: unknown, options?: ErrorOptions);
64
+ }
65
+ export declare class ContextPipelineCleanupError extends CriticalError {
66
+ constructor(error: unknown, options?: ErrorOptions);
67
+ }
68
+ export declare class RequestHandlerError extends Error {
69
+ constructor(error: unknown, options?: ErrorOptions);
70
+ }
71
+ /**
72
+ * Thrown when attempting to set a different service instance after one has already been retrieved.
73
+ */
74
+ export declare class ServiceConflictError extends Error {
75
+ constructor(serviceName: string, newValue: unknown, existingValue: unknown);
76
+ }
77
+ /**
78
+ * Thrown by crawlers when `skipNavigation` is used on a request.
79
+ * Subclasses can catch this error to skip their own navigation-dependent logic.
80
+ */
81
+ export declare class NavigationSkippedError extends NonRetryableError {
82
+ }
package/errors.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { inspectValue } from './debug.js';
1
2
  /**
2
3
  * Errors of `NonRetryableError` type will never be retried by the crawler.
3
4
  */
@@ -14,6 +15,28 @@ export class CriticalError extends NonRetryableError {
14
15
  */
15
16
  export class MissingRouteError extends CriticalError {
16
17
  }
18
+ /**
19
+ * Thrown when a request's `userData` does not match the {@link RouteSchemas|Standard Schema} registered for its label.
20
+ *
21
+ * As the `userData` does not change between attempts, this error is non-retryable.
22
+ */
23
+ export class RequestValidationError extends NonRetryableError {
24
+ label;
25
+ issues;
26
+ constructor(label, issues) {
27
+ const details = issues
28
+ .map((issue) => {
29
+ const path = (issue.path ?? [])
30
+ .map((segment) => (typeof segment === 'object' ? segment.key : segment))
31
+ .join('.');
32
+ return `- ${path ? `${path}: ` : ''}${issue.message}`;
33
+ })
34
+ .join('\n');
35
+ super(`Request userData for label '${String(label)}' failed schema validation:\n${details}`);
36
+ this.label = label;
37
+ this.issues = issues;
38
+ }
39
+ }
17
40
  /**
18
41
  * Errors of `RetryRequestError` type will always be retried by the crawler.
19
42
  *
@@ -25,13 +48,55 @@ export class RetryRequestError extends Error {
25
48
  }
26
49
  }
27
50
  /**
28
- * Errors of `SessionError` type will trigger a session rotation.
51
+ * Errors of `SessionError` type retire the session associated with the request and trigger a regular retry.
29
52
  *
30
- * This error doesn't respect the `maxRequestRetries` option and has a separate limit of `maxSessionRotations`.
53
+ * The retry counts towards the `maxRequestRetries` limit, just like any other error.
31
54
  */
32
- export class SessionError extends RetryRequestError {
55
+ export class SessionError extends Error {
33
56
  constructor(message) {
34
- super(`Detected a session error, rotating session... ${message ? `\n${message}` : ''}`);
57
+ super(`Detected a session error, retiring session... ${message ? `\n${message}` : ''}`);
35
58
  }
36
59
  }
37
- //# sourceMappingURL=errors.js.map
60
+ /**
61
+ * Thrown when a requested session is not found in the referenced SessionPool.
62
+ */
63
+ export class MissingSessionError extends Error {
64
+ constructor(sessionId) {
65
+ super(`The current SessionPool instance couldn't find a valid session${sessionId ? ` for the following id: ${sessionId}.` : '.'}`);
66
+ }
67
+ }
68
+ export class ContextPipelineInterruptedError extends Error {
69
+ constructor(message) {
70
+ super(`Request handling was interrupted during context initialization ${message ? ` - ${message}` : ''}`);
71
+ }
72
+ }
73
+ export class ContextPipelineInitializationError extends Error {
74
+ constructor(error, options) {
75
+ super(undefined, { cause: error, ...options });
76
+ }
77
+ }
78
+ export class ContextPipelineCleanupError extends CriticalError {
79
+ constructor(error, options) {
80
+ super(undefined, { cause: error, ...options });
81
+ }
82
+ }
83
+ export class RequestHandlerError extends Error {
84
+ constructor(error, options) {
85
+ super(undefined, { cause: error, ...options });
86
+ }
87
+ }
88
+ /**
89
+ * Thrown when attempting to set a different service instance after one has already been retrieved.
90
+ */
91
+ export class ServiceConflictError extends Error {
92
+ constructor(serviceName, newValue, existingValue) {
93
+ super(`Service ${serviceName} is already in use. ` +
94
+ `Existing value: ${inspectValue(existingValue)}, attempted new value: ${inspectValue(newValue)}.`);
95
+ }
96
+ }
97
+ /**
98
+ * Thrown by crawlers when `skipNavigation` is used on a request.
99
+ * Subclasses can catch this error to skip their own navigation-dependent logic.
100
+ */
101
+ export class NavigationSkippedError extends NonRetryableError {
102
+ }
@@ -1,28 +1,55 @@
1
1
  import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';
2
2
  import type { BetterIntervalID } from '@apify/utilities';
3
- import { Configuration } from '../configuration.js';
3
+ export interface EventManagerOptions {
4
+ /** Interval between emitted `persistState` events in milliseconds. */
5
+ persistStateIntervalMillis: number;
6
+ }
4
7
  export declare const enum EventType {
5
8
  PERSIST_STATE = "persistState",
6
9
  SYSTEM_INFO = "systemInfo",
7
10
  MIGRATING = "migrating",
8
11
  ABORTING = "aborting",
9
- EXIT = "exit"
12
+ EXIT = "exit",
13
+ STATUS_MESSAGE = "statusMessage"
14
+ }
15
+ export type EventTypeName = EventType | 'systemInfo' | 'persistState' | 'migrating' | 'aborting' | 'exit' | 'statusMessage';
16
+ /**
17
+ * Payload emitted with the {@link EventType.STATUS_MESSAGE|`statusMessage`} event.
18
+ *
19
+ * The crawler broadcasts these whenever it wants to report its progress (e.g. periodically, or on
20
+ * start/finish). Consumers such as the Apify SDK can listen for the event and propagate the message
21
+ * to the platform. This keeps the crawler decoupled from any specific status-reporting backend.
22
+ */
23
+ export interface EventStatusMessageData {
24
+ /**
25
+ * Identifies the crawler that emitted the message.
26
+ *
27
+ * Either the user-provided `id` from the crawler options, or a randomly generated one.
28
+ * Since a single event manager may be shared by multiple crawlers, consumers can use this
29
+ * to attribute the message to a specific crawler instance.
30
+ */
31
+ crawlerId: string;
32
+ /** The human-readable status message. */
33
+ message: string;
34
+ /** Whether this is the final status message of the run. */
35
+ isStatusMessageTerminal?: boolean;
36
+ /** The log level the message was logged with. */
37
+ level?: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR';
10
38
  }
11
- export type EventTypeName = EventType | 'systemInfo' | 'persistState' | 'migrating' | 'aborting' | 'exit';
12
39
  interface Intervals {
13
40
  persistState?: BetterIntervalID;
14
41
  systemInfo?: BetterIntervalID;
15
42
  }
16
43
  export declare abstract class EventManager {
17
- readonly config: Configuration;
18
44
  protected events: AsyncEventEmitter<{}>;
19
45
  protected initialized: boolean;
20
46
  protected intervals: Intervals;
21
47
  // @ts-ignore optional peer dependency or compatibility with es2022
22
- protected log: import("@apify/log").Log;
23
- constructor(config?: Configuration);
48
+ protected log: import("@crawlee/types").CrawleeLogger;
49
+ private persistStateIntervalMillis;
50
+ constructor(options: EventManagerOptions);
24
51
  /**
25
- * Initializes the event manager by creating the `persistState` event interval.
52
+ * Initializes the event manager by starting the `persistState` event interval.
26
53
  * This is automatically called at the beginning of `crawler.run()`.
27
54
  */
28
55
  init(): Promise<void>;
@@ -49,4 +76,3 @@ export declare abstract class EventManager {
49
76
  waitForAllListenersToComplete(): Promise<boolean>;
50
77
  }
51
78
  export {};
52
- //# sourceMappingURL=event_manager.d.ts.map
@@ -1,7 +1,6 @@
1
1
  import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';
2
- import log from '@apify/log';
3
2
  import { betterClearInterval, betterSetInterval } from '@apify/utilities';
4
- import { Configuration } from '../configuration.js';
3
+ import { serviceLocator } from '../service_locator.js';
5
4
  export var EventType;
6
5
  (function (EventType) {
7
6
  EventType["PERSIST_STATE"] = "persistState";
@@ -9,30 +8,30 @@ export var EventType;
9
8
  EventType["MIGRATING"] = "migrating";
10
9
  EventType["ABORTING"] = "aborting";
11
10
  EventType["EXIT"] = "exit";
11
+ EventType["STATUS_MESSAGE"] = "statusMessage";
12
12
  })(EventType || (EventType = {}));
13
13
  export class EventManager {
14
- config;
15
14
  events = new AsyncEventEmitter();
16
15
  initialized = false;
17
16
  intervals = {};
18
- log = log.child({ prefix: 'Events' });
19
- constructor(config = Configuration.getGlobalConfig()) {
20
- this.config = config;
17
+ log = serviceLocator.getLogger().child({ prefix: 'Events' });
18
+ persistStateIntervalMillis;
19
+ constructor(options) {
20
+ this.persistStateIntervalMillis = options.persistStateIntervalMillis;
21
21
  this.events.setMaxListeners(50);
22
22
  }
23
23
  /**
24
- * Initializes the event manager by creating the `persistState` event interval.
24
+ * Initializes the event manager by starting the `persistState` event interval.
25
25
  * This is automatically called at the beginning of `crawler.run()`.
26
26
  */
27
27
  async init() {
28
28
  if (this.initialized) {
29
29
  return;
30
30
  }
31
- const persistStateIntervalMillis = this.config.get('persistStateIntervalMillis');
32
31
  this.intervals.persistState = betterSetInterval((intervalCallback) => {
33
32
  this.emit("persistState" /* EventType.PERSIST_STATE */, { isMigrating: false });
34
33
  intervalCallback();
35
- }, persistStateIntervalMillis);
34
+ }, this.persistStateIntervalMillis);
36
35
  this.initialized = true;
37
36
  }
38
37
  /**
@@ -86,4 +85,3 @@ export class EventManager {
86
85
  return this.events.waitForAllListenersToComplete();
87
86
  }
88
87
  }
89
- //# sourceMappingURL=event_manager.js.map
package/events/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
1
  export * from './event_manager.js';
2
2
  export * from './local_event_manager.js';
3
- //# sourceMappingURL=index.d.ts.map
package/events/index.js CHANGED
@@ -1,3 +1,2 @@
1
1
  export * from './event_manager.js';
2
2
  export * from './local_event_manager.js';
3
- //# sourceMappingURL=index.js.map