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

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 +84 -13
  86. package/request.js +107 -28
  87. package/router.d.ts +143 -17
  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 +0 -1
  106. package/storages/access_checking.js +5 -2
  107. package/storages/dataset.d.ts +103 -53
  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 -38
  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 +91 -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 +1 -2
  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,19 @@
1
- import { EventManager } from './event_manager.js';
1
+ import type { Configuration } from '../configuration.js';
2
+ import { EventManager, type EventManagerOptions } from './event_manager.js';
3
+ export interface LocalEventManagerOptions extends EventManagerOptions {
4
+ /** Interval between emitted `systemInfo` events in milliseconds. */
5
+ systemInfoIntervalMillis: number;
6
+ }
2
7
  export declare class LocalEventManager extends EventManager {
8
+ private systemInfoIntervalMillis;
9
+ constructor(options: LocalEventManagerOptions);
10
+ /**
11
+ * Creates a new `LocalEventManager` based on the provided `Configuration`.
12
+ * Uses the global configuration from the service locator if none is provided.
13
+ */
14
+ static fromConfiguration(configuration?: Configuration): LocalEventManager;
3
15
  /**
4
- * Initializes the EventManager and sets up periodic `systemInfo` and `persistState` events.
16
+ * Initializes the EventManager and sets up periodic `systemInfo` events.
5
17
  * This is automatically called at the beginning of `crawler.run()`.
6
18
  */
7
19
  init(): Promise<void>;
@@ -23,5 +35,5 @@ export declare class LocalEventManager extends EventManager {
23
35
  private createSystemInfo;
24
36
  private createCpuInfo;
25
37
  private createMemoryInfo;
38
+ private getMemoryInfo;
26
39
  }
27
- //# sourceMappingURL=local_event_manager.d.ts.map
@@ -1,10 +1,25 @@
1
- import { getCurrentCpuTicksV2, getMemoryInfo, isContainerized } from '@crawlee/utils';
2
- import log from '@apify/log';
3
1
  import { betterClearInterval, betterSetInterval } from '@apify/utilities';
2
+ import { serviceLocator } from '../service_locator.js';
4
3
  import { EventManager } from './event_manager.js';
5
4
  export class LocalEventManager extends EventManager {
5
+ systemInfoIntervalMillis;
6
+ constructor(options) {
7
+ super(options);
8
+ this.systemInfoIntervalMillis = options.systemInfoIntervalMillis;
9
+ }
10
+ /**
11
+ * Creates a new `LocalEventManager` based on the provided `Configuration`.
12
+ * Uses the global configuration from the service locator if none is provided.
13
+ */
14
+ static fromConfiguration(configuration) {
15
+ const resolvedConfiguration = configuration ?? serviceLocator.getConfiguration();
16
+ return new LocalEventManager({
17
+ persistStateIntervalMillis: resolvedConfiguration.persistStateIntervalMillis,
18
+ systemInfoIntervalMillis: resolvedConfiguration.systemInfoIntervalMillis,
19
+ });
20
+ }
6
21
  /**
7
- * Initializes the EventManager and sets up periodic `systemInfo` and `persistState` events.
22
+ * Initializes the EventManager and sets up periodic `systemInfo` events.
8
23
  * This is automatically called at the beginning of `crawler.run()`.
9
24
  */
10
25
  async init() {
@@ -12,9 +27,8 @@ export class LocalEventManager extends EventManager {
12
27
  return;
13
28
  }
14
29
  await super.init();
15
- const systemInfoIntervalMillis = this.config.get('systemInfoIntervalMillis');
16
30
  this.emitSystemInfoEvent = this.emitSystemInfoEvent.bind(this);
17
- this.intervals.systemInfo = betterSetInterval(this.emitSystemInfoEvent.bind(this), systemInfoIntervalMillis);
31
+ this.intervals.systemInfo = betterSetInterval(this.emitSystemInfoEvent.bind(this), this.systemInfoIntervalMillis);
18
32
  }
19
33
  /**
20
34
  * @inheritDoc
@@ -31,7 +45,7 @@ export class LocalEventManager extends EventManager {
31
45
  */
32
46
  async emitSystemInfoEvent(intervalCallback) {
33
47
  const info = await this.createSystemInfo({
34
- maxUsedCpuRatio: this.config.get('maxUsedCpuRatio'),
48
+ maxUsedCpuRatio: serviceLocator.getConfiguration().maxUsedCpuRatio,
35
49
  });
36
50
  this.events.emit("systemInfo" /* EventType.SYSTEM_INFO */, info);
37
51
  intervalCallback();
@@ -40,7 +54,8 @@ export class LocalEventManager extends EventManager {
40
54
  * @internal
41
55
  */
42
56
  async isContainerizedWrapper() {
43
- return this.config.get('containerized', await isContainerized());
57
+ const { isContainerized } = await import('../system-info/runtime.js');
58
+ return serviceLocator.getConfiguration().containerized ?? (await isContainerized());
44
59
  }
45
60
  /**
46
61
  * Creates a SystemInfo object based on local metrics.
@@ -53,7 +68,11 @@ export class LocalEventManager extends EventManager {
53
68
  };
54
69
  }
55
70
  async createCpuInfo(options) {
56
- const usedCpuRatio = await getCurrentCpuTicksV2(await this.isContainerizedWrapper());
71
+ const { getCurrentCpuTicksV2 } = await import('../system-info/cpu-info.js');
72
+ const usedCpuRatio = await getCurrentCpuTicksV2({
73
+ containerized: await this.isContainerizedWrapper(),
74
+ logger: serviceLocator.getLogger(),
75
+ });
57
76
  return {
58
77
  cpuCurrentUsage: usedCpuRatio * 100,
59
78
  isCpuOverloaded: usedCpuRatio > options.maxUsedCpuRatio,
@@ -61,15 +80,22 @@ export class LocalEventManager extends EventManager {
61
80
  }
62
81
  async createMemoryInfo() {
63
82
  try {
64
- const memInfo = await getMemoryInfo(await this.isContainerizedWrapper());
83
+ const memInfo = await this.getMemoryInfo();
65
84
  return {
85
+ memTotalBytes: memInfo.totalBytes,
66
86
  memCurrentBytes: memInfo.mainProcessBytes + memInfo.childProcessesBytes,
67
87
  };
68
88
  }
69
89
  catch (err) {
70
- log.exception(err, 'Memory snapshot failed.');
90
+ this.log.exception(err, 'Memory snapshot failed.');
71
91
  return {};
72
92
  }
73
93
  }
94
+ async getMemoryInfo() {
95
+ const { getMemoryInfo } = await import('../system-info/memory-info.js');
96
+ return getMemoryInfo({
97
+ containerized: await this.isContainerizedWrapper(),
98
+ logger: serviceLocator.getLogger(),
99
+ });
100
+ }
74
101
  }
75
- //# sourceMappingURL=local_event_manager.js.map
package/index.d.ts CHANGED
@@ -1,19 +1,22 @@
1
+ export * from './debug.js';
1
2
  export * from './errors.js';
2
3
  export * from './autoscaling/index.js';
3
4
  export * from './configuration.js';
5
+ export * from './service_locator.js';
4
6
  export * from './crawlers/index.js';
5
7
  export * from './enqueue_links/index.js';
6
8
  export * from './events/index.js';
7
- export * from './http_clients/index.js';
8
9
  export * from './log.js';
10
+ export * from './owned_or_injected.js';
9
11
  export * from './proxy_configuration.js';
10
12
  export * from './request.js';
11
13
  export * from './router.js';
12
14
  export * from './serialization.js';
13
15
  export * from './session_pool/index.js';
14
16
  export * from './storages/index.js';
17
+ export * from './memory-storage/index.js';
15
18
  export * from './validators.js';
16
19
  export * from './cookie_utils.js';
20
+ export * from './recoverable_state.js';
17
21
  export { PseudoUrl } from '@apify/pseudo_url';
18
- export { Dictionary, Awaitable, Constructor, StorageClient, Cookie, QueueOperationInfo } from '@crawlee/types';
19
- //# sourceMappingURL=index.d.ts.map
22
+ export type { Dictionary, Awaitable, Constructor, StorageBackend, Cookie, QueueOperationInfo } from '@crawlee/types';
package/index.js CHANGED
@@ -1,18 +1,21 @@
1
+ export * from './debug.js';
1
2
  export * from './errors.js';
2
3
  export * from './autoscaling/index.js';
3
4
  export * from './configuration.js';
5
+ export * from './service_locator.js';
4
6
  export * from './crawlers/index.js';
5
7
  export * from './enqueue_links/index.js';
6
8
  export * from './events/index.js';
7
- export * from './http_clients/index.js';
8
9
  export * from './log.js';
10
+ export * from './owned_or_injected.js';
9
11
  export * from './proxy_configuration.js';
10
12
  export * from './request.js';
11
13
  export * from './router.js';
12
14
  export * from './serialization.js';
13
15
  export * from './session_pool/index.js';
14
16
  export * from './storages/index.js';
17
+ export * from './memory-storage/index.js';
15
18
  export * from './validators.js';
16
19
  export * from './cookie_utils.js';
20
+ export * from './recoverable_state.js';
17
21
  export { PseudoUrl } from '@apify/pseudo_url';
18
- //# sourceMappingURL=index.js.map
package/log.d.ts CHANGED
@@ -1,3 +1,82 @@
1
- import log, { Log, Logger, LoggerJson, LoggerOptions, LoggerText, LogLevel } from '@apify/log';
2
- export { log, Log, LoggerOptions, LogLevel, Logger, LoggerJson, LoggerText };
3
- //# sourceMappingURL=log.d.ts.map
1
+ import type { CrawleeLogger, CrawleeLoggerOptions } from '@crawlee/types';
2
+ import type { LoggerOptions } from '@apify/log';
3
+ import log, { Log, Logger, LoggerJson, LoggerText, LogLevel } from '@apify/log';
4
+ export type { CrawleeLogger, CrawleeLoggerOptions };
5
+ /**
6
+ * Abstract base class for custom Crawlee logger implementations.
7
+ *
8
+ * Subclasses must implement two methods:
9
+ * - {@link BaseCrawleeLogger.logWithLevel} — the core logging dispatch
10
+ * - {@link BaseCrawleeLogger.createChild} — how to create a child logger instance
11
+ *
12
+ * All other `CrawleeLogger` methods (`error`, `warning`, `info`, `debug`, etc.)
13
+ * are derived automatically. Level filtering is entirely the responsibility of the
14
+ * underlying library — `logWithLevel()` is called for every message.
15
+ *
16
+ * **Example — Winston adapter:**
17
+ * ```typescript
18
+ * const CRAWLEE_TO_WINSTON = { 1: 'error', 2: 'warn', 3: 'warn', 4: 'info', 5: 'debug', 6: 'debug' };
19
+ *
20
+ * class WinstonAdapter extends BaseCrawleeLogger {
21
+ * constructor(private logger: winston.Logger, options?: Partial<CrawleeLoggerOptions>) {
22
+ * super(options);
23
+ * }
24
+ *
25
+ * logWithLevel(level: number, message: string, data?: Record<string, unknown>): void {
26
+ * this.logger.log(CRAWLEE_TO_WINSTON[level] ?? 'info', message, data);
27
+ * }
28
+ *
29
+ * protected createChild(options: Partial<CrawleeLoggerOptions>): CrawleeLogger {
30
+ * return new WinstonAdapter(this.logger.child({ prefix: options.prefix }), { ...this.getOptions(), ...options });
31
+ * }
32
+ * }
33
+ * ```
34
+ */
35
+ export declare abstract class BaseCrawleeLogger implements CrawleeLogger {
36
+ private options;
37
+ private readonly warningsLogged;
38
+ constructor(options?: Partial<CrawleeLoggerOptions>);
39
+ /**
40
+ * Core logging method. Subclasses must implement this to dispatch log messages
41
+ * to the underlying logger (Winston, Pino, console, etc.).
42
+ *
43
+ * Level filtering is the responsibility of the underlying library — this method
44
+ * is called for every message regardless of the current level.
45
+ *
46
+ * @param level Crawlee log level (use {@link LogLevel} constants)
47
+ * @param message The log message
48
+ * @param data Optional structured data to attach to the log entry
49
+ */
50
+ abstract logWithLevel(level: number, message: string, data?: Record<string, unknown>): void;
51
+ /**
52
+ * Creates a child logger instance. Subclasses must implement this to define
53
+ * how child loggers are created for the underlying logger.
54
+ */
55
+ protected abstract createChild(options: Partial<CrawleeLoggerOptions>): CrawleeLogger;
56
+ getOptions(): CrawleeLoggerOptions;
57
+ setOptions(options: Partial<CrawleeLoggerOptions>): void;
58
+ child(options: Partial<CrawleeLoggerOptions>): CrawleeLogger;
59
+ error(message: string, data?: Record<string, unknown>): void;
60
+ exception(exception: Error, message: string, data?: Record<string, unknown>): void;
61
+ softFail(message: string, data?: Record<string, unknown>): void;
62
+ warning(message: string, data?: Record<string, unknown>): void;
63
+ warningOnce(message: string): void;
64
+ info(message: string, data?: Record<string, unknown>): void;
65
+ debug(message: string, data?: Record<string, unknown>): void;
66
+ perf(message: string, data?: Record<string, unknown>): void;
67
+ deprecated(message: string): void;
68
+ }
69
+ /**
70
+ * Adapter that wraps `@apify/log`'s {@link Log} instance to implement the {@link CrawleeLogger} interface.
71
+ *
72
+ * This is the default logger used by Crawlee when no custom logger is configured.
73
+ * Users who want to use a different logging library should implement {@link BaseCrawleeLogger} directly.
74
+ */
75
+ export declare class ApifyLogAdapter extends BaseCrawleeLogger {
76
+ private readonly apifyLog;
77
+ constructor(apifyLog: Log, options?: Partial<CrawleeLoggerOptions>);
78
+ logWithLevel(level: number, message: string, data?: Record<string, unknown>): void;
79
+ protected createChild(options: Partial<CrawleeLoggerOptions>): CrawleeLogger;
80
+ }
81
+ export { log, Log, LogLevel, Logger, LoggerJson, LoggerText };
82
+ export type { LoggerOptions };
package/log.js CHANGED
@@ -1,3 +1,104 @@
1
1
  import log, { Log, Logger, LoggerJson, LoggerText, LogLevel } from '@apify/log';
2
+ /**
3
+ * Abstract base class for custom Crawlee logger implementations.
4
+ *
5
+ * Subclasses must implement two methods:
6
+ * - {@link BaseCrawleeLogger.logWithLevel} — the core logging dispatch
7
+ * - {@link BaseCrawleeLogger.createChild} — how to create a child logger instance
8
+ *
9
+ * All other `CrawleeLogger` methods (`error`, `warning`, `info`, `debug`, etc.)
10
+ * are derived automatically. Level filtering is entirely the responsibility of the
11
+ * underlying library — `logWithLevel()` is called for every message.
12
+ *
13
+ * **Example — Winston adapter:**
14
+ * ```typescript
15
+ * const CRAWLEE_TO_WINSTON = { 1: 'error', 2: 'warn', 3: 'warn', 4: 'info', 5: 'debug', 6: 'debug' };
16
+ *
17
+ * class WinstonAdapter extends BaseCrawleeLogger {
18
+ * constructor(private logger: winston.Logger, options?: Partial<CrawleeLoggerOptions>) {
19
+ * super(options);
20
+ * }
21
+ *
22
+ * logWithLevel(level: number, message: string, data?: Record<string, unknown>): void {
23
+ * this.logger.log(CRAWLEE_TO_WINSTON[level] ?? 'info', message, data);
24
+ * }
25
+ *
26
+ * protected createChild(options: Partial<CrawleeLoggerOptions>): CrawleeLogger {
27
+ * return new WinstonAdapter(this.logger.child({ prefix: options.prefix }), { ...this.getOptions(), ...options });
28
+ * }
29
+ * }
30
+ * ```
31
+ */
32
+ export class BaseCrawleeLogger {
33
+ options;
34
+ warningsLogged = new Set();
35
+ constructor(options = {}) {
36
+ this.options = options;
37
+ }
38
+ getOptions() {
39
+ return this.options;
40
+ }
41
+ setOptions(options) {
42
+ this.options = { ...this.options, ...options };
43
+ }
44
+ child(options) {
45
+ return this.createChild(options);
46
+ }
47
+ error(message, data) {
48
+ this.logWithLevel(LogLevel.ERROR, message, data);
49
+ }
50
+ exception(exception, message, data) {
51
+ this.logWithLevel(LogLevel.ERROR, `${message}: ${exception.message}`, {
52
+ ...data,
53
+ stack: exception.stack,
54
+ exception,
55
+ });
56
+ }
57
+ softFail(message, data) {
58
+ this.logWithLevel(LogLevel.SOFT_FAIL, message, data);
59
+ }
60
+ warning(message, data) {
61
+ this.logWithLevel(LogLevel.WARNING, message, data);
62
+ }
63
+ warningOnce(message) {
64
+ if (!this.warningsLogged.has(message)) {
65
+ this.warningsLogged.add(message);
66
+ this.warning(message);
67
+ }
68
+ }
69
+ info(message, data) {
70
+ this.logWithLevel(LogLevel.INFO, message, data);
71
+ }
72
+ debug(message, data) {
73
+ this.logWithLevel(LogLevel.DEBUG, message, data);
74
+ }
75
+ perf(message, data) {
76
+ this.logWithLevel(LogLevel.PERF, `[PERF] ${message}`, data);
77
+ }
78
+ deprecated(message) {
79
+ this.warningOnce(`[DEPRECATED] ${message}`);
80
+ }
81
+ }
82
+ /**
83
+ * Adapter that wraps `@apify/log`'s {@link Log} instance to implement the {@link CrawleeLogger} interface.
84
+ *
85
+ * This is the default logger used by Crawlee when no custom logger is configured.
86
+ * Users who want to use a different logging library should implement {@link BaseCrawleeLogger} directly.
87
+ */
88
+ export class ApifyLogAdapter extends BaseCrawleeLogger {
89
+ apifyLog;
90
+ constructor(apifyLog, options) {
91
+ super(options ?? {});
92
+ this.apifyLog = apifyLog;
93
+ }
94
+ logWithLevel(level, message, data) {
95
+ this.apifyLog.internal(level, message, data);
96
+ }
97
+ createChild(options) {
98
+ return new ApifyLogAdapter(this.apifyLog.child({ prefix: options.prefix ?? null }), {
99
+ ...this.getOptions(),
100
+ ...options,
101
+ });
102
+ }
103
+ }
2
104
  export { log, Log, LogLevel, Logger, LoggerJson, LoggerText };
3
- //# sourceMappingURL=log.js.map
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Length of id property of a Request instance in characters.
3
+ */
4
+ export declare const REQUEST_ID_LENGTH = 15;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Length of id property of a Request instance in characters.
3
+ */
4
+ export const REQUEST_ID_LENGTH = 15;
@@ -0,0 +1 @@
1
+ export * from './memory-storage.js';
@@ -0,0 +1 @@
1
+ export * from './memory-storage.js';
@@ -0,0 +1,46 @@
1
+ import type * as storage from '@crawlee/types';
2
+ import type { CrawleeLogger } from '@crawlee/types';
3
+ import { DatasetBackend } from './resource-clients/dataset.js';
4
+ import { KeyValueStoreBackend } from './resource-clients/key-value-store.js';
5
+ import { RequestQueueBackend } from './resource-clients/request-queue.js';
6
+ export interface MemoryStorageOptions {
7
+ /**
8
+ * Optional logger for MemoryStorageBackend warnings.
9
+ */
10
+ logger?: CrawleeLogger;
11
+ }
12
+ export declare class MemoryStorageBackend implements storage.StorageBackend {
13
+ readonly logger?: CrawleeLogger;
14
+ /**
15
+ * Unique per-instance cache partition key. Mirrors the way `FileSystemStorageBackend` partitions its
16
+ * cache by storage directory: two distinct `MemoryStorageBackend` instances must not share cached backends.
17
+ */
18
+ private readonly instanceCacheKey;
19
+ readonly keyValueStoreBackendCache: KeyValueStoreBackend[];
20
+ readonly datasetBackendCache: DatasetBackend[];
21
+ readonly requestQueueBackendCache: RequestQueueBackend[];
22
+ constructor(options?: MemoryStorageOptions);
23
+ /**
24
+ * Return a per-instance unique cache key so that distinct `MemoryStorageBackend` instances get separate
25
+ * cache partitions in the storage backend cache.
26
+ */
27
+ getStorageBackendCacheKey(): string;
28
+ private static resolveStorageKey;
29
+ createDatasetBackend(options?: storage.StorageIdentifier): Promise<storage.DatasetBackend>;
30
+ createKeyValueStoreBackend(options?: storage.StorageIdentifier): Promise<storage.KeyValueStoreBackend>;
31
+ createRequestQueueBackend(options?: storage.StorageIdentifier): Promise<RequestQueueBackend>;
32
+ storageExists(id: string, type: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<boolean>;
33
+ /**
34
+ * Cleans up the default storages before the run starts. For the in-memory storage this simply
35
+ * resets the in-memory state of the cached default dataset, key-value store and request queue.
36
+ *
37
+ * As with `FileSystemStorageBackend`, the run's input (the `INPUT` key in the default key-value
38
+ * store) is preserved — only the rest of the default storages is cleared.
39
+ */
40
+ purge(): Promise<void>;
41
+ /**
42
+ * This method should be called at the end of the process. The in-memory storage holds no resources
43
+ * that outlive the process (no file handles, no cross-process locks), so there is nothing to do.
44
+ */
45
+ teardown(): Promise<void>;
46
+ }
@@ -0,0 +1,136 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { DatasetBackend } from './resource-clients/dataset.js';
3
+ import { KeyValueStoreBackend } from './resource-clients/key-value-store.js';
4
+ import { RequestQueueBackend } from './resource-clients/request-queue.js';
5
+ export class MemoryStorageBackend {
6
+ logger;
7
+ /**
8
+ * Unique per-instance cache partition key. Mirrors the way `FileSystemStorageBackend` partitions its
9
+ * cache by storage directory: two distinct `MemoryStorageBackend` instances must not share cached backends.
10
+ */
11
+ instanceCacheKey = `MemoryStorageBackend:${randomUUID()}`;
12
+ keyValueStoreBackendCache = [];
13
+ datasetBackendCache = [];
14
+ requestQueueBackendCache = [];
15
+ constructor(options = {}) {
16
+ this.logger = options.logger;
17
+ }
18
+ /**
19
+ * Return a per-instance unique cache key so that distinct `MemoryStorageBackend` instances get separate
20
+ * cache partitions in the storage backend cache.
21
+ */
22
+ getStorageBackendCacheKey() {
23
+ return this.instanceCacheKey;
24
+ }
25
+ static resolveStorageKey(options) {
26
+ const isAlias = 'alias' in options && !!options.alias;
27
+ const rawKey = isAlias ? options.alias : (options.name ?? options.id);
28
+ // Normalize the internal __default__ alias to the user-facing 'default' name.
29
+ const cacheKey = rawKey === '__default__' ? 'default' : rawKey;
30
+ return { isAlias, cacheKey };
31
+ }
32
+ async createDatasetBackend(options = {}) {
33
+ const { isAlias, cacheKey } = MemoryStorageBackend.resolveStorageKey(options);
34
+ if (cacheKey) {
35
+ const found = this.datasetBackendCache.find((store) => store.id === cacheKey ||
36
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
37
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
38
+ if (found) {
39
+ return found;
40
+ }
41
+ }
42
+ const newStore = new DatasetBackend({
43
+ name: isAlias ? undefined : cacheKey,
44
+ cacheKey,
45
+ storageBackend: this,
46
+ });
47
+ this.datasetBackendCache.push(newStore);
48
+ return newStore;
49
+ }
50
+ async createKeyValueStoreBackend(options = {}) {
51
+ const { isAlias, cacheKey } = MemoryStorageBackend.resolveStorageKey(options);
52
+ if (cacheKey) {
53
+ const found = this.keyValueStoreBackendCache.find((store) => store.id === cacheKey ||
54
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
55
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
56
+ if (found) {
57
+ return found;
58
+ }
59
+ }
60
+ const newStore = new KeyValueStoreBackend({
61
+ name: isAlias ? undefined : cacheKey,
62
+ cacheKey,
63
+ storageBackend: this,
64
+ });
65
+ this.keyValueStoreBackendCache.push(newStore);
66
+ return newStore;
67
+ }
68
+ async createRequestQueueBackend(options = {}) {
69
+ const { isAlias, cacheKey } = MemoryStorageBackend.resolveStorageKey(options);
70
+ if (cacheKey) {
71
+ const found = this.requestQueueBackendCache.find((queue) => queue.id === cacheKey ||
72
+ queue.name?.toLowerCase() === cacheKey.toLowerCase() ||
73
+ queue.cacheKey.toLowerCase() === cacheKey.toLowerCase());
74
+ if (found) {
75
+ return found;
76
+ }
77
+ }
78
+ const newStore = new RequestQueueBackend({
79
+ name: isAlias ? undefined : cacheKey,
80
+ cacheKey,
81
+ storageBackend: this,
82
+ });
83
+ this.requestQueueBackendCache.push(newStore);
84
+ return newStore;
85
+ }
86
+ async storageExists(id, type) {
87
+ let backends;
88
+ switch (type) {
89
+ case 'Dataset':
90
+ backends = this.datasetBackendCache;
91
+ break;
92
+ case 'KeyValueStore':
93
+ backends = this.keyValueStoreBackendCache;
94
+ break;
95
+ case 'RequestQueue':
96
+ backends = this.requestQueueBackendCache;
97
+ break;
98
+ default:
99
+ return false;
100
+ }
101
+ // In-memory storage only knows about backends in its cache.
102
+ return backends.some((store) => store.id === id);
103
+ }
104
+ /**
105
+ * Cleans up the default storages before the run starts. For the in-memory storage this simply
106
+ * resets the in-memory state of the cached default dataset, key-value store and request queue.
107
+ *
108
+ * As with `FileSystemStorageBackend`, the run's input (the `INPUT` key in the default key-value
109
+ * store) is preserved — only the rest of the default storages is cleared.
110
+ */
111
+ async purge() {
112
+ // The run default is opened via `{ alias: '__default__' }`, which `resolveStorageKey`
113
+ // normalizes to `cacheKey === 'default'` (with `name === undefined`) — that is the clause
114
+ // that actually matches it. The `name === 'default'` clause additionally covers a store a user
115
+ // explicitly opened via `{ name: 'default' }`. (`'__default__'` never reaches `cacheKey`,
116
+ // as it is always normalized to `'default'` first, so it does not need to be checked here.)
117
+ const isDefault = (store) => store.name === 'default' || store.cacheKey === 'default';
118
+ const purgeDefaults = async (cache, purgeStore) => {
119
+ await Promise.all(cache.filter(isDefault).map(async (store) => purgeStore(store)));
120
+ };
121
+ await Promise.all([
122
+ // Preserve the run input (INPUT) when purging the default key-value store, matching
123
+ // `FileSystemStorageBackend`.
124
+ purgeDefaults(this.keyValueStoreBackendCache, async (store) => store.purgeExceptInput()),
125
+ purgeDefaults(this.datasetBackendCache, async (store) => store.purge()),
126
+ purgeDefaults(this.requestQueueBackendCache, async (store) => store.purge()),
127
+ ]);
128
+ }
129
+ /**
130
+ * This method should be called at the end of the process. The in-memory storage holds no resources
131
+ * that outlive the process (no file handles, no cross-process locks), so there is nothing to do.
132
+ */
133
+ async teardown() {
134
+ // Nothing to tear down for in-memory storage.
135
+ }
136
+ }
@@ -0,0 +1,4 @@
1
+ export declare class BaseClient {
2
+ id: string;
3
+ constructor(id: string);
4
+ }
@@ -0,0 +1,6 @@
1
+ export class BaseClient {
2
+ id;
3
+ constructor(id) {
4
+ this.id = id;
5
+ }
6
+ }
@@ -0,0 +1,40 @@
1
+ import type * as storage from '@crawlee/types';
2
+ import type { Dictionary } from '@crawlee/types';
3
+ import type { MemoryStorageBackend } from '../memory-storage.js';
4
+ import { BaseClient } from './common/base-client.js';
5
+ export interface DatasetBackendOptions {
6
+ id?: string;
7
+ name?: string;
8
+ /**
9
+ * The key used for cache lookup. When provided, takes precedence over `name` and `id`.
10
+ * This allows alias-opened storages to have a cache key that differs from their
11
+ * metadata `name` (which is `undefined` for unnamed storages).
12
+ */
13
+ cacheKey?: string;
14
+ storageBackend: MemoryStorageBackend;
15
+ }
16
+ export declare class DatasetBackend<Data extends Dictionary = Dictionary> extends BaseClient implements storage.DatasetBackend<Data> {
17
+ name?: string;
18
+ /**
19
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
20
+ * storages, this is the alias string. Falls back to id.
21
+ */
22
+ cacheKey: string;
23
+ createdAt: Date;
24
+ accessedAt: Date;
25
+ modifiedAt: Date;
26
+ itemCount: number;
27
+ private readonly datasetEntries;
28
+ private readonly storageBackend;
29
+ constructor(options: DatasetBackendOptions);
30
+ getMetadata(): Promise<storage.DatasetInfo>;
31
+ drop(): Promise<void>;
32
+ purge(): Promise<void>;
33
+ getData(options?: storage.DatasetBackendListOptions): Promise<storage.PaginatedList<Data>>;
34
+ private getDataPage;
35
+ pushData(items: Data[]): Promise<void>;
36
+ toDatasetInfo(): storage.DatasetInfo;
37
+ private generateLocalEntryName;
38
+ private getStartAndEndIndexes;
39
+ private updateTimestamps;
40
+ }