@crawlee/core 4.0.0-beta.17 → 4.0.0-beta.171

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 (270) hide show
  1. package/README.md +14 -14
  2. package/byte_utils.d.ts +17 -0
  3. package/byte_utils.js +42 -0
  4. package/configuration.d.ts +96 -223
  5. package/configuration.js +170 -222
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +40 -19
  9. package/errors.js +53 -28
  10. package/events/event_manager.d.ts +35 -9
  11. package/events/event_manager.js +12 -13
  12. package/events/index.d.ts +1 -1
  13. package/events/index.js +0 -1
  14. package/events/local_event_manager.d.ts +15 -3
  15. package/events/local_event_manager.js +39 -13
  16. package/events/system_info.d.ts +38 -0
  17. package/events/system_info.js +1 -0
  18. package/index.d.ts +7 -11
  19. package/index.js +8 -10
  20. package/internal.d.ts +8 -0
  21. package/internal.js +9 -0
  22. package/iterables.d.ts +79 -0
  23. package/iterables.js +134 -0
  24. package/log.d.ts +77 -1
  25. package/log.js +134 -1
  26. package/memory-storage/consts.d.ts +4 -0
  27. package/memory-storage/consts.js +4 -0
  28. package/memory-storage/index.d.ts +1 -0
  29. package/memory-storage/index.js +1 -0
  30. package/memory-storage/memory-storage.d.ts +44 -0
  31. package/memory-storage/memory-storage.js +160 -0
  32. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  33. package/memory-storage/resource-clients/common/base-client.js +6 -0
  34. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  35. package/memory-storage/resource-clients/dataset.js +106 -0
  36. package/memory-storage/resource-clients/key-value-store.d.ts +63 -0
  37. package/memory-storage/resource-clients/key-value-store.js +199 -0
  38. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  39. package/memory-storage/resource-clients/request-queue.js +414 -0
  40. package/memory-storage/utils.d.ts +16 -0
  41. package/memory-storage/utils.js +41 -0
  42. package/owned_or_injected.d.ts +58 -0
  43. package/owned_or_injected.js +98 -0
  44. package/package.json +18 -19
  45. package/proxy_configuration.d.ts +22 -128
  46. package/proxy_configuration.js +32 -144
  47. package/recoverable_state.d.ts +84 -51
  48. package/recoverable_state.js +175 -72
  49. package/request.d.ts +60 -17
  50. package/request.js +130 -69
  51. package/serialization.d.ts +0 -1
  52. package/serialization.js +15 -15
  53. package/service_locator.d.ts +165 -0
  54. package/service_locator.js +253 -0
  55. package/storages/batched_adds.d.ts +37 -0
  56. package/storages/batched_adds.js +73 -0
  57. package/storages/dataset.d.ts +114 -56
  58. package/storages/dataset.js +292 -149
  59. package/storages/index.d.ts +7 -9
  60. package/storages/index.js +5 -9
  61. package/storages/key_value_store.d.ts +186 -48
  62. package/storages/key_value_store.js +452 -170
  63. package/storages/key_value_store_codec.d.ts +32 -0
  64. package/storages/key_value_store_codec.js +113 -0
  65. package/storages/request_dedup_cache.d.ts +22 -0
  66. package/storages/request_dedup_cache.js +48 -0
  67. package/storages/request_list.d.ts +54 -129
  68. package/storages/request_list.js +272 -245
  69. package/storages/request_loader.d.ts +133 -0
  70. package/storages/request_loader.js +36 -0
  71. package/storages/request_manager.d.ts +109 -0
  72. package/storages/request_manager.js +1 -0
  73. package/storages/request_manager_tandem.d.ts +55 -23
  74. package/storages/request_manager_tandem.js +139 -57
  75. package/storages/request_queue.d.ts +286 -48
  76. package/storages/request_queue.js +757 -218
  77. package/storages/storage_instance_manager.d.ts +87 -0
  78. package/storages/storage_instance_manager.js +256 -0
  79. package/storages/storage_stats.d.ts +48 -0
  80. package/storages/storage_stats.js +29 -0
  81. package/storages/transaction.d.ts +260 -0
  82. package/storages/transaction.js +287 -0
  83. package/storages/utils.d.ts +59 -11
  84. package/storages/utils.js +75 -15
  85. package/system-info/cpu-info.d.ts +67 -0
  86. package/system-info/cpu-info.js +216 -0
  87. package/system-info/memory-info.d.ts +31 -0
  88. package/system-info/memory-info.js +115 -0
  89. package/system-info/ps-tree.d.ts +17 -0
  90. package/system-info/ps-tree.js +144 -0
  91. package/system-info/runtime.d.ts +14 -0
  92. package/system-info/runtime.js +80 -0
  93. package/typedefs.d.ts +0 -6
  94. package/typedefs.js +0 -1
  95. package/url.d.ts +9 -0
  96. package/url.js +11 -0
  97. package/validators.d.ts +23 -18
  98. package/validators.js +14 -18
  99. package/autoscaling/autoscaled_pool.d.ts +0 -300
  100. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  101. package/autoscaling/autoscaled_pool.js +0 -533
  102. package/autoscaling/autoscaled_pool.js.map +0 -1
  103. package/autoscaling/index.d.ts +0 -4
  104. package/autoscaling/index.d.ts.map +0 -1
  105. package/autoscaling/index.js +0 -4
  106. package/autoscaling/index.js.map +0 -1
  107. package/autoscaling/snapshotter.d.ts +0 -189
  108. package/autoscaling/snapshotter.d.ts.map +0 -1
  109. package/autoscaling/snapshotter.js +0 -285
  110. package/autoscaling/snapshotter.js.map +0 -1
  111. package/autoscaling/system_status.d.ts +0 -181
  112. package/autoscaling/system_status.d.ts.map +0 -1
  113. package/autoscaling/system_status.js +0 -169
  114. package/autoscaling/system_status.js.map +0 -1
  115. package/configuration.d.ts.map +0 -1
  116. package/configuration.js.map +0 -1
  117. package/cookie_utils.d.ts +0 -43
  118. package/cookie_utils.d.ts.map +0 -1
  119. package/cookie_utils.js +0 -111
  120. package/cookie_utils.js.map +0 -1
  121. package/crawlers/context_pipeline.d.ts +0 -61
  122. package/crawlers/context_pipeline.d.ts.map +0 -1
  123. package/crawlers/context_pipeline.js +0 -99
  124. package/crawlers/context_pipeline.js.map +0 -1
  125. package/crawlers/crawler_commons.d.ts +0 -195
  126. package/crawlers/crawler_commons.d.ts.map +0 -1
  127. package/crawlers/crawler_commons.js +0 -108
  128. package/crawlers/crawler_commons.js.map +0 -1
  129. package/crawlers/crawler_utils.d.ts +0 -10
  130. package/crawlers/crawler_utils.d.ts.map +0 -1
  131. package/crawlers/crawler_utils.js +0 -12
  132. package/crawlers/crawler_utils.js.map +0 -1
  133. package/crawlers/error_snapshotter.d.ts +0 -60
  134. package/crawlers/error_snapshotter.d.ts.map +0 -1
  135. package/crawlers/error_snapshotter.js +0 -118
  136. package/crawlers/error_snapshotter.js.map +0 -1
  137. package/crawlers/error_tracker.d.ts +0 -55
  138. package/crawlers/error_tracker.d.ts.map +0 -1
  139. package/crawlers/error_tracker.js +0 -309
  140. package/crawlers/error_tracker.js.map +0 -1
  141. package/crawlers/index.d.ts +0 -7
  142. package/crawlers/index.d.ts.map +0 -1
  143. package/crawlers/index.js +0 -7
  144. package/crawlers/index.js.map +0 -1
  145. package/crawlers/internals/types.d.ts +0 -8
  146. package/crawlers/internals/types.d.ts.map +0 -1
  147. package/crawlers/internals/types.js +0 -2
  148. package/crawlers/internals/types.js.map +0 -1
  149. package/crawlers/statistics.d.ts +0 -204
  150. package/crawlers/statistics.d.ts.map +0 -1
  151. package/crawlers/statistics.js +0 -346
  152. package/crawlers/statistics.js.map +0 -1
  153. package/enqueue_links/enqueue_links.d.ts +0 -249
  154. package/enqueue_links/enqueue_links.d.ts.map +0 -1
  155. package/enqueue_links/enqueue_links.js +0 -269
  156. package/enqueue_links/enqueue_links.js.map +0 -1
  157. package/enqueue_links/index.d.ts +0 -3
  158. package/enqueue_links/index.d.ts.map +0 -1
  159. package/enqueue_links/index.js +0 -3
  160. package/enqueue_links/index.js.map +0 -1
  161. package/enqueue_links/shared.d.ts +0 -73
  162. package/enqueue_links/shared.d.ts.map +0 -1
  163. package/enqueue_links/shared.js +0 -212
  164. package/enqueue_links/shared.js.map +0 -1
  165. package/errors.d.ts.map +0 -1
  166. package/errors.js.map +0 -1
  167. package/events/event_manager.d.ts.map +0 -1
  168. package/events/event_manager.js.map +0 -1
  169. package/events/index.d.ts.map +0 -1
  170. package/events/index.js.map +0 -1
  171. package/events/local_event_manager.d.ts.map +0 -1
  172. package/events/local_event_manager.js.map +0 -1
  173. package/http_clients/base-http-client.d.ts +0 -140
  174. package/http_clients/base-http-client.d.ts.map +0 -1
  175. package/http_clients/base-http-client.js +0 -40
  176. package/http_clients/base-http-client.js.map +0 -1
  177. package/http_clients/form-data-like.d.ts +0 -67
  178. package/http_clients/form-data-like.d.ts.map +0 -1
  179. package/http_clients/form-data-like.js +0 -5
  180. package/http_clients/form-data-like.js.map +0 -1
  181. package/http_clients/got-scraping-http-client.d.ts +0 -20
  182. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  183. package/http_clients/got-scraping-http-client.js +0 -85
  184. package/http_clients/got-scraping-http-client.js.map +0 -1
  185. package/http_clients/index.d.ts +0 -3
  186. package/http_clients/index.d.ts.map +0 -1
  187. package/http_clients/index.js +0 -3
  188. package/http_clients/index.js.map +0 -1
  189. package/index.d.ts.map +0 -1
  190. package/index.js.map +0 -1
  191. package/log.d.ts.map +0 -1
  192. package/log.js.map +0 -1
  193. package/proxy_configuration.d.ts.map +0 -1
  194. package/proxy_configuration.js.map +0 -1
  195. package/recoverable_state.d.ts.map +0 -1
  196. package/recoverable_state.js.map +0 -1
  197. package/request.d.ts.map +0 -1
  198. package/request.js.map +0 -1
  199. package/router.d.ts +0 -134
  200. package/router.d.ts.map +0 -1
  201. package/router.js +0 -164
  202. package/router.js.map +0 -1
  203. package/serialization.d.ts.map +0 -1
  204. package/serialization.js.map +0 -1
  205. package/session_pool/consts.d.ts +0 -4
  206. package/session_pool/consts.d.ts.map +0 -1
  207. package/session_pool/consts.js +0 -4
  208. package/session_pool/consts.js.map +0 -1
  209. package/session_pool/errors.d.ts +0 -8
  210. package/session_pool/errors.d.ts.map +0 -1
  211. package/session_pool/errors.js +0 -12
  212. package/session_pool/errors.js.map +0 -1
  213. package/session_pool/events.d.ts +0 -3
  214. package/session_pool/events.d.ts.map +0 -1
  215. package/session_pool/events.js +0 -3
  216. package/session_pool/events.js.map +0 -1
  217. package/session_pool/index.d.ts +0 -6
  218. package/session_pool/index.d.ts.map +0 -1
  219. package/session_pool/index.js +0 -6
  220. package/session_pool/index.js.map +0 -1
  221. package/session_pool/session.d.ts +0 -203
  222. package/session_pool/session.d.ts.map +0 -1
  223. package/session_pool/session.js +0 -278
  224. package/session_pool/session.js.map +0 -1
  225. package/session_pool/session_pool.d.ts +0 -258
  226. package/session_pool/session_pool.d.ts.map +0 -1
  227. package/session_pool/session_pool.js +0 -387
  228. package/session_pool/session_pool.js.map +0 -1
  229. package/storages/access_checking.d.ts +0 -13
  230. package/storages/access_checking.d.ts.map +0 -1
  231. package/storages/access_checking.js +0 -14
  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_list_adapter.d.ts +0 -58
  242. package/storages/request_list_adapter.d.ts.map +0 -1
  243. package/storages/request_list_adapter.js +0 -81
  244. package/storages/request_list_adapter.js.map +0 -1
  245. package/storages/request_manager_tandem.d.ts.map +0 -1
  246. package/storages/request_manager_tandem.js.map +0 -1
  247. package/storages/request_provider.d.ts +0 -371
  248. package/storages/request_provider.d.ts.map +0 -1
  249. package/storages/request_provider.js +0 -585
  250. package/storages/request_provider.js.map +0 -1
  251. package/storages/request_queue.d.ts.map +0 -1
  252. package/storages/request_queue.js.map +0 -1
  253. package/storages/request_queue_v2.d.ts +0 -87
  254. package/storages/request_queue_v2.d.ts.map +0 -1
  255. package/storages/request_queue_v2.js +0 -438
  256. package/storages/request_queue_v2.js.map +0 -1
  257. package/storages/sitemap_request_list.d.ts +0 -245
  258. package/storages/sitemap_request_list.d.ts.map +0 -1
  259. package/storages/sitemap_request_list.js +0 -430
  260. package/storages/sitemap_request_list.js.map +0 -1
  261. package/storages/storage_manager.d.ts +0 -58
  262. package/storages/storage_manager.d.ts.map +0 -1
  263. package/storages/storage_manager.js +0 -105
  264. package/storages/storage_manager.js.map +0 -1
  265. package/storages/utils.d.ts.map +0 -1
  266. package/storages/utils.js.map +0 -1
  267. package/typedefs.d.ts.map +0 -1
  268. package/typedefs.js.map +0 -1
  269. package/validators.d.ts.map +0 -1
  270. package/validators.js.map +0 -1
