@crawlee/core 4.0.0-beta.21 → 4.0.0-beta.210

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 +88 -227
  5. package/configuration.js +162 -226
  6. package/debug.d.ts +36 -0
  7. package/debug.js +70 -0
  8. package/errors.d.ts +45 -18
  9. package/errors.js +58 -27
  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 +43 -0
  31. package/memory-storage/memory-storage.js +158 -0
  32. package/memory-storage/resource-clients/common/base-client.d.ts +4 -0
  33. package/memory-storage/resource-clients/common/base-client.js +6 -0
  34. package/memory-storage/resource-clients/dataset.d.ts +40 -0
  35. package/memory-storage/resource-clients/dataset.js +106 -0
  36. package/memory-storage/resource-clients/key-value-store.d.ts +56 -0
  37. package/memory-storage/resource-clients/key-value-store.js +180 -0
  38. package/memory-storage/resource-clients/request-queue.d.ts +77 -0
  39. package/memory-storage/resource-clients/request-queue.js +414 -0
  40. package/memory-storage/utils.d.ts +16 -0
  41. package/memory-storage/utils.js +41 -0
  42. package/owned_or_injected.d.ts +58 -0
  43. package/owned_or_injected.js +98 -0
  44. package/package.json +19 -20
  45. package/proxy_configuration.d.ts +28 -77
  46. package/proxy_configuration.js +37 -146
  47. package/recoverable_state.d.ts +106 -52
  48. package/recoverable_state.js +200 -72
  49. package/request.d.ts +48 -93
  50. package/request.js +112 -230
  51. package/serialization.d.ts +0 -1
  52. package/serialization.js +18 -18
  53. package/service_locator.d.ts +168 -0
  54. package/service_locator.js +255 -0
  55. package/storages/batched_adds.d.ts +37 -0
  56. package/storages/batched_adds.js +73 -0
  57. package/storages/dataset.d.ts +115 -58
  58. package/storages/dataset.js +291 -149
  59. package/storages/index.d.ts +8 -9
  60. package/storages/index.js +4 -9
  61. package/storages/key_value_store.d.ts +186 -71
  62. package/storages/key_value_store.js +449 -194
  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 +50 -133
  68. package/storages/request_list.js +269 -248
  69. package/storages/request_loader.d.ts +127 -0
  70. package/storages/request_loader.js +36 -0
  71. package/storages/request_manager.d.ts +119 -0
  72. package/storages/request_manager.js +1 -0
  73. package/storages/request_manager_tandem.d.ts +50 -24
  74. package/storages/request_manager_tandem.js +134 -58
  75. package/storages/request_queue.d.ts +293 -48
  76. package/storages/request_queue.js +766 -216
  77. package/storages/storage_instance_manager.d.ts +86 -0
  78. package/storages/storage_instance_manager.js +256 -0
  79. package/storages/storage_stats.d.ts +48 -0
  80. package/storages/storage_stats.js +29 -0
  81. package/storages/transaction.d.ts +271 -0
  82. package/storages/transaction.js +296 -0
  83. package/storages/utils.d.ts +59 -11
  84. package/storages/utils.js +75 -15
  85. package/system-info/cpu-info.d.ts +67 -0
  86. package/system-info/cpu-info.js +216 -0
  87. package/system-info/memory-info.d.ts +31 -0
  88. package/system-info/memory-info.js +115 -0
  89. package/system-info/ps-tree.d.ts +17 -0
  90. package/system-info/ps-tree.js +144 -0
  91. package/system-info/runtime.d.ts +14 -0
  92. package/system-info/runtime.js +80 -0
  93. package/typedefs.d.ts +0 -6
  94. package/typedefs.js +0 -1
  95. package/url.d.ts +9 -0
  96. package/url.js +11 -0
  97. package/validators.d.ts +23 -18
  98. package/validators.js +14 -18
  99. package/autoscaling/autoscaled_pool.d.ts +0 -300
  100. package/autoscaling/autoscaled_pool.d.ts.map +0 -1
  101. package/autoscaling/autoscaled_pool.js +0 -533
  102. package/autoscaling/autoscaled_pool.js.map +0 -1
  103. package/autoscaling/index.d.ts +0 -4
  104. package/autoscaling/index.d.ts.map +0 -1
  105. package/autoscaling/index.js +0 -4
  106. package/autoscaling/index.js.map +0 -1
  107. package/autoscaling/snapshotter.d.ts +0 -189
  108. package/autoscaling/snapshotter.d.ts.map +0 -1
  109. package/autoscaling/snapshotter.js +0 -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 -194
  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 -213
  150. package/crawlers/statistics.d.ts.map +0 -1
  151. package/crawlers/statistics.js +0 -349
  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 -12
  174. package/http_clients/base-http-client.d.ts.map +0 -1
  175. package/http_clients/base-http-client.js +0 -44
  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 -22
  182. package/http_clients/got-scraping-http-client.d.ts.map +0 -1
  183. package/http_clients/got-scraping-http-client.js +0 -116
  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 -186
  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 -372
  248. package/storages/request_provider.d.ts.map +0 -1
  249. package/storages/request_provider.js +0 -591
  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 -250
  258. package/storages/sitemap_request_list.d.ts.map +0 -1
  259. package/storages/sitemap_request_list.js +0 -431
  260. package/storages/sitemap_request_list.js.map +0 -1
  261. package/storages/storage_manager.d.ts +0 -62
  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,56 @@
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
+ listKeys(options?: storage.KeyValueStoreListKeysOptions): Promise<storage.KeyValueStoreListKeysResult>;
38
+ /**
39
+ * In-memory records are not file-backed, so there is no public file URL to return.
40
+ * Always resolves to `undefined`.
41
+ * @param key The key of the record to generate the public URL for.
42
+ */
43
+ getPublicUrl(key: string): Promise<string | undefined>;
44
+ /**
45
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
46
+ *
47
+ * @param key The queried record key.
48
+ * @returns `true` if the record exists, `false` if it does not.
49
+ */
50
+ recordExists(key: string): Promise<boolean>;
51
+ getValue(key: string): Promise<storage.KeyValueStoreRecord | undefined>;
52
+ setValue(record: storage.KeyValueStoreInputRecord): Promise<void>;
53
+ deleteValue(key: string): Promise<void>;
54
+ toKeyValueStoreInfo(): storage.KeyValueStoreInfo;
55
+ private updateTimestamps;
56
+ }
@@ -0,0 +1,180 @@
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
+ export class KeyValueStoreBackend extends BaseClient {
24
+ name;
25
+ /**
26
+ * The key used for cache lookup. For named storages, this equals the name. For alias (unnamed)
27
+ * storages, this is the alias string. Falls back to id.
28
+ */
29
+ cacheKey;
30
+ createdAt = new Date();
31
+ accessedAt = new Date();
32
+ modifiedAt = new Date();
33
+ #keyValueEntries = new Map();
34
+ // kept as TS-private: storage-backend tests read this field at runtime
35
+ storageBackend;
36
+ constructor(options) {
37
+ super(options.id ?? randomUUID());
38
+ this.name = options.name;
39
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
40
+ this.storageBackend = options.storageBackend;
41
+ }
42
+ async getMetadata() {
43
+ this.updateTimestamps(false);
44
+ return this.toKeyValueStoreInfo();
45
+ }
46
+ async drop() {
47
+ if (this.storageBackend.evictBackend('KeyValueStore', this.id)) {
48
+ this.#keyValueEntries.clear();
49
+ }
50
+ }
51
+ async purge() {
52
+ this.#keyValueEntries.clear();
53
+ this.updateTimestamps(true);
54
+ }
55
+ async listKeys(options = {}) {
56
+ const { prefix, exclusiveStartKey, limit } = parseArgument(options, schemas.keyValueStoreListKeysOptions);
57
+ const items = [];
58
+ for (const record of this.#keyValueEntries.values()) {
59
+ const size = Buffer.byteLength(record.value);
60
+ items.push({
61
+ key: record.key,
62
+ size,
63
+ contentType: record.contentType ?? 'application/octet-stream',
64
+ });
65
+ }
66
+ // Lexically sort to emulate API.
67
+ items.sort((a, b) => a.key.localeCompare(b.key));
68
+ let filteredItems = items.filter((item) => !prefix || item.key.startsWith(prefix));
69
+ if (exclusiveStartKey) {
70
+ const keyPos = filteredItems.findIndex((item) => item.key === exclusiveStartKey);
71
+ if (keyPos === -1) {
72
+ throw new Error(`exclusiveStartKey "${exclusiveStartKey}" was not found in the key-value store. ` +
73
+ `This is likely a bug — the key may have been deleted between paginated listKeys calls.`);
74
+ }
75
+ filteredItems = filteredItems.slice(keyPos + 1);
76
+ }
77
+ const isTruncated = limit !== undefined && filteredItems.length > limit;
78
+ const pageItems = isTruncated ? filteredItems.slice(0, limit) : filteredItems;
79
+ const nextExclusiveStartKey = isTruncated ? pageItems[pageItems.length - 1].key : undefined;
80
+ this.updateTimestamps(false);
81
+ return {
82
+ items: pageItems,
83
+ count: pageItems.length,
84
+ limit: limit ?? pageItems.length,
85
+ exclusiveStartKey,
86
+ isTruncated,
87
+ nextExclusiveStartKey,
88
+ };
89
+ }
90
+ /**
91
+ * In-memory records are not file-backed, so there is no public file URL to return.
92
+ * Always resolves to `undefined`.
93
+ * @param key The key of the record to generate the public URL for.
94
+ */
95
+ async getPublicUrl(key) {
96
+ parseArgument(key, keySchema);
97
+ return undefined;
98
+ }
99
+ /**
100
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
101
+ *
102
+ * @param key The queried record key.
103
+ * @returns `true` if the record exists, `false` if it does not.
104
+ */
105
+ async recordExists(key) {
106
+ parseArgument(key, keySchema);
107
+ return this.#keyValueEntries.has(key);
108
+ }
109
+ async getValue(key) {
110
+ parseArgument(key, keySchema);
111
+ const entry = this.#keyValueEntries.get(key);
112
+ if (!entry) {
113
+ return undefined;
114
+ }
115
+ // Return raw bytes + verbatim content type. Parsing is the frontend's job (see the
116
+ // KeyValueStore codec). The mime fallback reconstructs the content type for on-disk records.
117
+ const record = {
118
+ key: entry.key,
119
+ value: entry.value,
120
+ // mime.contentType returns `false` for unknown extensions; fall back to undefined so the
121
+ // frontend treats it as "no content type" rather than a bogus value.
122
+ contentType: entry.contentType ?? (mime.contentType(entry.extension) || undefined),
123
+ };
124
+ this.updateTimestamps(false);
125
+ return record;
126
+ }
127
+ async setValue(record) {
128
+ parseArgument(record, inputRecordSchema);
129
+ const { key } = record;
130
+ let { value } = record;
131
+ // The frontend (KeyValueStore codec) serializes the value and resolves its content type
132
+ // before it reaches the backend. We only need it here for on-disk extension bookkeeping.
133
+ const contentType = record.contentType ?? 'application/octet-stream';
134
+ const extension = mime.extension(contentType) || DEFAULT_LOCAL_FILE_EXTENSION;
135
+ // Draining a stream into a Buffer for storage is the backend's responsibility.
136
+ if (isStream(value)) {
137
+ const chunks = [];
138
+ for await (const chunk of value) {
139
+ chunks.push(chunk);
140
+ }
141
+ value = Buffer.concat(chunks);
142
+ }
143
+ // This backend is a byte transport: it stores and returns raw bytes regardless of the input
144
+ // shape. Streams were drained above; encode strings to UTF-8 bytes and normalize
145
+ // ArrayBuffer / typed-array views to a Buffer over the same memory.
146
+ const normalizedValue = typeof value === 'string'
147
+ ? Buffer.from(value, 'utf-8')
148
+ : toBuffer(value);
149
+ const normalizedRecord = {
150
+ extension,
151
+ key,
152
+ value: normalizedValue,
153
+ contentType,
154
+ };
155
+ this.#keyValueEntries.set(key, normalizedRecord);
156
+ this.updateTimestamps(true);
157
+ }
158
+ async deleteValue(key) {
159
+ parseArgument(key, keySchema);
160
+ if (this.#keyValueEntries.has(key)) {
161
+ this.#keyValueEntries.delete(key);
162
+ this.updateTimestamps(true);
163
+ }
164
+ }
165
+ toKeyValueStoreInfo() {
166
+ return {
167
+ id: this.id,
168
+ name: this.name,
169
+ accessedAt: this.accessedAt,
170
+ createdAt: this.createdAt,
171
+ modifiedAt: this.modifiedAt,
172
+ };
173
+ }
174
+ updateTimestamps(hasBeenModified) {
175
+ this.accessedAt = new Date();
176
+ if (hasBeenModified) {
177
+ this.modifiedAt = new Date();
178
+ }
179
+ }
180
+ }
@@ -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
+ }