Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

feat: implements async iterators (#3352)

Richard Solar7f7a4ab3e21b
diff --git a/packages/core/src/storages/dataset.ts b/packages/core/src/storages/dataset.ts
index dc27d09b3..1a85d8c57 100644
--- a/packages/core/src/storages/dataset.ts
+++ b/packages/core/src/storages/dataset.ts
@@ -1,4 +1,4 @@
-import type { DatasetClient, DatasetInfo, Dictionary, StorageClient } from '@crawlee/types';
+import type { DatasetClient, DatasetInfo, Dictionary, PaginatedList, StorageClient } from '@crawlee/types';
import { stringify } from 'csv-stringify/sync';
import ow from 'ow';
@@ -606,6 +606,78 @@ export class Dataset<Data extends Dictionary = Dictionary> {
return currentMemo;
}
+ /**
+ * Iterates over dataset items using an async generator,
+ * allowing the use of `for await...of` syntax.
+ *
+ * **Example usage:**
+ * ```javascript
+ * const dataset = await Dataset.open('my-results');
+ * for await (const item of dataset.values()) {
+ * console.log(item);
+ * }
+ * ```
+ *
+ * @param options Options for the iteration.
+ */
+ values(options: DatasetIteratorOptions = {}): AsyncIterable<Data> & Promise<PaginatedList<Data>> {
+ checkStorageAccess();
+
+ const result = this.client.listItems(options) as AsyncIterable<Data> & Promise<PaginatedList<Data>>;
+
+ if (!(Symbol.asyncIterator in result)) {
+ Object.defineProperty(result, Symbol.asyncIterator, {
+ get() {
+ throw new Error('Resource client "listItems" method does not return an async iterable.');
+ },
+ });
+ }
+
+ return result;
+ }
+
+ /**
+ * Iterates over dataset entries (index-value pairs) using an async generator,
+ * allowing the use of `for await...of` syntax.
+ *
+ * **Example usage:**
+ * ```javascript
+ * const dataset = await Dataset.open('my-results');
+ * for await (const [index, item] of dataset.entries()) {
+ * console.log(`Item at ${index}: ${JSON.stringify(item)}`);
+ * }
+ * ```
+ *
+ * @param options Options for the iteration.
+ */
+ entries(
+ options: DatasetIteratorOptions = {},
+ ): AsyncIterable<[number, Data]> & Promise<PaginatedList<[number, Data]>> {
+ checkStorageAccess();
+
+ if (!this.client.listEntries) {
+ throw new Error('Resource client is missing the "listEntries" method.');
+ }
+
+ return this.client.listEntries(options);
+ }
+
+ /**
+ * Default async iterator for the dataset, iterating over items.
+ * Allows using the dataset directly in a `for await...of` loop.
+ *
+ * **Example usage:**
+ * ```javascript
+ * const dataset = await Dataset.open('my-results');
+ * for await (const item of dataset) {
+ * console.log(item);
+ * }
+ * ```
+ */
+ async *[Symbol.asyncIterator](): AsyncGenerator<Data, void, undefined> {
+ yield* this.values();
+ }
+
/**
* Removes the dataset either from the Apify cloud storage or from the local directory,
* depending on the mode of operation.
diff --git a/packages/core/src/storages/key_value_store.ts b/packages/core/src/storages/key_value_store.ts
index 161d4fa29..74bfba63b 100644
--- a/packages/core/src/storages/key_value_store.ts
+++ b/packages/core/src/storages/key_value_store.ts
@@ -481,6 +481,96 @@ export class KeyValueStore {
: undefined; // [].forEach() returns undefined.
}
+ /**
+ * Iterates over key-value store keys using an async generator,
+ * allowing the use of `for await...of` syntax.
+ *
+ * **Example usage:**
+ * ```javascript
+ * const keyValueStore = await KeyValueStore.open();
+ * for await (const key of keyValueStore.keys()) {
+ * console.log(key);
+ * }
+ * ```
+ *
+ * @param options Options for the iteration.
+ */
+ async *keys(options: KeyValueStoreIteratorOptions = {}): AsyncGenerator<string, void, undefined> {
+ checkStorageAccess();
+
+ if (!this.client.keys) {
+ throw new Error('Resource client is missing the "keys" method.');
+ }
+
+ yield* this.client.keys(options);
+ }
+
+ /**
+ * Iterates over key-value store values using an async generator,
+ * allowing the use of `for await...of` syntax.
+ *
+ * **Example usage:**
+ * ```javascript
+ * const keyValueStore = await KeyValueStore.open();
+ * for await (const value of keyValueStore.values()) {
+ * console.log(value);
+ * }
+ * ```
+ *
+ * @param options Options for the iteration.
+ */
+ values<T = unknown>(options: KeyValueStoreIteratorOptions = {}): AsyncIterable<T> & Promise<T[]> {
+ checkStorageAccess();
+
+ if (!this.client.values) {
+ throw new Error('Resource client is missing the "values" method.');
+ }
+
+ return this.client.values(options) as AsyncIterable<T> & Promise<T[]>;
+ }
+
+ /**
+ * Iterates over key-value store entries (key-value pairs) using an async generator,
+ * allowing the use of `for await...of` syntax.
+ *
+ * **Example usage:**
+ * ```javascript
+ * const keyValueStore = await KeyValueStore.open();
+ * for await (const [key, value] of keyValueStore.entries()) {
+ * console.log(`${key}: ${value}`);
+ * }
+ * ```
+ *
+ * @param options Options for the iteration.
+ */
+ entries<T = unknown>(
+ options: KeyValueStoreIteratorOptions = {},
+ ): AsyncIterable<[string, T]> & Promise<[string, T][]> {
+ checkStorageAccess();
+
+ if (!this.client.entries) {
+ throw new Error('Resource client is missing the "entries" method.');
+ }
+
+ return this.client.entries(options) as AsyncIterable<[string, T]> & Promise<[string, T][]>;
+ }
+
+ /**
+ * Default async iterator for the key-value store, iterating over entries (key-value pairs).
+ * Allows using the store directly in a `for await...of` loop.
+ *
+ * **Example usage:**
+ * ```javascript
+ * const keyValueStore = await KeyValueStore.open();
+ * for await (const [key, value] of keyValueStore) {
+ * console.log(`${key}: ${value}`);
+ * }
+ * ```
+ */
+ async *[Symbol.asyncIterator]<T = unknown>(): AsyncGenerator<[string, T], void, undefined> {
+ yield* this.entries<T>();
+ }
+
/**
* Returns a file URL for the given key.
*/
diff --git a/packages/memory-storage/src/resource-clients/dataset.ts b/packages/memory-storage/src/resource-clients/dataset.ts
index a90df844a..1ef9f9aad 100644
--- a/packages/memory-storage/src/resource-clients/dataset.ts
+++ b/packages/memory-storage/src/resource-clients/dataset.ts
@@ -3,8 +3,8 @@ import { randomUUID } from 'node:crypto';
import { rm } from 'node:fs/promises';
import { resolve } from 'node:path';
-import type { Dictionary } from '@crawlee/types';
import type * as storage from '@crawlee/types';
+import type { Dictionary } from '@crawlee/types';
import { s } from '@sapphire/shapeshift';
import { move } from 'fs-extra';
@@ -14,6 +14,7 @@ import { StorageTypes } from '../consts';
import type { StorageImplementation } from '../fs/common';
import { createDatasetStorageImplementation } from '../fs/dataset';
import type { MemoryStorage } from '../index';
+import { createPaginatedEntryList, createPaginatedList } from '../utils';
import { BaseClient } from './common/base-client';
/**
@@ -128,12 +129,32 @@ export class DatasetClient<Data extends Dictionary = Dictionary>
throw new Error('This method is not implemented in @crawlee/memory-storage');
}
- async listItems(options: storage.DatasetClientListOptions = {}): Promise<storage.PaginatedList<Data>> {
- const {
- limit = LIST_ITEMS_LIMIT,
- offset = 0,
- desc,
- } = s
+ listItems(
+ options: storage.DatasetClientListOptions = {},
+ ): AsyncIterable<Data> & Promise<storage.PaginatedList<Data>> {
+ const { desc, limit, offset } = s
+ .object({
+ desc: s.boolean.optional,
+ limit: s.number.int.optional,
+ offset: s.number.int.optional,
+ })
+ .parse(options);
+
+ return createPaginatedList<Data>(
+ (pageOffset, pageLimit) =>
+ this.listItemsPage({
+ desc,
+ offset: pageOffset,
+ limit: Math.min(pageLimit, LIST_ITEMS_LIMIT),
+ }),
+ { offset, limit },
+ );
+ }
+
+ listEntries(
+ options: storage.DatasetClientListOptions = {},
+ ): AsyncIterable<[number, Data]> & Promise<storage.PaginatedList<[number, Data]>> {
+ const { desc, limit, offset } = s
.object({
desc: s.boolean.optional,
limit: s.number.int.optional,
@@ -141,6 +162,20 @@ export class DatasetClient<Data extends Dictionary = Dictionary>
})
.parse(options);
+ return createPaginatedEntryList<Data>(
+ (pageOffset, pageLimit) =>
+ this.listItemsPage({
+ desc,
+ offset: pageOffset,
+ limit: Math.min(pageLimit, LIST_ITEMS_LIMIT),
+ }),
+ { offset, limit },
+ );
+ }
+
+ private async listItemsPage(options: storage.DatasetClientListOptions = {}): Promise<storage.PaginatedList<Data>> {
+ const { limit = LIST_ITEMS_LIMIT, offset = 0, desc } = options;
+
// Check by id
const existingStoreById = await findOrCacheDatasetByPossibleId(this.client, this.name ?? this.id);
diff --git a/packages/memory-storage/src/resource-clients/key-value-store.ts b/packages/memory-storage/src/resource-clients/key-value-store.ts
index 1a3af0432..ddd666f27 100644
--- a/packages/memory-storage/src/resource-clients/key-value-store.ts
+++ b/packages/memory-storage/src/resource-clients/key-value-store.ts
@@ -15,7 +15,7 @@ import { DEFAULT_API_PARAM_LIMIT, StorageTypes } from '../consts';
import type { StorageImplementation } from '../fs/common';
import { createKeyValueStorageImplementation } from '../fs/key-value-store';
import type { MemoryStorage } from '../index';
-import { isBuffer, isStream } from '../utils';
+import { createKeyList, createKeyStringList, isBuffer, isStream } from '../utils';
import { BaseClient } from './common/base-client';
const DEFAULT_LOCAL_FILE_EXTENSION = 'bin';
@@ -118,12 +118,10 @@ export class KeyValueStoreClient extends BaseClient {
}
}
- async listKeys(options: storage.KeyValueStoreClientListOptions = {}): Promise<storage.KeyValueStoreClientListData> {
- const {
- limit = DEFAULT_API_PARAM_LIMIT,
- exclusiveStartKey,
- prefix,
- } = s
+ listKeys(
+ options: storage.KeyValueStoreClientListOptions = {},
+ ): AsyncIterable<storage.KeyValueStoreItemData> & Promise<storage.KeyValueStoreClientListData> {
+ const { limit, exclusiveStartKey, prefix } = s
.object({
limit: s.number.greaterThan(0).optional,
exclusiveStartKey: s.string.optional,
@@ -132,6 +130,144 @@ export class KeyValueStoreClient extends BaseClient {
})
.parse(options);
+ return createKeyList(
+ (pageExclusiveStartKey) =>
+ this.listKeysPage({
+ limit: limit ?? DEFAULT_API_PARAM_LIMIT,
+ exclusiveStartKey: pageExclusiveStartKey,
+ prefix,
+ }),
+ { exclusiveStartKey, limit },
+ );
+ }
+
+ keys(
+ options: storage.KeyValueStoreClientListOptions = {},
+ ): AsyncIterable<string> & Promise<storage.KeyValueStoreClientListData> {
+ const { limit, exclusiveStartKey, prefix } = s
+ .object({
+ limit: s.number.greaterThan(0).optional,
+ exclusiveStartKey: s.string.optional,
+ collection: s.string.optional,
+ prefix: s.string.optional,
+ })
+ .parse(options);
+
+ return createKeyStringList(
+ (pageExclusiveStartKey) =>
+ this.listKeysPage({
+ limit: limit ?? DEFAULT_API_PARAM_LIMIT,
+ exclusiveStartKey: pageExclusiveStartKey,
+ prefix,
+ }),
+ { exclusiveStartKey, limit },
+ );
+ }
+
+ values(options: storage.KeyValueStoreClientListOptions = {}): AsyncIterable<unknown> & Promise<unknown[]> {
+ const keys = this.keys.bind(this);
+ const getRecord = this.getRecord.bind(this);
+ const limit = options.limit;
+
+ const firstPageKeysPromise = keys(options);
+
+ const firstPageValuesPromise = (async () => {
+ const firstPageKeys = await firstPageKeysPromise;
+ const values: unknown[] = [];
+ for (const item of firstPageKeys.items) {
+ if (limit !== undefined && values.length >= limit) break;
+ const record = await getRecord(item.key);
+ if (record) {
+ values.push(record.value);
+ }
+ }
+ return values;
+ })();
+
+ async function* asyncGenerator(): AsyncGenerator<unknown> {
+ // Reuse the already-fetched first page values
+ const firstPageValues = await firstPageValuesPromise;
+ let yielded = 0;
+
+ for (const value of firstPageValues) {
+ if (limit !== undefined && yielded >= limit) return;
+ yield value;
+ yielded++;
+ }
+
+ const firstPageKeys = await firstPageKeysPromise;
+ if (firstPageKeys.nextExclusiveStartKey && (limit === undefined || yielded < limit)) {
+ for await (const key of keys({ ...options, exclusiveStartKey: firstPageKeys.nextExclusiveStartKey })) {
+ if (limit !== undefined && yielded >= limit) return;
+ const record = await getRecord(key);
+ if (record) {
+ yield record.value;
+ yielded++;
+ }
+ }
+ }
+ }
+
+ return Object.defineProperty(firstPageValuesPromise, Symbol.asyncIterator, {
+ value: asyncGenerator,
+ }) as AsyncIterable<unknown> & Promise<unknown[]>;
+ }
+
+ entries(
+ options: storage.KeyValueStoreClientListOptions = {},
+ ): AsyncIterable<[string, unknown]> & Promise<[string, unknown][]> {
+ const keys = this.keys.bind(this);
+ const getRecord = this.getRecord.bind(this);
+ const limit = options.limit;
+
+ const firstPageKeysPromise = keys(options);
+
+ const firstPageEntriesPromise = (async () => {
+ const firstPageKeys = await firstPageKeysPromise;
+ const entries: [string, unknown][] = [];
+ for (const item of firstPageKeys.items) {
+ if (limit !== undefined && entries.length >= limit) break;
+ const record = await getRecord(item.key);
+ if (record) {
+ entries.push([item.key, record.value]);
+ }
+ }
+ return entries;
+ })();
+
+ async function* asyncGenerator(): AsyncGenerator<[string, unknown]> {
+ const firstPageEntries = await firstPageEntriesPromise;
+ let yielded = 0;
+
+ for (const entry of firstPageEntries) {
+ if (limit !== undefined && yielded >= limit) return;
+ yield entry;
+ yielded++;
+ }
+
+ const firstPageKeys = await firstPageKeysPromise;
+ if (firstPageKeys.nextExclusiveStartKey && (limit === undefined || yielded < limit)) {
+ for await (const key of keys({ ...options, exclusiveStartKey: firstPageKeys.nextExclusiveStartKey })) {
+ if (limit !== undefined && yielded >= limit) return;
+ const record = await getRecord(key);
+ if (record) {
+ yield [key, record.value];
+ yielded++;
+ }
+ }
+ }
+ }
+
+ return Object.defineProperty(firstPageEntriesPromise, Symbol.asyncIterator, {
+ value: asyncGenerator,
+ }) as AsyncIterable<[string, unknown]> & Promise<[string, unknown][]>;
+ }
+
+ private async listKeysPage(
+ options: storage.KeyValueStoreClientListOptions = {},
+ ): Promise<storage.KeyValueStoreClientListData> {
+ const { limit = DEFAULT_API_PARAM_LIMIT, exclusiveStartKey, prefix } = options;
+
// Check by id
const existingStoreById = await findOrCacheKeyValueStoreByPossibleId(this.client, this.name ?? this.id);
diff --git a/packages/memory-storage/src/utils.ts b/packages/memory-storage/src/utils.ts
index b423bfb48..a22fa1a9a 100644
--- a/packages/memory-storage/src/utils.ts
+++ b/packages/memory-storage/src/utils.ts
@@ -71,3 +71,154 @@ interface MetadataUpdate<Type extends EntityType, DataType> {
writeMetadata: boolean;
persistStorage: boolean;
}
+
+/**
+ * Creates a hybrid Promise + AsyncIterable for offset-based pagination (Dataset.listItems).
+ *
+ * The returned object can be:
+ * - Awaited directly to get the first page (backward compatible)
+ * - Used with `for await...of` to iterate through all items
+ */
+export function createPaginatedList<Data>(
+ getPage: (offset: number, limit: number) => Promise<storage.PaginatedList<Data>>,
+ options: { offset?: number; limit?: number } = {},
+): AsyncIterable<Data> & Promise<storage.PaginatedList<Data>> {
+ const offset = options.offset ?? 0;
+
+ // Immediately fetch the first page (Infinity is used when no limit, gets clamped by Math.min downstream)
+ const firstPagePromise = getPage(offset, options.limit ?? Infinity);
+
+ async function* asyncGenerator(): AsyncGenerator<Data> {
+ let currentPage = await firstPagePromise;
+ yield* currentPage.items;
+
+ const limit = Math.min(options.limit ?? currentPage.total, currentPage.total);
+ let currentOffset = offset + currentPage.items.length;
+ let remainingItems = Math.min(currentPage.total - offset, limit) - currentPage.items.length;
+
+ while (
+ currentPage.items.length > 0 && // Continue only if at least some items were returned in the last page.
+ remainingItems > 0
+ ) {
+ currentPage = await getPage(currentOffset, remainingItems);
+ yield* currentPage.items;
+ currentOffset += currentPage.items.length;
+ remainingItems -= currentPage.items.length;
+ }
+ }
+
+ return Object.defineProperty(firstPagePromise, Symbol.asyncIterator, {
+ value: asyncGenerator,
+ }) as AsyncIterable<Data> & Promise<storage.PaginatedList<Data>>;
+}
+
+/**
+ * Creates a hybrid Promise + AsyncIterable for cursor-based pagination (KeyValueStore.listKeys).
+ *
+ * The returned object can be:
+ * - Awaited directly to get the first page (backward compatible)
+ * - Used with `for await...of` to iterate through all keys
+ */
+export function createKeyList(
+ getPage: (exclusiveStartKey?: string) => Promise<storage.KeyValueStoreClientListData>,
+ options: { exclusiveStartKey?: string; limit?: number } = {},
+): AsyncIterable<storage.KeyValueStoreItemData> & Promise<storage.KeyValueStoreClientListData> {
+ // Immediately fetch the first page
+ const firstPagePromise = getPage(options.exclusiveStartKey);
+
+ async function* asyncGenerator(): AsyncGenerator<storage.KeyValueStoreItemData> {
+ let currentPage = await firstPagePromise;
+ yield* currentPage.items;
+
+ let remainingItems = options.limit ? options.limit - currentPage.items.length : undefined;
+
+ while (
+ currentPage.items.length > 0 &&
+ currentPage.nextExclusiveStartKey !== undefined &&
+ (remainingItems === undefined || remainingItems > 0)
+ ) {
+ currentPage = await getPage(currentPage.nextExclusiveStartKey);
+ yield* currentPage.items;
+ if (remainingItems !== undefined) {
+ remainingItems -= currentPage.items.length;
+ }
+ }
+ }
+
+ return Object.defineProperty(firstPagePromise, Symbol.asyncIterator, {
+ value: asyncGenerator,
+ }) as AsyncIterable<storage.KeyValueStoreItemData> & Promise<storage.KeyValueStoreClientListData>;
+}
+
+/**
+ * Creates a hybrid Promise + AsyncIterable that yields only key strings (KeyValueStore.keys).
+ *
+ * The returned object can be:
+ * - Awaited directly to get the first page (backward compatible)
+ * - Used with `for await...of` to iterate through all key strings
+ */
+export function createKeyStringList(
+ getPage: (exclusiveStartKey?: string) => Promise<storage.KeyValueStoreClientListData>,
+ options: { exclusiveStartKey?: string; limit?: number } = {},
+): AsyncIterable<string> & Promise<storage.KeyValueStoreClientListData> {
+ // Immediately fetch the first page
+ const firstPagePromise = getPage(options.exclusiveStartKey);
+
+ async function* asyncGenerator(): AsyncGenerator<string> {
+ let currentPage = await firstPagePromise;
+ for (const item of currentPage.items) {
+ yield item.key;
+ }
+
+ let remainingItems = options.limit ? options.limit - currentPage.items.length : undefined;
+
+ while (
+ currentPage.items.length > 0 &&
+ currentPage.nextExclusiveStartKey !== undefined &&
+ (remainingItems === undefined || remainingItems > 0)
+ ) {
+ currentPage = await getPage(currentPage.nextExclusiveStartKey);
+ for (const item of currentPage.items) {
+ yield item.key;
+ }
+ if (remainingItems !== undefined) {
+ remainingItems -= currentPage.items.length;
+ }
+ }
+ }
+
+ return Object.defineProperty(firstPagePromise, Symbol.asyncIterator, {
+ value: asyncGenerator,
+ }) as AsyncIterable<string> & Promise<storage.KeyValueStoreClientListData>;
+}
+
+/**
+ * Creates a hybrid Promise + AsyncIterable for offset-based pagination with index-value entries (Dataset.listEntries).
+ *
+ * The returned object can be:
+ * - Awaited directly to get the first page with [index, item] tuples (backward compatible)
+ * - Used with `for await...of` to iterate through all entries as [index, item] tuples
+ */
+export function createPaginatedEntryList<Data>(
+ getPage: (offset: number, limit: number) => Promise<storage.PaginatedList<Data>>,
+ options: { offset?: number; limit?: number } = {},
+): AsyncIterable<[number, Data]> & Promise<storage.PaginatedList<[number, Data]>> {
+ const offset = options.offset ?? 0;
+
+ // Immediately fetch the first page and transform items to entries
+ const firstPagePromise = getPage(offset, options.limit ?? Infinity).then((result) => ({
+ ...result,
+ items: result.items.map((item, i) => [offset + i, item] as [number, Data]),
+ }));
+
+ async function* asyncGenerator(): AsyncGenerator<[number, Data]> {
+ let currentIndex = offset;
+ for await (const item of createPaginatedList(getPage, options)) {
+ yield [currentIndex++, item];
+ }
+ }
+
+ return Object.defineProperty(firstPagePromise, Symbol.asyncIterator, {
+ value: asyncGenerator,
+ }) as AsyncIterable<[number, Data]> & Promise<storage.PaginatedList<[number, Data]>>;
+}
diff --git a/packages/memory-storage/test/async-iteration.test.ts b/packages/memory-storage/test/async-iteration.test.ts
new file mode 100644
index 000000000..c82f98dd7
--- /dev/null
+++ b/packages/memory-storage/test/async-iteration.test.ts
@@ -0,0 +1,432 @@
+import { rm } from 'node:fs/promises';
+import { resolve } from 'node:path';
+
+import { MemoryStorage } from '@crawlee/memory-storage';
+import type { DatasetClient, KeyValueStoreClient } from '@crawlee/types';
+
+describe('Async iteration support', () => {
+ const localDataDirectory = resolve(__dirname, './tmp/async-iteration');
+ const storage = new MemoryStorage({
+ localDataDirectory,
+ persistStorage: false,
+ });
+
+ afterAll(async () => {
+ await rm(localDataDirectory, { force: true, recursive: true });
+ });
+
+ describe('Dataset.listItems', () => {
+ const elements = Array.from({ length: 25 }, (_, i) => ({ index: i }));
+ let dataset: DatasetClient;
+
+ beforeAll(async () => {
+ const { id } = await storage.datasets().getOrCreate('async-iteration-dataset');
+ dataset = storage.dataset(id);
+ await dataset.pushItems(elements);
+ });
+
+ test('can be awaited directly (backward compatibility)', async () => {
+ const result = await dataset.listItems({ limit: 10 });
+
+ expect(result.items).toHaveLength(10);
+ expect(result.total).toBe(25);
+ expect(result.offset).toBe(0);
+ expect(result.items).toStrictEqual(elements.slice(0, 10));
+ });
+
+ test('can be used with for await...of to iterate all items', async () => {
+ const items: { index: number }[] = [];
+
+ for await (const item of dataset.listItems()) {
+ items.push(item);
+ }
+
+ expect(items).toHaveLength(25);
+ expect(items).toStrictEqual(elements);
+ });
+
+ test('respects limit option when iterating', async () => {
+ const items: { index: number }[] = [];
+
+ for await (const item of dataset.listItems({ limit: 10 })) {
+ items.push(item);
+ }
+
+ expect(items).toHaveLength(10);
+ expect(items).toStrictEqual(elements.slice(0, 10));
+ });
+
+ test('respects offset option when iterating', async () => {
+ const items: { index: number }[] = [];
+
+ for await (const item of dataset.listItems({ offset: 5 })) {
+ items.push(item);
+ }
+
+ expect(items).toHaveLength(20);
+ expect(items).toStrictEqual(elements.slice(5));
+ });
+
+ test('respects both offset and limit options when iterating', async () => {
+ const items: { index: number }[] = [];
+
+ for await (const item of dataset.listItems({ offset: 5, limit: 10 })) {
+ items.push(item);
+ }
+
+ expect(items).toHaveLength(10);
+ expect(items).toStrictEqual(elements.slice(5, 15));
+ });
+
+ test('respects desc option when iterating', async () => {
+ const items: { index: number }[] = [];
+
+ for await (const item of dataset.listItems({ desc: true, limit: 5 })) {
+ items.push(item);
+ }
+
+ expect(items).toHaveLength(5);
+ expect(items).toStrictEqual(elements.slice().reverse().slice(0, 5));
+ });
+ });
+
+ describe('KeyValueStore.listKeys', () => {
+ const keys = Array.from({ length: 25 }, (_, i) => `key-${String(i).padStart(2, '0')}`);
+ let kvStore: KeyValueStoreClient;
+
+ beforeAll(async () => {
+ const { id } = await storage.keyValueStores().getOrCreate('async-iteration-kvs');
+ kvStore = storage.keyValueStore(id);
+
+ for (const key of keys) {
+ await kvStore.setRecord({ key, value: { data: key } });
+ }
+ });
+
+ test('can be awaited directly (backward compatibility)', async () => {
+ const result = await kvStore.listKeys({ limit: 10 });
+
+ expect(result.items).toHaveLength(10);
+ expect(result.isTruncated).toBe(true);
+ expect(result.items.map((i) => i.key)).toStrictEqual(keys.slice(0, 10));
+ });
+
+ test('can be used with for await...of to iterate all keys', async () => {
+ const items: string[] = [];
+
+ for await (const item of kvStore.listKeys()) {
+ items.push(item.key);
+ }
+
+ expect(items).toHaveLength(25);
+ expect(items).toStrictEqual(keys);
+ });
+
+ test('respects limit option when iterating (10 items, limit 2)', async () => {
+ // Create a fresh store with exactly 10 items to match the reported bug scenario
+ const { id } = await storage.keyValueStores().getOrCreate('limit-test-kvs');
+ const testStore = storage.keyValueStore(id);
+
+ for (let i = 0; i < 10; i++) {
+ await testStore.setRecord({ key: `key-${i}`, value: `value-${i}` });
+ }
+
+ const items: string[] = [];
+
+ // This should only return 2 items, matching apify-client behavior
+ for await (const item of testStore.listKeys({ limit: 2 })) {
+ items.push(item.key);
+ }
+
+ // Should only get 2 items, not all 10
+ expect(items).toHaveLength(2);
+ });
+
+ test('respects exclusiveStartKey option when iterating', async () => {
+ const items: string[] = [];
+
+ // Start after key-04 (index 4), should get keys 5-24
+ for await (const item of kvStore.listKeys({ exclusiveStartKey: 'key-04' })) {
+ items.push(item.key);
+ }
+
+ expect(items).toHaveLength(20);
+ expect(items).toStrictEqual(keys.slice(5));
+ });
+
+ test('respects prefix option when iterating', async () => {
+ const items: string[] = [];
+
+ // Only keys starting with 'key-0' (key-00 to key-09)
+ for await (const item of kvStore.listKeys({ prefix: 'key-0' })) {
+ items.push(item.key);
+ }
+
+ expect(items).toHaveLength(10);
+ expect(items).toStrictEqual(keys.slice(0, 10));
+ });
+ });
+
+ describe('KeyValueStore.keys', () => {
+ const keys = Array.from({ length: 25 }, (_, i) => `key-${String(i).padStart(2, '0')}`);
+ let kvStore: KeyValueStoreClient;
+
+ beforeAll(async () => {
+ const { id } = await storage.keyValueStores().getOrCreate('async-iteration-kvs-keys');
+ kvStore = storage.keyValueStore(id);
+
+ for (const key of keys) {
+ await kvStore.setRecord({ key, value: { data: key } });
+ }
+ });
+
+ test('can be awaited directly (backward compatibility)', async () => {
+ const result = await kvStore.keys({ limit: 10 });
+
+ // When awaited, returns the same structure as listKeys
+ expect(result.items).toHaveLength(10);
+ expect(result.isTruncated).toBe(true);
+ expect(result.items.map((i) => i.key)).toStrictEqual(keys.slice(0, 10));
+ });
+
+ test('can be used with for await...of to iterate all keys as strings', async () => {
+ const items: string[] = [];
+
+ for await (const key of kvStore.keys()) {
+ items.push(key);
+ }
+
+ expect(items).toHaveLength(25);
+ expect(items).toStrictEqual(keys);
+ });
+
+ test('yields strings directly, not objects', async () => {
+ // eslint-disable-next-line no-unreachable-loop
+ for await (const key of kvStore.keys()) {
+ expect(typeof key).toBe('string');
+ break; // Only need to check the first one
+ }
+ });
+
+ test('respects limit option when iterating', async () => {
+ const items: string[] = [];
+
+ for await (const key of kvStore.keys({ limit: 10 })) {
+ items.push(key);
+ }
+
+ expect(items).toHaveLength(10);
+ expect(items).toStrictEqual(keys.slice(0, 10));
+ });
+
+ test('respects exclusiveStartKey option when iterating', async () => {
+ const items: string[] = [];
+
+ // Start after key-04 (index 4), should get keys 5-24
+ for await (const key of kvStore.keys({ exclusiveStartKey: 'key-04' })) {
+ items.push(key);
+ }
+
+ expect(items).toHaveLength(20);
+ expect(items).toStrictEqual(keys.slice(5));
+ });
+
+ test('respects prefix option when iterating', async () => {
+ const items: string[] = [];
+
+ // Only keys starting with 'key-0' (key-00 to key-09)
+ for await (const key of kvStore.keys({ prefix: 'key-0' })) {
+ items.push(key);
+ }
+
+ expect(items).toHaveLength(10);
+ expect(items).toStrictEqual(keys.slice(0, 10));
+ });
+
+ test('respects both exclusiveStartKey and limit options', async () => {
+ const items: string[] = [];
+
+ for await (const key of kvStore.keys({ exclusiveStartKey: 'key-04', limit: 5 })) {
+ items.push(key);
+ }
+
+ expect(items).toHaveLength(5);
+ expect(items).toStrictEqual(keys.slice(5, 10));
+ });
+ });
+
+ describe('KeyValueStore.values', () => {
+ const keys = Array.from({ length: 25 }, (_, i) => `key-${String(i).padStart(2, '0')}`);
+ let kvStore: KeyValueStoreClient;
+
+ beforeAll(async () => {
+ const { id } = await storage.keyValueStores().getOrCreate('async-iteration-kvs-values');
+ kvStore = storage.keyValueStore(id);
+
+ for (const key of keys) {
+ await kvStore.setRecord({ key, value: { data: key } });
+ }
+ });
+
+ test('can be awaited directly (backward compatibility)', async () => {
+ const values = await kvStore.values({ limit: 10 });
+
+ expect(values).toHaveLength(10);
+ expect(Array.isArray(values)).toBe(true);
+ expect(values[0]).toStrictEqual({ data: 'key-00' });
+ });
+
+ test('can be used with for await...of to iterate all values', async () => {
+ const values: unknown[] = [];
+
+ for await (const value of kvStore.values()) {
+ values.push(value);
+ }
+
+ expect(values).toHaveLength(25);
+ expect(values.every((v) => v && typeof v === 'object')).toBe(true);
+ });
+
+ test('yields values directly, not KeyValueStoreRecord objects', async () => {
+ // eslint-disable-next-line no-unreachable-loop
+ for await (const value of kvStore.values()) {
+ // Should be the actual value, not a record wrapper
+ expect(value).toStrictEqual({ data: 'key-00' });
+ expect(value).not.toHaveProperty('contentType');
+ break; // Only need to check the first one
+ }
+ });
+
+ test('respects limit option when iterating', async () => {
+ const values: unknown[] = [];
+
+ for await (const value of kvStore.values({ limit: 10 })) {
+ values.push(value);
+ }
+
+ expect(values).toHaveLength(10);
+ });
+
+ test('respects exclusiveStartKey option when iterating', async () => {
+ const values: unknown[] = [];
+
+ // Start after key-04 (index 4), should get keys 5-24
+ for await (const value of kvStore.values({ exclusiveStartKey: 'key-04' })) {
+ values.push(value);
+ }
+
+ expect(values).toHaveLength(20);
+ });
+
+ test('respects prefix option when iterating', async () => {
+ const values: unknown[] = [];
+
+ // Only keys starting with 'key-0' (key-00 to key-09)
+ for await (const value of kvStore.values({ prefix: 'key-0' })) {
+ values.push(value);
+ }
+
+ expect(values).toHaveLength(10);
+ });
+
+ test('fetches actual record values', async () => {
+ const values: unknown[] = [];
+
+ for await (const value of kvStore.values({ limit: 3 })) {
+ values.push(value);
+ }
+
+ expect(values[0]).toStrictEqual({ data: 'key-00' });
+ expect(values[1]).toStrictEqual({ data: 'key-01' });
+ expect(values[2]).toStrictEqual({ data: 'key-02' });
+ });
+ });
+
+ describe('KeyValueStore.entries', () => {
+ const keys = Array.from({ length: 25 }, (_, i) => `key-${String(i).padStart(2, '0')}`);
+ let kvStore: KeyValueStoreClient;
+
+ beforeAll(async () => {
+ const { id } = await storage.keyValueStores().getOrCreate('async-iteration-kvs-entries');
+ kvStore = storage.keyValueStore(id);
+
+ for (const key of keys) {
+ await kvStore.setRecord({ key, value: { data: key } });
+ }
+ });
+
+ test('can be awaited directly (backward compatibility)', async () => {
+ const entries = await kvStore.entries({ limit: 10 });
+
+ expect(entries).toHaveLength(10);
+ expect(Array.isArray(entries)).toBe(true);
+ // Each entry is a [key, value] tuple
+ expect(entries[0][0]).toBe('key-00');
+ expect(entries[0][1]).toStrictEqual({ data: 'key-00' });
+ });
+
+ test('can be used with for await...of to iterate all entries', async () => {
+ const entries: [string, unknown][] = [];
+
+ for await (const entry of kvStore.entries()) {
+ entries.push(entry);
+ }
+
+ expect(entries).toHaveLength(25);
+ expect(entries.map(([key]) => key)).toStrictEqual(keys);
+ });
+
+ test('yields [key, value] tuples', async () => {
+ // eslint-disable-next-line no-unreachable-loop
+ for await (const [key, value] of kvStore.entries()) {
+ expect(typeof key).toBe('string');
+ expect(key).toBe('key-00');
+ expect(value).toStrictEqual({ data: 'key-00' });
+ // Value should not be a record wrapper
+ expect(value).not.toHaveProperty('contentType');
+ break; // Only need to check the first one
+ }
+ });
+
+ test('respects limit option when iterating', async () => {
+ const entries: [string, unknown][] = [];
+
+ for await (const entry of kvStore.entries({ limit: 10 })) {
+ entries.push(entry);
+ }
+
+ expect(entries).toHaveLength(10);
+ expect(entries.map(([key]) => key)).toStrictEqual(keys.slice(0, 10));
+ });
+
+ test('respects exclusiveStartKey option when iterating', async () => {
+ const entries: [string, unknown][] = [];
+
+ // Start after key-04 (index 4), should get keys 5-24
+ for await (const entry of kvStore.entries({ exclusiveStartKey: 'key-04' })) {
+ entries.push(entry);
+ }
+
+ expect(entries).toHaveLength(20);
+ expect(entries.map(([key]) => key)).toStrictEqual(keys.slice(5));
+ });
+
+ test('respects prefix option when iterating', async () => {
+ const entries: [string, unknown][] = [];
+
+ // Only keys starting with 'key-0' (key-00 to key-09)
+ for await (const entry of kvStore.entries({ prefix: 'key-0' })) {
+ entries.push(entry);
+ }
+
+ expect(entries).toHaveLength(10);
+ expect(entries.map(([key]) => key)).toStrictEqual(keys.slice(0, 10));
+ });
+
+ test('values in entries match expected data', async () => {
+ for await (const [key, value] of kvStore.entries({ limit: 5 })) {
+ expect(value).toStrictEqual({ data: key });
+ }
+ });
+ });
+});
diff --git a/packages/types/src/storages.ts b/packages/types/src/storages.ts
index ba9247626..dec1a8af4 100644
--- a/packages/types/src/storages.ts
+++ b/packages/types/src/storages.ts
@@ -86,7 +86,10 @@ export interface DatasetClient<Data extends Dictionary = Dictionary> {
update(newFields: DatasetClientUpdateOptions): Promise<Partial<DatasetInfo>>;
delete(): Promise<void>;
downloadItems(...args: unknown[]): Promise<Buffer>;
- listItems(options?: DatasetClientListOptions): Promise<PaginatedList<Data>>;
+ listItems(options?: DatasetClientListOptions): AsyncIterable<Data> & Promise<PaginatedList<Data>>;
+ listEntries?(
+ options?: DatasetClientListOptions,
+ ): AsyncIterable<[number, Data]> & Promise<PaginatedList<[number, Data]>>;
pushItems(items: Data | Data[] | string | string[]): Promise<void>;
}
@@ -166,7 +169,12 @@ export interface KeyValueStoreClient {
get(): Promise<KeyValueStoreInfo | undefined>;
update(newFields: KeyValueStoreClientUpdateOptions): Promise<Partial<KeyValueStoreInfo>>;
delete(): Promise<void>;
- listKeys(options?: KeyValueStoreClientListOptions): Promise<KeyValueStoreClientListData>;
+ listKeys(
+ options?: KeyValueStoreClientListOptions,
+ ): Partial<AsyncIterable<KeyValueStoreItemData>> & Promise<KeyValueStoreClientListData>;
+ keys?(options?: KeyValueStoreClientListOptions): AsyncIterable<string> & Promise<KeyValueStoreClientListData>;
+ values?(options?: KeyValueStoreClientListOptions): AsyncIterable<unknown> & Promise<unknown[]>;
+ entries?(options?: KeyValueStoreClientListOptions): AsyncIterable<[string, unknown]> & Promise<[string, unknown][]>;
recordExists(key: string): Promise<boolean>;
getRecord(key: string, options?: KeyValueStoreClientGetRecordOptions): Promise<KeyValueStoreRecord | undefined>;
setRecord(record: KeyValueStoreRecord, options?: KeyValueStoreRecordOptions): Promise<void>;
diff --git a/test/core/storages/dataset.test.ts b/test/core/storages/dataset.test.ts
index eec10d9d1..d3eb614f5 100644
--- a/test/core/storages/dataset.test.ts
+++ b/test/core/storages/dataset.test.ts
@@ -573,5 +573,159 @@ describe('dataset', () => {
expect(exported).toContain('age');
});
});
+
+ describe('async iterators', () => {
+ const testData = [
+ { id: 1, name: 'Alice' },
+ { id: 2, name: 'Bob' },
+ { id: 3, name: 'Charlie' },
+ ];
+
+ test('values() should iterate over all items', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData(testData);
+
+ const items = [];
+ for await (const item of dataset.values()) {
+ items.push(item);
+ }
+
+ expect(items).toEqual(testData);
+ });
+
+ test('values() can be awaited directly (hybrid usage)', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData(testData);
+
+ const result = await dataset.values();
+
+ expect(result.items).toEqual(testData);
+ expect(result.total).toBe(3);
+ expect(result.count).toBe(3);
+ expect(result.offset).toBe(0);
+ });
+
+ test('values() respects limit when awaited directly', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData(testData);
+
+ const result = await dataset.values({ limit: 2 });
+
+ expect(result.items).toHaveLength(2);
+ expect(result.items).toEqual(testData.slice(0, 2));
+ expect(result.total).toBe(3);
+ expect(result.count).toBe(2);
+ });
+
+ test('values() respects offset when awaited directly', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData(testData);
+
+ const result = await dataset.values({ offset: 1 });
+
+ expect(result.items).toHaveLength(2);
+ expect(result.items).toEqual(testData.slice(1));
+ expect(result.offset).toBe(1);
+ });
+
+ test('entries() should iterate over index-item pairs', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData(testData);
+
+ const entries = [];
+ for await (const [index, item] of dataset.entries()) {
+ entries.push([index, item]);
+ }
+
+ expect(entries).toEqual([
+ [0, { id: 1, name: 'Alice' }],
+ [1, { id: 2, name: 'Bob' }],
+ [2, { id: 3, name: 'Charlie' }],
+ ]);
+ });
+
+ test('entries() should respect offset option', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData(testData);
+
+ const entries = [];
+ for await (const [index, item] of dataset.entries({ offset: 1 })) {
+ entries.push([index, item]);
+ }
+
+ expect(entries).toEqual([
+ [1, { id: 2, name: 'Bob' }],
+ [2, { id: 3, name: 'Charlie' }],
+ ]);
+ });
+
+ test('entries() can be awaited directly (hybrid usage)', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData(testData);
+
+ const result = await dataset.entries();
+
+ expect(result.items).toEqual([
+ [0, { id: 1, name: 'Alice' }],
+ [1, { id: 2, name: 'Bob' }],
+ [2, { id: 3, name: 'Charlie' }],
+ ]);
+ expect(result.total).toBe(3);
+ expect(result.count).toBe(3);
+ expect(result.offset).toBe(0);
+ });
+
+ test('entries() respects limit when awaited directly', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData(testData);
+
+ const result = await dataset.entries({ limit: 2 });
+
+ expect(result.items).toHaveLength(2);
+ expect(result.items).toEqual([
+ [0, { id: 1, name: 'Alice' }],
+ [1, { id: 2, name: 'Bob' }],
+ ]);
+ expect(result.total).toBe(3);
+ expect(result.count).toBe(2);
+ });
+
+ test('entries() respects offset when awaited directly', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData(testData);
+
+ const result = await dataset.entries({ offset: 1 });
+
+ expect(result.items).toHaveLength(2);
+ expect(result.items).toEqual([
+ [1, { id: 2, name: 'Bob' }],
+ [2, { id: 3, name: 'Charlie' }],
+ ]);
+ expect(result.offset).toBe(1);
+ });
+
+ test('Symbol.asyncIterator should iterate over items', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData(testData);
+
+ const items = [];
+ for await (const item of dataset) {
+ items.push(item);
+ }
+
+ expect(items).toEqual(testData);
+ });
+
+ test('should work with empty dataset', async () => {
+ const dataset = await Dataset.open();
+
+ const items: unknown[] = [];
+ for await (const item of dataset.values()) {
+ items.push(item);
+ }
+
+ expect(items).toEqual([]);
+ });
+ });
});
});
diff --git a/test/core/storages/key_value_store.test.ts b/test/core/storages/key_value_store.test.ts
index 2476b114a..b01388923 100644
--- a/test/core/storages/key_value_store.test.ts
+++ b/test/core/storages/key_value_store.test.ts
@@ -604,4 +604,115 @@ describe('KeyValueStore', () => {
});
});
});
+
+ describe('async iterators', () => {
+ test('keys() should iterate over all keys', async () => {
+ const store = await KeyValueStore.open();
+
+ const testData = {
+ key1: { value: 1 },
+ key2: { value: 2 },
+ key3: { value: 3 },
+ };
+
+ for (const [key, value] of Object.entries(testData)) {
+ await store.setValue(key, value);
+ }
+
+ const keys: string[] = [];
+ for await (const key of store.keys()) {
+ keys.push(key);
+ }
+
+ expect(keys).toEqual(['key1', 'key2', 'key3']);
+ });
+
+ test('keys() should respect prefix option', async () => {
+ const store = await KeyValueStore.open();
+
+ for (const [key, value] of Object.entries({
+ 'img-key1': 'PAYLOAD',
+ 'img-key2': 'PAYLOAD',
+ 'txt-key1': 'PAYLOAD',
+ })) {
+ await store.setValue(key, value);
+ }
+
+ const imgKeys: string[] = [];
+ for await (const key of store.keys({ prefix: 'img-' })) {
+ imgKeys.push(key);
+ }
+
+ expect(imgKeys).toEqual(['img-key1', 'img-key2']);
+ });
+
+ test('values() should iterate over all values', async () => {
+ const store = await KeyValueStore.open();
+
+ const testData = {
+ key1: { value: 1 },
+ key2: { value: 2 },
+ key3: { value: 3 },
+ };
+
+ for (const [key, value] of Object.entries(testData)) {
+ await store.setValue(key, value);
+ }
+
+ const values: { value: number }[] = [];
+ for await (const value of store.values<{ value: number }>()) {
+ values.push(value);
+ }
+
+ expect(values).toEqual([{ value: 1 }, { value: 2 }, { value: 3 }]);
+ });
+
+ test('entries() should iterate over all key-value pairs', async () => {
+ const store = await KeyValueStore.open();
+
+ const testData = {
+ key1: { value: 1 },
+ key2: { value: 2 },
+ key3: { value: 3 },
+ };
+
+ for (const [key, value] of Object.entries(testData)) {
+ await store.setValue(key, value);
+ }
+
+ const entries: [string, { value: number }][] = [];
+ for await (const [key, value] of store.entries<{ value: number }>()) {
+ entries.push([key, value]);
+ }
+
+ expect(entries).toEqual([
+ ['key1', { value: 1 }],
+ ['key2', { value: 2 }],
+ ['key3', { value: 3 }],
+ ]);
+ });
+
+ test('Symbol.asyncIterator should iterate over entries', async () => {
+ const store = await KeyValueStore.open();
+
+ const testData = {
+ key1: { value: 1 },
+ key2: { value: 2 },
+ };
+
+ for (const [key, value] of Object.entries(testData)) {
+ await store.setValue(key, value);
+ }
+
+ const entries: [string, { value: number }][] = [];
+ for await (const [key, value] of store) {
+ entries.push([key, value as { value: number }]);
+ }
+
+ expect(entries).toEqual([
+ ['key1', { value: 1 }],
+ ['key2', { value: 2 }],
+ ]);
+ });
+ });
});