@crawlee/core 4.0.0-beta.22 → 4.0.0-beta.221

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 +15 -15
  2. package/byte_utils.d.ts +17 -0
  3. package/byte_utils.js +42 -0
  4. package/configuration.d.ts +77 -235
  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 +14 -9
  15. package/events/local_event_manager.js +45 -19
  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 +35 -0
  35. package/memory-storage/resource-clients/dataset.js +105 -0
  36. package/memory-storage/resource-clients/key-value-store.d.ts +54 -0
  37. package/memory-storage/resource-clients/key-value-store.js +179 -0
  38. package/memory-storage/resource-clients/request-queue.d.ts +55 -0
  39. package/memory-storage/resource-clients/request-queue.js +413 -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 +20 -21
  45. package/proxy_configuration.d.ts +28 -79
  46. package/proxy_configuration.js +40 -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 +105 -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 +169 -72
  62. package/storages/key_value_store.js +451 -196
  63. package/storages/key_value_store_codec.d.ts +32 -0
  64. package/storages/key_value_store_codec.js +108 -0
  65. package/storages/request_dedup_cache.d.ts +20 -0
  66. package/storages/request_dedup_cache.js +48 -0
  67. package/storages/request_list.d.ts +33 -173
  68. package/storages/request_list.js +275 -254
  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 +39 -25
  74. package/storages/request_manager_tandem.js +134 -58
  75. package/storages/request_queue.d.ts +261 -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 +270 -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 -113
  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,105 @@
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
+ #storageBackend;
27
+ constructor(options) {
28
+ super(options.id ?? randomUUID());
29
+ this.name = options.name;
30
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
31
+ this.#storageBackend = options.storageBackend;
32
+ }
33
+ async getMetadata() {
34
+ this.#updateTimestamps(false);
35
+ return this.toDatasetInfo();
36
+ }
37
+ async drop() {
38
+ if (this.#storageBackend.evictBackend('Dataset', this.id)) {
39
+ this.itemCount = 0;
40
+ this.#datasetEntries.clear();
41
+ }
42
+ }
43
+ async purge() {
44
+ this.itemCount = 0;
45
+ this.#datasetEntries.clear();
46
+ this.#updateTimestamps(true);
47
+ }
48
+ getData(options = {}) {
49
+ const { desc, limit, offset } = parseArgument(options, schemas.datasetListItemsOptions);
50
+ return this.#getDataPage({
51
+ desc,
52
+ offset: offset ?? 0,
53
+ limit: Math.min(limit ?? LIST_ITEMS_LIMIT, LIST_ITEMS_LIMIT),
54
+ });
55
+ }
56
+ async #getDataPage(options = {}) {
57
+ const { limit = LIST_ITEMS_LIMIT, offset = 0, desc } = options;
58
+ const [start, end] = this.#getStartAndEndIndexes(desc ? Math.max(this.itemCount - offset - limit, 0) : offset, limit);
59
+ const items = [];
60
+ for (let idx = start; idx < end; idx++) {
61
+ const entryNumber = this.#generateLocalEntryName(idx);
62
+ items.push(this.#datasetEntries.get(entryNumber));
63
+ }
64
+ this.#updateTimestamps(false);
65
+ return {
66
+ count: items.length,
67
+ desc: desc ?? false,
68
+ items: desc ? items.reverse() : items,
69
+ limit,
70
+ offset,
71
+ total: this.itemCount,
72
+ };
73
+ }
74
+ async pushData(items) {
75
+ for (const entry of items) {
76
+ const idx = this.#generateLocalEntryName(++this.itemCount);
77
+ this.#datasetEntries.set(idx, JSON.parse(JSON.stringify(entry)));
78
+ }
79
+ this.#updateTimestamps(true);
80
+ }
81
+ toDatasetInfo() {
82
+ return {
83
+ id: this.id,
84
+ accessedAt: this.accessedAt,
85
+ createdAt: this.createdAt,
86
+ itemCount: this.itemCount,
87
+ modifiedAt: this.modifiedAt,
88
+ name: this.name,
89
+ };
90
+ }
91
+ #generateLocalEntryName(idx) {
92
+ return idx.toString().padStart(LOCAL_ENTRY_NAME_DIGITS, '0');
93
+ }
94
+ #getStartAndEndIndexes(offset, limit = this.itemCount) {
95
+ const start = offset + 1;
96
+ const end = Math.min(offset + limit, this.itemCount) + 1;
97
+ return [start, end];
98
+ }
99
+ #updateTimestamps(hasBeenModified) {
100
+ this.accessedAt = new Date();
101
+ if (hasBeenModified) {
102
+ this.modifiedAt = new Date();
103
+ }
104
+ }
105
+ }
@@ -0,0 +1,54 @@
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
+ constructor(options: KeyValueStoreBackendOptions);
33
+ getMetadata(): Promise<storage.KeyValueStoreInfo>;
34
+ drop(): Promise<void>;
35
+ purge(): Promise<void>;
36
+ listKeys(options?: storage.KeyValueStoreListKeysOptions): Promise<storage.KeyValueStoreListKeysResult>;
37
+ /**
38
+ * In-memory records are not file-backed, so there is no public file URL to return.
39
+ * Always resolves to `undefined`.
40
+ * @param key The key of the record to generate the public URL for.
41
+ */
42
+ getPublicUrl(key: string): Promise<string | undefined>;
43
+ /**
44
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
45
+ *
46
+ * @param key The queried record key.
47
+ * @returns `true` if the record exists, `false` if it does not.
48
+ */
49
+ recordExists(key: string): Promise<boolean>;
50
+ getValue(key: string): Promise<storage.KeyValueStoreRecord | undefined>;
51
+ setValue(record: storage.KeyValueStoreInputRecord): Promise<void>;
52
+ deleteValue(key: string): Promise<void>;
53
+ toKeyValueStoreInfo(): storage.KeyValueStoreInfo;
54
+ }
@@ -0,0 +1,179 @@
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
+ #storageBackend;
35
+ constructor(options) {
36
+ super(options.id ?? randomUUID());
37
+ this.name = options.name;
38
+ this.cacheKey = options.cacheKey ?? this.name ?? this.id;
39
+ this.#storageBackend = options.storageBackend;
40
+ }
41
+ async getMetadata() {
42
+ this.#updateTimestamps(false);
43
+ return this.toKeyValueStoreInfo();
44
+ }
45
+ async drop() {
46
+ if (this.#storageBackend.evictBackend('KeyValueStore', this.id)) {
47
+ this.#keyValueEntries.clear();
48
+ }
49
+ }
50
+ async purge() {
51
+ this.#keyValueEntries.clear();
52
+ this.#updateTimestamps(true);
53
+ }
54
+ async listKeys(options = {}) {
55
+ const { prefix, exclusiveStartKey, limit } = parseArgument(options, schemas.keyValueStoreListKeysOptions);
56
+ const items = [];
57
+ for (const record of this.#keyValueEntries.values()) {
58
+ const size = Buffer.byteLength(record.value);
59
+ items.push({
60
+ key: record.key,
61
+ size,
62
+ contentType: record.contentType ?? 'application/octet-stream',
63
+ });
64
+ }
65
+ // Lexically sort to emulate API.
66
+ items.sort((a, b) => a.key.localeCompare(b.key));
67
+ let filteredItems = items.filter((item) => !prefix || item.key.startsWith(prefix));
68
+ if (exclusiveStartKey) {
69
+ const keyPos = filteredItems.findIndex((item) => item.key === exclusiveStartKey);
70
+ if (keyPos === -1) {
71
+ throw new Error(`exclusiveStartKey "${exclusiveStartKey}" was not found in the key-value store. ` +
72
+ `This is likely a bug — the key may have been deleted between paginated listKeys calls.`);
73
+ }
74
+ filteredItems = filteredItems.slice(keyPos + 1);
75
+ }
76
+ const isTruncated = limit !== undefined && filteredItems.length > limit;
77
+ const pageItems = isTruncated ? filteredItems.slice(0, limit) : filteredItems;
78
+ const nextExclusiveStartKey = isTruncated ? pageItems[pageItems.length - 1].key : undefined;
79
+ this.#updateTimestamps(false);
80
+ return {
81
+ items: pageItems,
82
+ count: pageItems.length,
83
+ limit: limit ?? pageItems.length,
84
+ exclusiveStartKey,
85
+ isTruncated,
86
+ nextExclusiveStartKey,
87
+ };
88
+ }
89
+ /**
90
+ * In-memory records are not file-backed, so there is no public file URL to return.
91
+ * Always resolves to `undefined`.
92
+ * @param key The key of the record to generate the public URL for.
93
+ */
94
+ async getPublicUrl(key) {
95
+ parseArgument(key, keySchema);
96
+ return undefined;
97
+ }
98
+ /**
99
+ * Tests whether a record with the given key exists in the key-value store without retrieving its value.
100
+ *
101
+ * @param key The queried record key.
102
+ * @returns `true` if the record exists, `false` if it does not.
103
+ */
104
+ async recordExists(key) {
105
+ parseArgument(key, keySchema);
106
+ return this.#keyValueEntries.has(key);
107
+ }
108
+ async getValue(key) {
109
+ parseArgument(key, keySchema);
110
+ const entry = this.#keyValueEntries.get(key);
111
+ if (!entry) {
112
+ return undefined;
113
+ }
114
+ // Return raw bytes + verbatim content type. Parsing is the frontend's job (see the
115
+ // KeyValueStore codec). The mime fallback reconstructs the content type for on-disk records.
116
+ const record = {
117
+ key: entry.key,
118
+ value: entry.value,
119
+ // mime.contentType returns `false` for unknown extensions; fall back to undefined so the
120
+ // frontend treats it as "no content type" rather than a bogus value.
121
+ contentType: entry.contentType ?? (mime.contentType(entry.extension) || undefined),
122
+ };
123
+ this.#updateTimestamps(false);
124
+ return record;
125
+ }
126
+ async setValue(record) {
127
+ parseArgument(record, inputRecordSchema);
128
+ const { key } = record;
129
+ let { value } = record;
130
+ // The frontend (KeyValueStore codec) serializes the value and resolves its content type
131
+ // before it reaches the backend. We only need it here for on-disk extension bookkeeping.
132
+ const contentType = record.contentType ?? 'application/octet-stream';
133
+ const extension = mime.extension(contentType) || DEFAULT_LOCAL_FILE_EXTENSION;
134
+ // Draining a stream into a Buffer for storage is the backend's responsibility.
135
+ if (isStream(value)) {
136
+ const chunks = [];
137
+ for await (const chunk of value) {
138
+ chunks.push(chunk);
139
+ }
140
+ value = Buffer.concat(chunks);
141
+ }
142
+ // This backend is a byte transport: it stores and returns raw bytes regardless of the input
143
+ // shape. Streams were drained above; encode strings to UTF-8 bytes and normalize
144
+ // ArrayBuffer / typed-array views to a Buffer over the same memory.
145
+ const normalizedValue = typeof value === 'string'
146
+ ? Buffer.from(value, 'utf-8')
147
+ : toBuffer(value);
148
+ const normalizedRecord = {
149
+ extension,
150
+ key,
151
+ value: normalizedValue,
152
+ contentType,
153
+ };
154
+ this.#keyValueEntries.set(key, normalizedRecord);
155
+ this.#updateTimestamps(true);
156
+ }
157
+ async deleteValue(key) {
158
+ parseArgument(key, keySchema);
159
+ if (this.#keyValueEntries.has(key)) {
160
+ this.#keyValueEntries.delete(key);
161
+ this.#updateTimestamps(true);
162
+ }
163
+ }
164
+ toKeyValueStoreInfo() {
165
+ return {
166
+ id: this.id,
167
+ name: this.name,
168
+ accessedAt: this.accessedAt,
169
+ createdAt: this.createdAt,
170
+ modifiedAt: this.modifiedAt,
171
+ };
172
+ }
173
+ #updateTimestamps(hasBeenModified) {
174
+ this.accessedAt = new Date();
175
+ if (hasBeenModified) {
176
+ this.modifiedAt = new Date();
177
+ }
178
+ }
179
+ }
@@ -0,0 +1,55 @@
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
+ constructor(options: RequestQueueBackendOptions);
38
+ getMetadata(): Promise<storage.RequestQueueInfo>;
39
+ drop(): Promise<void>;
40
+ purge(): Promise<void>;
41
+ fetchNextRequest(): Promise<storage.UpdateRequestSchema | undefined>;
42
+ addBatchOfRequests(requests: storage.RequestSchema[], options?: storage.RequestQueueOperationOptions): Promise<storage.BatchAddRequestsResult>;
43
+ getRequest(uniqueKey: string): Promise<storage.UpdateRequestSchema | undefined>;
44
+ markRequestAsHandled(request: storage.UpdateRequestSchema): Promise<storage.QueueOperationInfo | undefined>;
45
+ reclaimRequest(request: storage.UpdateRequestSchema, options?: storage.RequestQueueOperationOptions): Promise<storage.QueueOperationInfo | undefined>;
46
+ isEmpty(): Promise<boolean>;
47
+ isFinished(): Promise<boolean>;
48
+ /**
49
+ * Returns all pending (not yet handled, not currently in progress) requests in the queue, ordered
50
+ * the same way {@link fetchNextRequest} would hand them out. This does not mutate the queue,
51
+ * nothing is marked in progress.
52
+ */
53
+ listItems(): Promise<storage.UpdateRequestSchema[]>;
54
+ toRequestQueueInfo(): storage.RequestQueueInfo;
55
+ }