@crawlee/core 4.0.0-beta.13 → 4.0.0-beta.130

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 (280) hide show
  1. package/README.md +17 -13
  2. package/autoscaling/autoscaled_pool.d.ts +67 -172
  3. package/autoscaling/autoscaled_pool.js +182 -329
  4. package/autoscaling/concurrency_system.d.ts +268 -0
  5. package/autoscaling/concurrency_system.js +362 -0
  6. package/autoscaling/cpu_load_signal.d.ts +43 -0
  7. package/autoscaling/cpu_load_signal.js +47 -0
  8. package/autoscaling/event_loop_load_signal.d.ts +51 -0
  9. package/autoscaling/event_loop_load_signal.js +60 -0
  10. package/autoscaling/index.d.ts +6 -1
  11. package/autoscaling/index.js +6 -1
  12. package/autoscaling/load_signal.d.ts +100 -0
  13. package/autoscaling/load_signal.js +105 -0
  14. package/autoscaling/memory_load_signal.d.ts +47 -0
  15. package/autoscaling/memory_load_signal.js +106 -0
  16. package/autoscaling/snapshotter.d.ts +58 -163
  17. package/autoscaling/snapshotter.js +45 -263
  18. package/autoscaling/storage_backend_load_signal.d.ts +56 -0
  19. package/autoscaling/storage_backend_load_signal.js +73 -0
  20. package/autoscaling/system_status.d.ts +67 -89
  21. package/autoscaling/system_status.js +92 -122
  22. package/autoscaling/weighted_avg.d.ts +5 -0
  23. package/autoscaling/weighted_avg.js +14 -0
  24. package/byte_utils.d.ts +17 -0
  25. package/byte_utils.js +42 -0
  26. package/configuration.d.ts +96 -223
  27. package/configuration.js +170 -222
  28. package/cookie_utils.d.ts +3 -2
  29. package/cookie_utils.js +18 -7
  30. package/crawlers/context_pipeline.d.ts +10 -1
  31. package/crawlers/context_pipeline.js +31 -8
  32. package/crawlers/crawler_commons.d.ts +90 -129
  33. package/crawlers/crawler_commons.js +1 -116
  34. package/crawlers/error_snapshotter.d.ts +2 -5
  35. package/crawlers/error_snapshotter.js +7 -8
  36. package/crawlers/error_tracker.d.ts +0 -1
  37. package/crawlers/error_tracker.js +0 -1
  38. package/crawlers/index.d.ts +1 -3
  39. package/crawlers/index.js +0 -3
  40. package/crawlers/internals/types.d.ts +0 -1
  41. package/crawlers/internals/types.js +0 -1
  42. package/crawlers/statistics.d.ts +187 -63
  43. package/crawlers/statistics.js +354 -164
  44. package/debug.d.ts +36 -0
  45. package/debug.js +70 -0
  46. package/enqueue_links/enqueue_links.d.ts +68 -154
  47. package/enqueue_links/enqueue_links.js +38 -210
  48. package/enqueue_links/index.d.ts +0 -1
  49. package/enqueue_links/index.js +0 -1
  50. package/enqueue_links/shared.d.ts +52 -26
  51. package/enqueue_links/shared.js +115 -66
  52. package/errors.d.ts +72 -4
  53. package/errors.js +89 -5
  54. package/events/event_manager.d.ts +35 -9
  55. package/events/event_manager.js +12 -13
  56. package/events/index.d.ts +0 -1
  57. package/events/index.js +0 -1
  58. package/events/local_event_manager.d.ts +15 -3
  59. package/events/local_event_manager.js +39 -13
  60. package/http.d.ts +9 -0
  61. package/http.js +28 -0
  62. package/index.d.ts +7 -4
  63. package/index.js +6 -3
  64. package/iterables.d.ts +79 -0
  65. package/iterables.js +134 -0
  66. package/log.d.ts +82 -3
  67. package/log.js +106 -1
  68. package/memory-storage/consts.d.ts +4 -0
  69. package/memory-storage/consts.js +4 -0
  70. package/memory-storage/index.d.ts +1 -0
  71. package/memory-storage/index.js +1 -0
  72. package/memory-storage/memory-storage.d.ts +38 -0
  73. package/memory-storage/memory-storage.js +130 -0
  74. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  75. package/memory-storage/resource-clients/common/base-client.js +6 -0
  76. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  77. package/memory-storage/resource-clients/dataset.js +108 -0
  78. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  79. package/memory-storage/resource-clients/key-value-store.js +201 -0
  80. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  81. package/memory-storage/resource-clients/request-queue.js +409 -0
  82. package/memory-storage/utils.d.ts +16 -0
  83. package/memory-storage/utils.js +41 -0
  84. package/owned_or_injected.d.ts +58 -0
  85. package/owned_or_injected.js +98 -0
  86. package/package.json +14 -13
  87. package/proxy_configuration.d.ts +24 -132
  88. package/proxy_configuration.js +32 -147
  89. package/recoverable_state.d.ts +155 -0
  90. package/recoverable_state.js +231 -0
  91. package/request.d.ts +80 -16
  92. package/request.js +147 -68
  93. package/router.d.ts +193 -21
  94. package/router.js +188 -43
  95. package/serialization.d.ts +0 -1
  96. package/serialization.js +15 -15
  97. package/service_locator.d.ts +165 -0
  98. package/service_locator.js +253 -0
  99. package/session_pool/consts.d.ts +1 -2
  100. package/session_pool/consts.js +1 -2
  101. package/session_pool/errors.d.ts +0 -1
  102. package/session_pool/errors.js +0 -1
  103. package/session_pool/fingerprint.d.ts +9 -0
  104. package/session_pool/fingerprint.js +30 -0
  105. package/session_pool/index.d.ts +0 -2
  106. package/session_pool/index.js +0 -2
  107. package/session_pool/session.d.ts +35 -88
  108. package/session_pool/session.js +101 -159
  109. package/session_pool/session_pool.d.ts +73 -91
  110. package/session_pool/session_pool.js +172 -165
  111. package/storages/batched_adds.d.ts +37 -0
  112. package/storages/batched_adds.js +73 -0
  113. package/storages/dataset.d.ts +114 -54
  114. package/storages/dataset.js +291 -148
  115. package/storages/index.d.ts +10 -8
  116. package/storages/index.js +8 -8
  117. package/storages/key_value_store.d.ts +185 -42
  118. package/storages/key_value_store.js +445 -169
  119. package/storages/key_value_store_codec.d.ts +32 -0
  120. package/storages/key_value_store_codec.js +113 -0
  121. package/storages/request_dedup_cache.d.ts +22 -0
  122. package/storages/request_dedup_cache.js +48 -0
  123. package/storages/request_list.d.ts +52 -115
  124. package/storages/request_list.js +183 -152
  125. package/storages/request_loader.d.ts +101 -0
  126. package/storages/request_loader.js +1 -0
  127. package/storages/request_manager.d.ts +33 -0
  128. package/storages/request_manager.js +1 -0
  129. package/storages/request_manager_tandem.d.ts +97 -0
  130. package/storages/request_manager_tandem.js +197 -0
  131. package/storages/request_queue.d.ts +290 -47
  132. package/storages/request_queue.js +762 -216
  133. package/storages/{sitemap_request_list.d.ts → sitemap_request_loader.d.ts} +45 -89
  134. package/storages/sitemap_request_loader.js +438 -0
  135. package/storages/storage_instance_manager.d.ts +87 -0
  136. package/storages/storage_instance_manager.js +256 -0
  137. package/storages/storage_stats.d.ts +48 -0
  138. package/storages/storage_stats.js +29 -0
  139. package/storages/throttling_request_manager.d.ts +239 -0
  140. package/storages/throttling_request_manager.js +646 -0
  141. package/storages/transaction.d.ts +252 -0
  142. package/storages/transaction.js +251 -0
  143. package/storages/utils.d.ts +59 -11
  144. package/storages/utils.js +75 -15
  145. package/system-info/cpu-info.d.ts +67 -0
  146. package/system-info/cpu-info.js +216 -0
  147. package/system-info/memory-info.d.ts +31 -0
  148. package/system-info/memory-info.js +115 -0
  149. package/system-info/ps-tree.d.ts +17 -0
  150. package/system-info/ps-tree.js +144 -0
  151. package/system-info/runtime.d.ts +14 -0
  152. package/system-info/runtime.js +80 -0
  153. package/typedefs.d.ts +0 -6
  154. package/typedefs.js +0 -1
  155. package/url.d.ts +9 -0
  156. package/url.js +11 -0
  157. package/validators.d.ts +22 -18
  158. package/validators.js +13 -18
  159. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  160. package/autoscaling/autoscaled_pool.js.map +0 -1
  161. package/autoscaling/index.d.ts.map +0 -1
  162. package/autoscaling/index.js.map +0 -1
  163. package/autoscaling/snapshotter.d.ts.map +0 -1
  164. package/autoscaling/snapshotter.js.map +0 -1
  165. package/autoscaling/system_status.d.ts.map +0 -1
  166. package/autoscaling/system_status.js.map +0 -1
  167. package/configuration.d.ts.map +0 -1
  168. package/configuration.js.map +0 -1
  169. package/cookie_utils.d.ts.map +0 -1
  170. package/cookie_utils.js.map +0 -1
  171. package/crawlers/context_pipeline.d.ts.map +0 -1
  172. package/crawlers/context_pipeline.js.map +0 -1
  173. package/crawlers/crawler_commons.d.ts.map +0 -1
  174. package/crawlers/crawler_commons.js.map +0 -1
  175. package/crawlers/crawler_utils.d.ts +0 -10
  176. package/crawlers/crawler_utils.d.ts.map +0 -1
  177. package/crawlers/crawler_utils.js +0 -12
  178. package/crawlers/crawler_utils.js.map +0 -1
  179. package/crawlers/error_snapshotter.d.ts.map +0 -1
  180. package/crawlers/error_snapshotter.js.map +0 -1
  181. package/crawlers/error_tracker.d.ts.map +0 -1
  182. package/crawlers/error_tracker.js.map +0 -1
  183. package/crawlers/index.d.ts.map +0 -1
  184. package/crawlers/index.js.map +0 -1
  185. package/crawlers/internals/types.d.ts.map +0 -1
  186. package/crawlers/internals/types.js.map +0 -1
  187. package/crawlers/statistics.d.ts.map +0 -1
  188. package/crawlers/statistics.js.map +0 -1
  189. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  190. package/enqueue_links/enqueue_links.js.map +0 -1
  191. package/enqueue_links/index.d.ts.map +0 -1
  192. package/enqueue_links/index.js.map +0 -1
  193. package/enqueue_links/shared.d.ts.map +0 -1
  194. package/enqueue_links/shared.js.map +0 -1
  195. package/errors.d.ts.map +0 -1
  196. package/errors.js.map +0 -1
  197. package/events/event_manager.d.ts.map +0 -1
  198. package/events/event_manager.js.map +0 -1
  199. package/events/index.d.ts.map +0 -1
  200. package/events/index.js.map +0 -1
  201. package/events/local_event_manager.d.ts.map +0 -1
  202. package/events/local_event_manager.js.map +0 -1
  203. package/http_clients/base-http-client.d.ts +0 -140
  204. package/http_clients/base-http-client.d.ts.map +0 -1
  205. package/http_clients/base-http-client.js +0 -40
  206. package/http_clients/base-http-client.js.map +0 -1
  207. package/http_clients/form-data-like.d.ts +0 -67
  208. package/http_clients/form-data-like.d.ts.map +0 -1
  209. package/http_clients/form-data-like.js +0 -5
  210. package/http_clients/form-data-like.js.map +0 -1
  211. package/http_clients/got-scraping-http-client.d.ts +0 -20
  212. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  213. package/http_clients/got-scraping-http-client.js +0 -82
  214. package/http_clients/got-scraping-http-client.js.map +0 -1
  215. package/http_clients/index.d.ts +0 -3
  216. package/http_clients/index.d.ts.map +0 -1
  217. package/http_clients/index.js +0 -3
  218. package/http_clients/index.js.map +0 -1
  219. package/index.d.ts.map +0 -1
  220. package/index.js.map +0 -1
  221. package/log.d.ts.map +0 -1
  222. package/log.js.map +0 -1
  223. package/proxy_configuration.d.ts.map +0 -1
  224. package/proxy_configuration.js.map +0 -1
  225. package/request.d.ts.map +0 -1
  226. package/request.js.map +0 -1
  227. package/router.d.ts.map +0 -1
  228. package/router.js.map +0 -1
  229. package/serialization.d.ts.map +0 -1
  230. package/serialization.js.map +0 -1
  231. package/session_pool/consts.d.ts.map +0 -1
  232. package/session_pool/consts.js.map +0 -1
  233. package/session_pool/errors.d.ts.map +0 -1
  234. package/session_pool/errors.js.map +0 -1
  235. package/session_pool/events.d.ts +0 -3
  236. package/session_pool/events.d.ts.map +0 -1
  237. package/session_pool/events.js +0 -3
  238. package/session_pool/events.js.map +0 -1
  239. package/session_pool/index.d.ts.map +0 -1
  240. package/session_pool/index.js.map +0 -1
  241. package/session_pool/session.d.ts.map +0 -1
  242. package/session_pool/session.js.map +0 -1
  243. package/session_pool/session_pool.d.ts.map +0 -1
  244. package/session_pool/session_pool.js.map +0 -1
  245. package/storages/access_checking.d.ts +0 -13
  246. package/storages/access_checking.d.ts.map +0 -1
  247. package/storages/access_checking.js +0 -14
  248. package/storages/access_checking.js.map +0 -1
  249. package/storages/dataset.d.ts.map +0 -1
  250. package/storages/dataset.js.map +0 -1
  251. package/storages/index.d.ts.map +0 -1
  252. package/storages/index.js.map +0 -1
  253. package/storages/key_value_store.d.ts.map +0 -1
  254. package/storages/key_value_store.js.map +0 -1
  255. package/storages/request_list.d.ts.map +0 -1
  256. package/storages/request_list.js.map +0 -1
  257. package/storages/request_provider.d.ts +0 -308
  258. package/storages/request_provider.d.ts.map +0 -1
  259. package/storages/request_provider.js +0 -555
  260. package/storages/request_provider.js.map +0 -1
  261. package/storages/request_queue.d.ts.map +0 -1
  262. package/storages/request_queue.js.map +0 -1
  263. package/storages/request_queue_v2.d.ts +0 -87
  264. package/storages/request_queue_v2.d.ts.map +0 -1
  265. package/storages/request_queue_v2.js +0 -438
  266. package/storages/request_queue_v2.js.map +0 -1
  267. package/storages/sitemap_request_list.d.ts.map +0 -1
  268. package/storages/sitemap_request_list.js +0 -430
  269. package/storages/sitemap_request_list.js.map +0 -1
  270. package/storages/storage_manager.d.ts +0 -58
  271. package/storages/storage_manager.d.ts.map +0 -1
  272. package/storages/storage_manager.js +0 -105
  273. package/storages/storage_manager.js.map +0 -1
  274. package/storages/utils.d.ts.map +0 -1
  275. package/storages/utils.js.map +0 -1
  276. package/tsconfig.build.tsbuildinfo +0 -1
  277. package/typedefs.d.ts.map +0 -1
  278. package/typedefs.js.map +0 -1
  279. package/validators.d.ts.map +0 -1
  280. package/validators.js.map +0 -1