@@ -0,0 +1,106 @@
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
+ if (this.storageBackend.evictBackend('Dataset', this.id)) {
40
+ this.itemCount = 0;
41
+ this.#datasetEntries.clear();
42
+ }
43
+ }
44
+ async purge() {
45
+ this.itemCount = 0;
46
+ this.#datasetEntries.clear();
47
+ this.updateTimestamps(true);
48
+ }
49
+ getData(options = {}) {
50
+ const { desc, limit, offset } = parseArgument(options, schemas.datasetListItemsOptions);
51
+ return this.getDataPage({
52
+ desc,
53
+ offset: offset ?? 0,
54
+ limit: Math.min(limit ?? LIST_ITEMS_LIMIT, LIST_ITEMS_LIMIT),
55
+ });
56
+ }
57
+ async getDataPage(options = {}) {
58
+ const { limit = LIST_ITEMS_LIMIT, offset = 0, desc } = options;
59
+ const [start, end] = this.getStartAndEndIndexes(desc ? Math.max(this.itemCount - offset - limit, 0) : offset, limit);
60
+ const items = [];
61
+ for (let idx = start; idx < end; idx++) {
62
+ const entryNumber = this.generateLocalEntryName(idx);
63
+ items.push(this.#datasetEntries.get(entryNumber));
64
+ }
65
+ this.updateTimestamps(false);
66
+ return {
67
+ count: items.length,
68
+ desc: desc ?? false,
69
+ items: desc ? items.reverse() : items,
70
+ limit,
71
+ offset,
72
+ total: this.itemCount,
73
+ };
74
+ }
75
+ async pushData(items) {
76
+ for (const entry of items) {
77
+ const idx = this.generateLocalEntryName(++this.itemCount);
78
+ this.#datasetEntries.set(idx, JSON.parse(JSON.stringify(entry)));
79
+ }
80
+ this.updateTimestamps(true);
81
+ }
82
+ toDatasetInfo() {
83
+ return {
84
+ id: this.id,
85
+ accessedAt: this.accessedAt,
86
+ createdAt: this.createdAt,
87
+ itemCount: this.itemCount,
88
+ modifiedAt: this.modifiedAt,
89
+ name: this.name,
90
+ };
91
+ }
92
+ generateLocalEntryName(idx) {
93
+ return idx.toString().padStart(LOCAL_ENTRY_NAME_DIGITS, '0');
94
+ }
95
+ getStartAndEndIndexes(offset, limit = this.itemCount) {
96
+ const start = offset + 1;
97
+ const end = Math.min(offset + limit, this.itemCount) + 1;
98
+ return [start, end];
99
+ }
100
+ updateTimestamps(hasBeenModified) {
101
+ this.accessedAt = new Date();
102
+ if (hasBeenModified) {
103
+ this.modifiedAt = new Date();
104
+ }
105
+ }
106
+ }
@@ -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
+ }
@@ -0,0 +1,199 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
3
+ import { z } from 'zod';
4
+ import { isStream, toBuffer } from '../utils.js';
5
+ import { BaseClient } from './common/base-client.js';
6
+ import mime from 'mime-types';
7
+ const DEFAULT_LOCAL_FILE_EXTENSION = 'bin';
8
+ const keySchema = z.string();
9
+ const inputRecordSchema = z.object({
10
+ key: z.string().min(1),
11
+ value: z.union([
12
+ z.null(),
13
+ z.string(),
14
+ z.number(),
15
+ z.instanceof(Buffer),
16
+ z.instanceof(ArrayBuffer),
17
+ schemas.typedArray,
18
+ // only checks the value is an actual object, not null, nor array
19
+ schemas.plainObject,
20
+ ]),
21
+ contentType: z.string().min(1).optional(),
22
+ });
23
+ /**
24
+ * Key under which a run's input is stored in the default key-value store. Matches Crawlee's default
25
+ * `inputKey` (`CRAWLEE_INPUT_KEY`) and the `INPUT` files `FileSystemStorageBackend` preserves on purge.
26
+ */
27
+ const KEY_VALUE_STORE_INPUT_KEY = 'INPUT';
28
+ export class KeyValueStoreBackend extends BaseClient {
29
+ name;
30
+ /**
31
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
32
+ * storages, this is the alias string. Falls back to id.
33
+ */
34
+ cacheKey;
35
+ createdAt = new Date();
36
+ accessedAt = new Date();
37
+ modifiedAt = new Date();
38
+ #keyValueEntries = new Map();
39
+ // kept as TS-private: storage-backend tests read this field at runtime
40
+ storageBackend;
41
+ constructor(options) {
42
+ super(options.id ?? randomUUID());
43
+ this.name = options.name;
44
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
45
+ this.storageBackend = options.storageBackend;
46
+ }
47
+ async getMetadata() {
48
+ this.updateTimestamps(false);
49
+ return this.toKeyValueStoreInfo();
50
+ }
51
+ async drop() {
52
+ if (this.storageBackend.evictBackend('KeyValueStore', this.id)) {
53
+ this.#keyValueEntries.clear();
54
+ }
55
+ }
56
+ async purge() {
57
+ this.#keyValueEntries.clear();
58
+ this.updateTimestamps(true);
59
+ }
60
+ /**
61
+ * Purges every record except the run's input. Used by {@link MemoryStorageBackend.purge} for the
62
+ * default key-value store, mirroring `FileSystemStorageBackend`, which preserves `INPUT` (and its
63
+ * extension variants) when purging the default store. The in-memory key has no extension, so we
64
+ * preserve the bare `INPUT` key only.
65
+ */
66
+ async purgeExceptInput() {
67
+ for (const key of this.#keyValueEntries.keys()) {
68
+ if (key !== KEY_VALUE_STORE_INPUT_KEY) {
69
+ this.#keyValueEntries.delete(key);
70
+ }
71
+ }
72
+ this.updateTimestamps(true);
73
+ }
74
+ async listKeys(options = {}) {
75
+ const { prefix, exclusiveStartKey, limit } = parseArgument(options, schemas.keyValueStoreListKeysOptions);
76
+ const items = [];
77
+ for (const record of this.#keyValueEntries.values()) {
78
+ const size = Buffer.byteLength(record.value);
79
+ items.push({
80
+ key: record.key,
81
+ size,
82
+ contentType: record.contentType ?? 'application/octet-stream',
83
+ });
84
+ }
85
+ // Lexically sort to emulate API.
86
+ items.sort((a, b) => a.key.localeCompare(b.key));
87
+ let filteredItems = items.filter((item) => !prefix || item.key.startsWith(prefix));
88
+ if (exclusiveStartKey) {
89
+ const keyPos = filteredItems.findIndex((item) => item.key === exclusiveStartKey);
90
+ if (keyPos === -1) {
91
+ throw new Error(`exclusiveStartKey "${exclusiveStartKey}" was not found in the key-value store. ` +
92
+ `This is likely a bug — the key may have been deleted between paginated listKeys calls.`);
93
+ }
94
+ filteredItems = filteredItems.slice(keyPos + 1);
95
+ }
96
+ const isTruncated = limit !== undefined && filteredItems.length > limit;
97
+ const pageItems = isTruncated ? filteredItems.slice(0, limit) : filteredItems;
98
+ const nextExclusiveStartKey = isTruncated ? pageItems[pageItems.length - 1].key : undefined;
99
+ this.updateTimestamps(false);
100
+ return {
101
+ items: pageItems,
102
+ count: pageItems.length,
103
+ limit: limit ?? pageItems.length,
104
+ exclusiveStartKey,
105
+ isTruncated,
106
+ nextExclusiveStartKey,
107
+ };
108
+ }
109
+ /**
110
+ * In-memory records are not file-backed, so there is no public file URL to return.
111
+ * Always resolves to `undefined`.
112
+ * @param key The key of the record to generate the public URL for.
113
+ */
114
+ async getPublicUrl(key) {
115
+ parseArgument(key, keySchema);
116
+ return undefined;
117
+ }
118
+ /**
119
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
120
+ *
121
+ * @param key The queried record key.
122
+ * @returns `true` if the record exists, `false` if it does not.
123
+ */
124
+ async recordExists(key) {
125
+ parseArgument(key, keySchema);
126
+ return this.#keyValueEntries.has(key);
127
+ }
128
+ async getValue(key) {
129
+ parseArgument(key, keySchema);
130
+ const entry = this.#keyValueEntries.get(key);
131
+ if (!entry) {
132
+ return undefined;
133
+ }
134
+ // Return raw bytes + verbatim content type. Parsing is the frontend's job (see the
135
+ // KeyValueStore codec). The mime fallback reconstructs the content type for on-disk records.
136
+ const record = {
137
+ key: entry.key,
138
+ value: entry.value,
139
+ // mime.contentType returns `false` for unknown extensions; fall back to undefined so the
140
+ // frontend treats it as "no content type" rather than a bogus value.
141
+ contentType: entry.contentType ?? (mime.contentType(entry.extension) || undefined),
142
+ };
143
+ this.updateTimestamps(false);
144
+ return record;
145
+ }
146
+ async setValue(record) {
147
+ parseArgument(record, inputRecordSchema);
148
+ const { key } = record;
149
+ let { value } = record;
150
+ // The frontend (KeyValueStore codec) serializes the value and resolves its content type
151
+ // before it reaches the backend. We only need it here for on-disk extension bookkeeping.
152
+ const contentType = record.contentType ?? 'application/octet-stream';
153
+ const extension = mime.extension(contentType) || DEFAULT_LOCAL_FILE_EXTENSION;
154
+ // Draining a stream into a Buffer for storage is the backend's responsibility.
155
+ if (isStream(value)) {
156
+ const chunks = [];
157
+ for await (const chunk of value) {
158
+ chunks.push(chunk);
159
+ }
160
+ value = Buffer.concat(chunks);
161
+ }
162
+ // This backend is a byte transport: it stores and returns raw bytes regardless of the input
163
+ // shape. Streams were drained above; encode strings to UTF-8 bytes and normalize
164
+ // ArrayBuffer / typed-array views to a Buffer over the same memory.
165
+ const normalizedValue = typeof value === 'string'
166
+ ? Buffer.from(value, 'utf-8')
167
+ : toBuffer(value);
168
+ const normalizedRecord = {
169
+ extension,
170
+ key,
171
+ value: normalizedValue,
172
+ contentType,
173
+ };
174
+ this.#keyValueEntries.set(key, normalizedRecord);
175
+ this.updateTimestamps(true);
176
+ }
177
+ async deleteValue(key) {
178
+ parseArgument(key, keySchema);
179
+ if (this.#keyValueEntries.has(key)) {
180
+ this.#keyValueEntries.delete(key);
181
+ this.updateTimestamps(true);
182
+ }
183
+ }
184
+ toKeyValueStoreInfo() {
185
+ return {
186
+ id: this.id,
187
+ name: this.name,
188
+ accessedAt: this.accessedAt,
189
+ createdAt: this.createdAt,
190
+ modifiedAt: this.modifiedAt,
191
+ };
192
+ }
193
+ updateTimestamps(hasBeenModified) {
194
+ this.accessedAt = new Date();
195
+ if (hasBeenModified) {
196
+ this.modifiedAt = new Date();
197
+ }
198
+ }
199
+ }
@@ -0,0 +1,77 @@
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 RequestQueueBackendOptions {
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 InternalRequest {
16
+ id: string;
17
+ orderNo: number | null;
18
+ url: string;
19
+ uniqueKey: string;
20
+ method: storage.RequestSchema['method'];
21
+ retryCount: number;
22
+ json: string;
23
+ }
24
+ export declare class RequestQueueBackend extends BaseClient implements storage.RequestQueueBackend {
25
+ #private;
26
+ name?: string;
27
+ /**
28
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
29
+ * storages, this is the alias string. Falls back to id.
30
+ */
31
+ cacheKey: string;
32
+ createdAt: Date;
33
+ accessedAt: Date;
34
+ modifiedAt: Date;
35
+ handledRequestCount: number;
36
+ pendingRequestCount: number;
37
+ private readonly storageBackend;
38
+ constructor(options: RequestQueueBackendOptions);
39
+ getMetadata(): Promise<storage.RequestQueueInfo>;
40
+ drop(): Promise<void>;
41
+ purge(): Promise<void>;
42
+ private requestKeyIterator;
43
+ /**
44
+ * Scans the queue and returns the pending head — requests that are neither handled nor currently
45
+ * in progress — ordered by `orderNo`, deduplicated.
46
+ *
47
+ * When `detectInProgressRequests` is set, the result also carries an `hasInProgressRequests` flag
48
+ * telling whether any unhandled-but-in-progress request was skipped along the way. It lets
49
+ * {@link isFinished} distinguish "no work left at all" from "work remains, but it is currently being
50
+ * processed". Without it, a consumer with concurrency could consider the queue finished and shut the
51
+ * crawler down while it is still handling the last requests.
52
+ *
53
+ * Computing the flag is expensive: because an in-progress request may sit anywhere in the queue, it
54
+ * forces a scan of every pending entry even when only `limit` items are wanted. Callers that only
55
+ * need the head (e.g. {@link fetchNextRequest}, {@link isEmpty}) leave it off so the scan can stop as
56
+ * soon as the page is filled, keeping those calls O(head) instead of O(pending).
57
+ */
58
+ private listPendingHead;
59
+ fetchNextRequest(): Promise<storage.UpdateRequestSchema | undefined>;
60
+ addBatchOfRequests(requests: storage.RequestSchema[], options?: storage.RequestQueueOperationOptions): Promise<storage.BatchAddRequestsResult>;
61
+ getRequest(uniqueKey: string): Promise<storage.UpdateRequestSchema | undefined>;
62
+ markRequestAsHandled(request: storage.UpdateRequestSchema): Promise<storage.QueueOperationInfo | undefined>;
63
+ reclaimRequest(request: storage.UpdateRequestSchema, options?: storage.RequestQueueOperationOptions): Promise<storage.QueueOperationInfo | undefined>;
64
+ isEmpty(): Promise<boolean>;
65
+ isFinished(): Promise<boolean>;
66
+ /**
67
+ * Returns all pending (not yet handled, not currently in progress) requests in the queue, ordered
68
+ * the same way {@link fetchNextRequest} would hand them out. This does not mutate the queue,
69
+ * nothing is marked in progress.
70
+ */
71
+ listItems(): Promise<storage.UpdateRequestSchema[]>;
72
+ toRequestQueueInfo(): storage.RequestQueueInfo;
73
+ private updateTimestamps;
74
+ private jsonToRequest;
75
+ private createInternalRequest;
76
+ private calculateOrderNo;
77
+ }