package/log.js CHANGED
@@ -1,3 +1,108 @@
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
+ // kept as TS-private: the adaptive crawler's log proxy calls non-intercepted methods with `this === proxy`,
34
+ // where `#`-field access would throw at runtime
35
+ options;
36
+ warningsLogged = new Set();
37
+ constructor(options = {}) {
38
+ this.options = options;
39
+ }
40
+ getOptions() {
41
+ return this.options;
42
+ }
43
+ setOptions(options) {
44
+ this.options = { ...this.options, ...options };
45
+ }
46
+ child(options) {
47
+ return this.createChild(options);
48
+ }
49
+ error(message, data) {
50
+ this.logWithLevel(LogLevel.ERROR, message, data);
51
+ }
52
+ exception(exception, message, data) {
53
+ this.logWithLevel(LogLevel.ERROR, `${message}: ${exception.message}`, {
54
+ ...data,
55
+ stack: exception.stack,
56
+ exception,
57
+ });
58
+ }
59
+ softFail(message, data) {
60
+ this.logWithLevel(LogLevel.SOFT_FAIL, message, data);
61
+ }
62
+ warning(message, data) {
63
+ this.logWithLevel(LogLevel.WARNING, message, data);
64
+ }
65
+ warningOnce(message) {
66
+ if (!this.warningsLogged.has(message)) {
67
+ this.warningsLogged.add(message);
68
+ this.warning(message);
69
+ }
70
+ }
71
+ info(message, data) {
72
+ this.logWithLevel(LogLevel.INFO, message, data);
73
+ }
74
+ debug(message, data) {
75
+ this.logWithLevel(LogLevel.DEBUG, message, data);
76
+ }
77
+ perf(message, data) {
78
+ this.logWithLevel(LogLevel.PERF, `[PERF] ${message}`, data);
79
+ }
80
+ deprecated(message) {
81
+ this.warningOnce(`[DEPRECATED] ${message}`);
82
+ }
83
+ }
84
+ /**
85
+ * Adapter that wraps `@apify/log`'s {@link Log} instance to implement the {@link CrawleeLogger} interface.
86
+ *
87
+ * This is the default logger used by Crawlee when no custom logger is configured.
88
+ * Users who want to use a different logging library should implement {@link BaseCrawleeLogger} directly.
89
+ */
90
+ export class ApifyLogAdapter extends BaseCrawleeLogger {
91
+ apifyLog;
92
+ constructor(
93
+ // kept as a TS-private parameter property: reached through the adaptive crawler's log proxy, see above
94
+ apifyLog, options) {
95
+ super(options ?? {});
96
+ this.apifyLog = apifyLog;
97
+ }
98
+ logWithLevel(level, message, data) {
99
+ this.apifyLog.internal(level, message, data);
100
+ }
101
+ createChild(options) {
102
+ return new ApifyLogAdapter(this.apifyLog.child({ prefix: options.prefix ?? null }), {
103
+ ...this.getOptions(),
104
+ ...options,
105
+ });
106
+ }
107
+ }
2
108
  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,38 @@
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
+ #private;
14
+ readonly logger?: CrawleeLogger;
15
+ readonly keyValueStoreBackendCache: KeyValueStoreBackend[];
16
+ readonly datasetBackendCache: DatasetBackend[];
17
+ readonly requestQueueBackendCache: RequestQueueBackend[];
18
+ constructor(options?: MemoryStorageOptions);
19
+ /**
20
+ * Return a per-instance unique cache key so that distinct `MemoryStorageBackend` instances get separate
21
+ * cache partitions in the storage backend cache.
22
+ */
23
+ getStorageBackendCacheKey(): string;
24
+ createDatasetBackend(options?: storage.StorageIdentifier): Promise<storage.DatasetBackend>;
25
+ createKeyValueStoreBackend(options?: storage.StorageIdentifier): Promise<storage.KeyValueStoreBackend>;
26
+ createRequestQueueBackend(options?: storage.StorageIdentifier): Promise<RequestQueueBackend>;
27
+ storageExists(id: string, type: 'Dataset' | 'KeyValueStore' | 'RequestQueue'): Promise<boolean>;
28
+ /**
29
+ * Cleans up the run-scoped storages before the run starts. For the in-memory storage this simply
30
+ * resets the in-memory state of the cached backends.
31
+ */
32
+ purge(): Promise<void>;
33
+ /**
34
+ * This method should be called at the end of the process. The in-memory storage holds no resources
35
+ * that outlive the process (no file handles, no cross-process locks), so there is nothing to do.
36
+ */
37
+ teardown(): Promise<void>;
38
+ }
@@ -0,0 +1,130 @@
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
+ /** The alias the default (unnamed) storage is opened under. */
6
+ const DEFAULT_STORAGE_ALIAS = '__default__';
7
+ export class MemoryStorageBackend {
8
+ logger;
9
+ /**
10
+ * Unique per-instance cache partition key. Mirrors the way `FileSystemStorageBackend` partitions its
11
+ * cache by storage directory: two distinct `MemoryStorageBackend` instances must not share cached backends.
12
+ */
13
+ #instanceCacheKey = `MemoryStorageBackend:${randomUUID()}`;
14
+ keyValueStoreBackendCache = [];
15
+ datasetBackendCache = [];
16
+ requestQueueBackendCache = [];
17
+ constructor(options = {}) {
18
+ this.logger = options.logger;
19
+ }
20
+ /**
21
+ * Return a per-instance unique cache key so that distinct `MemoryStorageBackend` instances get separate
22
+ * cache partitions in the storage backend cache.
23
+ */
24
+ getStorageBackendCacheKey() {
25
+ return this.#instanceCacheKey;
26
+ }
27
+ static #resolveStorageKey(options) {
28
+ // No identifier at all means the default storage, which is opened under the reserved alias —
29
+ // same rule as `resolveStorageIdentifier` in the storage frontends, so that a backend used
30
+ // directly lands on the very storage the frontends would have opened.
31
+ const alias = options.alias || (!options.id && !options.name ? DEFAULT_STORAGE_ALIAS : undefined);
32
+ // `alias` covers the identifier-less case, so one of the three is always set.
33
+ const rawKey = alias ?? options.name ?? options.id;
34
+ // Normalize the internal __default__ alias to the user-facing 'default' name.
35
+ const cacheKey = rawKey === DEFAULT_STORAGE_ALIAS ? 'default' : rawKey;
36
+ return { isAlias: alias !== undefined, cacheKey };
37
+ }
38
+ async createDatasetBackend(options = {}) {
39
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
40
+ const found = this.datasetBackendCache.find((store) => store.id === cacheKey ||
41
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
42
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
43
+ if (found) {
44
+ return found;
45
+ }
46
+ const newStore = new DatasetBackend({
47
+ name: isAlias ? undefined : cacheKey,
48
+ cacheKey,
49
+ storageBackend: this,
50
+ });
51
+ this.datasetBackendCache.push(newStore);
52
+ return newStore;
53
+ }
54
+ async createKeyValueStoreBackend(options = {}) {
55
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
56
+ const found = this.keyValueStoreBackendCache.find((store) => store.id === cacheKey ||
57
+ store.name?.toLowerCase() === cacheKey.toLowerCase() ||
58
+ store.cacheKey.toLowerCase() === cacheKey.toLowerCase());
59
+ if (found) {
60
+ return found;
61
+ }
62
+ const newStore = new KeyValueStoreBackend({
63
+ name: isAlias ? undefined : cacheKey,
64
+ cacheKey,
65
+ storageBackend: this,
66
+ });
67
+ this.keyValueStoreBackendCache.push(newStore);
68
+ return newStore;
69
+ }
70
+ async createRequestQueueBackend(options = {}) {
71
+ const { isAlias, cacheKey } = MemoryStorageBackend.#resolveStorageKey(options);
72
+ const found = this.requestQueueBackendCache.find((queue) => queue.id === cacheKey ||
73
+ queue.name?.toLowerCase() === cacheKey.toLowerCase() ||
74
+ queue.cacheKey.toLowerCase() === cacheKey.toLowerCase());
75
+ if (found) {
76
+ return found;
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 run-scoped storages before the run starts. For the in-memory storage this simply
106
+ * resets the in-memory state of the cached backends.
107
+ */
108
+ async purge() {
109
+ // `#resolveStorageKey` leaves `name` unset for the default and alias-keyed storages, which is what
110
+ // marks them as run-scoped. `'default'` is the exception — it collapses onto the default storage.
111
+ const isRunScoped = (store) => store.name === undefined || store.name === 'default';
112
+ const isDefault = (store) => store.name === 'default' || store.cacheKey === 'default';
113
+ const purgeRunScoped = async (cache, purgeStore) => {
114
+ await Promise.all(cache.filter(isRunScoped).map(async (store) => purgeStore(store)));
115
+ };
116
+ await Promise.all([
117
+ // Only the default store holds the run input, so it is the only one that keeps `INPUT`.
118
+ purgeRunScoped(this.keyValueStoreBackendCache, async (store) => isDefault(store) ? store.purgeExceptInput() : store.purge()),
119
+ purgeRunScoped(this.datasetBackendCache, async (store) => store.purge()),
120
+ purgeRunScoped(this.requestQueueBackendCache, async (store) => store.purge()),
121
+ ]);
122
+ }
123
+ /**
124
+ * This method should be called at the end of the process. The in-memory storage holds no resources
125
+ * that outlive the process (no file handles, no cross-process locks), so there is nothing to do.
126
+ */
127
+ async teardown() {
128
+ // Nothing to tear down for in-memory storage.
129
+ }
130
+ }
@@ -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
+ #private;
18
+ name?: string;
19
+ /**
20
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
21
+ * storages, this is the alias string. Falls back to id.
22
+ */
23
+ cacheKey: string;
24
+ createdAt: Date;
25
+ accessedAt: Date;
26
+ modifiedAt: Date;
27
+ itemCount: number;
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
+ }
@@ -0,0 +1,108 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
3
+ import { BaseClient } from './common/base-client.js';
4
+ /**
5
+ * This is what API returns in the x-apify-pagination-limit
6
+ * header when no limit query parameter is used.
7
+ */
8
+ const LIST_ITEMS_LIMIT = 999_999_999_999;
9
+ /**
10
+ * Number of characters of the dataset item entry names.
11
+ * E.g.: 000000019 - 9 digits
12
+ */
13
+ const LOCAL_ENTRY_NAME_DIGITS = 9;
14
+ export class DatasetBackend extends BaseClient {
15
+ name;
16
+ /**
17
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
18
+ * storages, this is the alias string. Falls back to id.
19
+ */
20
+ cacheKey;
21
+ createdAt = new Date();
22
+ accessedAt = new Date();
23
+ modifiedAt = new Date();
24
+ itemCount = 0;
25
+ #datasetEntries = new Map();
26
+ // kept as TS-private: storage-backend tests read this field at runtime
27
+ storageBackend;
28
+ constructor(options) {
29
+ super(options.id ?? randomUUID());
30
+ this.name = options.name;
31
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
32
+ this.storageBackend = options.storageBackend;
33
+ }
34
+ async getMetadata() {
35
+ this.updateTimestamps(false);
36
+ return this.toDatasetInfo();
37
+ }
38
+ async drop() {
39
+ const storeIndex = this.storageBackend.datasetBackendCache.findIndex((store) => store.id === this.id);
40
+ if (storeIndex !== -1) {
41
+ const [oldBackend] = this.storageBackend.datasetBackendCache.splice(storeIndex, 1);
42
+ oldBackend.itemCount = 0;
43
+ oldBackend.#datasetEntries.clear();
44
+ }
45
+ }
46
+ async purge() {
47
+ this.itemCount = 0;
48
+ this.#datasetEntries.clear();
49
+ this.updateTimestamps(true);
50
+ }
51
+ getData(options = {}) {
52
+ const { desc, limit, offset } = parseArgument(options, schemas.datasetListItemsOptions);
53
+ return this.getDataPage({
54
+ desc,
55
+ offset: offset ?? 0,
56
+ limit: Math.min(limit ?? LIST_ITEMS_LIMIT, LIST_ITEMS_LIMIT),
57
+ });
58
+ }
59
+ async getDataPage(options = {}) {
60
+ const { limit = LIST_ITEMS_LIMIT, offset = 0, desc } = options;
61
+ const [start, end] = this.getStartAndEndIndexes(desc ? Math.max(this.itemCount - offset - limit, 0) : offset, limit);
62
+ const items = [];
63
+ for (let idx = start; idx < end; idx++) {
64
+ const entryNumber = this.generateLocalEntryName(idx);
65
+ items.push(this.#datasetEntries.get(entryNumber));
66
+ }
67
+ this.updateTimestamps(false);
68
+ return {
69
+ count: items.length,
70
+ desc: desc ?? false,
71
+ items: desc ? items.reverse() : items,
72
+ limit,
73
+ offset,
74
+ total: this.itemCount,
75
+ };
76
+ }
77
+ async pushData(items) {
78
+ for (const entry of items) {
79
+ const idx = this.generateLocalEntryName(++this.itemCount);
80
+ this.#datasetEntries.set(idx, JSON.parse(JSON.stringify(entry)));
81
+ }
82
+ this.updateTimestamps(true);
83
+ }
84
+ toDatasetInfo() {
85
+ return {
86
+ id: this.id,
87
+ accessedAt: this.accessedAt,
88
+ createdAt: this.createdAt,
89
+ itemCount: this.itemCount,
90
+ modifiedAt: this.modifiedAt,
91
+ name: this.name,
92
+ };
93
+ }
94
+ generateLocalEntryName(idx) {
95
+ return idx.toString().padStart(LOCAL_ENTRY_NAME_DIGITS, '0');
96
+ }
97
+ getStartAndEndIndexes(offset, limit = this.itemCount) {
98
+ const start = offset + 1;
99
+ const end = Math.min(offset + limit, this.itemCount) + 1;
100
+ return [start, end];
101
+ }
102
+ updateTimestamps(hasBeenModified) {
103
+ this.accessedAt = new Date();
104
+ if (hasBeenModified) {
105
+ this.modifiedAt = new Date();
106
+ }
107
+ }
108
+ }
@@ -0,0 +1,63 @@
1
+ import type * as storage from '@crawlee/types';
2
+ import type { MemoryStorageBackend } from '../memory-storage.js';
3
+ import { BaseClient } from './common/base-client.js';
4
+ export interface KeyValueStoreBackendOptions {
5
+ name?: string;
6
+ id?: string;
7
+ /**
8
+ * The key used for cache lookup. When provided, takes precedence over `name` and `id`.
9
+ * This allows alias-opened storages to have a cache key that differs from their
10
+ * metadata `name` (which is `undefined` for unnamed storages).
11
+ */
12
+ cacheKey?: string;
13
+ storageBackend: MemoryStorageBackend;
14
+ }
15
+ export interface InternalKeyRecord {
16
+ key: string;
17
+ value: Buffer;
18
+ contentType?: string;
19
+ extension: string;
20
+ }
21
+ export declare class KeyValueStoreBackend extends BaseClient implements storage.KeyValueStoreBackend {
22
+ #private;
23
+ name?: string;
24
+ /**
25
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
26
+ * storages, this is the alias string. Falls back to id.
27
+ */
28
+ cacheKey: string;
29
+ createdAt: Date;
30
+ accessedAt: Date;
31
+ modifiedAt: Date;
32
+ private readonly storageBackend;
33
+ constructor(options: KeyValueStoreBackendOptions);
34
+ getMetadata(): Promise<storage.KeyValueStoreInfo>;
35
+ drop(): Promise<void>;
36
+ purge(): Promise<void>;
37
+ /**
38
+ * Purges every record except the run's input. Used by {@link MemoryStorageBackend.purge} for the
39
+ * default key-value store, mirroring `FileSystemStorageBackend`, which preserves `INPUT` (and its
40
+ * extension variants) when purging the default store. The in-memory key has no extension, so we
41
+ * preserve the bare `INPUT` key only.
42
+ */
43
+ purgeExceptInput(): Promise<void>;
44
+ listKeys(options?: storage.KeyValueStoreListKeysOptions): Promise<storage.KeyValueStoreListKeysResult>;
45
+ /**
46
+ * In-memory records are not file-backed, so there is no public file URL to return.
47
+ * Always resolves to `undefined`.
48
+ * @param key The key of the record to generate the public URL for.
49
+ */
50
+ getPublicUrl(key: string): Promise<string | undefined>;
51
+ /**
52
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
53
+ *
54
+ * @param key The queried record key.
55
+ * @returns `true` if the record exists, `false` if it does not.
56
+ */
57
+ recordExists(key: string): Promise<boolean>;
58
+ getValue(key: string): Promise<storage.KeyValueStoreRecord | undefined>;
59
+ setValue(record: storage.KeyValueStoreInputRecord): Promise<void>;
60
+ deleteValue(key: string): Promise<void>;
61
+ toKeyValueStoreInfo(): storage.KeyValueStoreInfo;
62
+ private updateTimestamps;
63
+ }