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.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
refactor!: Centralize KVS value semantics in @crawlee/core (#3774)
Jan Bucharc067c50b0c1d
diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.mdindex ad0258db4..d00a9837c 100644--- a/docs/upgrading/upgrading_v4.md+++ b/docs/upgrading/upgrading_v4.md@@ -619,6 +619,10 @@ The high-level storage classes (`Dataset`, `KeyValueStore`, `RequestQueue`) now`timeoutSecs` and `doNotRetryTimeouts` were removed from `RecordOptions` (used by `KeyValueStore.setValue`). Only `contentType` remains.+### `maybeStringify` is removed++The `maybeStringify` helper exported from `@crawlee/core` has been removed. Value (de)serialization now lives entirely in the `KeyValueStore` frontend: writing serializes the value (and infers its content type), reading parses it back, and the storage client is a plain byte transport. If you imported `maybeStringify` directly, use the `serializeValue` / `parseValue` functions exported from `@crawlee/core` instead.+### `KeyValueStoreIteratorOptions` simplified`exclusiveStartKey` and `collection` were removed. Only `prefix` remains.diff --git a/packages/core/package.json b/packages/core/package.jsonindex e5de74aec..a7e308bee 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -59,6 +59,7 @@"@crawlee/utils": "workspace:*","@sapphire/async-queue": "^1.5.5","@vladfrangu/async_event_emitter": "^2.4.6",+ "content-type": "^1.0.5","csv-stringify": "^6.5.2","json5": "^2.2.3","minimatch": "^10.0.1",diff --git a/packages/core/src/storages/index.ts b/packages/core/src/storages/index.tsindex b66f8039f..04bc1130d 100644--- a/packages/core/src/storages/index.ts+++ b/packages/core/src/storages/index.ts@@ -1,5 +1,6 @@export * from './dataset.js';export * from './key_value_store.js';+export * from './key_value_store_codec.js';export * from './request_list.js';export type * from './request_loader.js';export type * from './request_manager.js';diff --git a/packages/core/src/storages/key_value_store.ts b/packages/core/src/storages/key_value_store.tsindex c81ced1da..c677ae3bd 100644--- a/packages/core/src/storages/key_value_store.ts+++ b/packages/core/src/storages/key_value_store.ts@@ -6,53 +6,21 @@ import JSON5 from 'json5';import ow, { ArgumentError } from 'ow';import { KEY_VALUE_STORE_KEY_REGEX } from '@apify/consts';-import { jsonStringifyExtended } from '@apify/utilities';import { Configuration } from '../configuration.js';import { serviceLocator } from '../service_locator.js';import type { Awaitable } from '../typedefs.js';import { checkStorageAccess } from './access_checking.js';+import { parseValue, serializeValue } from './key_value_store_codec.js';import type { StorageIdentifier } from './storage_instance_manager.js';import type { StorageOpenOptions } from './utils.js';import { resolveStorageIdentifier } from './storage_instance_manager.js';import { createDualIterable, purgeDefaultStorages } from './utils.js';+import { isBuffer, isStream } from '@crawlee/utils';/** @internal */const KVS_KEYS_DEFAULT_LIMIT = 1000;-/**- * Helper function to possibly stringify value if options.contentType is not set.- *- * @ignore- */-export const maybeStringify = <T>(value: T, options: { contentType?: string }) => {- // If contentType is missing, value will be stringified to JSON- if (options.contentType === null || options.contentType === undefined) {- options.contentType = 'application/json; charset=utf-8';-- try {- // Format JSON to simplify debugging, the overheads with compression is negligible- value = jsonStringifyExtended(value as Dictionary, null, 2) as unknown as T;- } catch (e) {- const error = e as Error;- // Give more meaningful error message- if (error.message?.includes('Invalid string length')) {- error.message = 'Object is too large';- }- throw new Error(`The "value" parameter cannot be stringified to JSON: ${error.message}`);- }-- if (value === undefined) {- throw new Error(- 'The "value" parameter was stringified to JSON and returned undefined. ' +- "Make sure you're not trying to stringify an undefined value.",- );- }- }-- return value;-};-/*** The `KeyValueStore` class represents a key-value store, a simple data storage that is used* for saving and reading data records or files. Each data record is@@ -232,7 +200,53 @@ export class KeyValueStore {ow(key, ow.string.nonEmpty);const record = await this.client.getValue(key);- return (record?.value as T) ?? defaultValue ?? null;+ // A missing record falls back to the default; a record that parses to a falsy value (including+ // a stored literal `null`) is returned verbatim, so callers can tell "stored null" from "absent".+ if (!record) {+ return defaultValue ?? null;+ }++ // Storage clients are byte transports — the value is raw bytes; the frontend parses it here.+ return parseValue(record.value, record.contentType ?? null) as T;+ }++ /**+ * Reads a record from the key-value store without parsing the value.+ *+ * Use this when you need the raw bytes and the content type — for example, to run your own+ * parser (`simdjson`, a custom XML library, etc.) or to forward the bytes verbatim.+ *+ * There is no symmetric `setRecord` method, because {@apilink KeyValueStore.setValue} already+ * passes a `Buffer` (or `string` / `Stream`) through unchanged when an explicit `contentType`+ * is provided. To write pre-serialized bytes, call+ * `setValue(key, buffer, { contentType: 'application/json; charset=utf-8' })`.+ *+ * Returns `null` if the record does not exist.+ *+ * **Example usage:**+ * ```javascript+ * const store = await KeyValueStore.open();+ * const record = await store.getRecord('huge.json');+ * if (record) {+ * const data = simdjson.parse(record.value);+ * }+ * ```+ *+ * @param key+ * Unique key of the record. It can be at most 256 characters long and only consist+ * of the following characters: `a`-`z`, `A`-`Z`, `0`-`9` and `!-_.'()`+ */+ async getRecord(key: string): Promise<KeyValueStoreRawRecord | null> {+ checkStorageAccess();++ ow(key, ow.string.nonEmpty);+ const record = await this.client.getValue(key);+ if (!record) return null;++ return {+ value: record.value,+ contentType: record.contentType ?? null,+ };}/**@@ -301,7 +315,10 @@ export class KeyValueStore {const results: T[] = [];for (const item of page) {const record = await this.client.getValue(item.key);- if (record) results.push(mapRecord(item.key, record.value));+ if (record) {+ const parsed = parseValue(record.value, record.contentType ?? null);+ results.push(mapRecord(item.key, parsed));+ }}yield results;}@@ -375,15 +392,9 @@ export class KeyValueStore {message: `The "key" argument "${key}" must be at most 256 characters long and only contain the following characters: a-zA-Z0-9!-_.'()`,})),);- if (- options.contentType &&- !(- ow.isValid(value, ow.any(ow.string, ow.uint8Array)) ||- (ow.isValid(value, ow.object) && typeof (value as Dictionary).pipe === 'function')- )- ) {+ if (options.contentType && !(typeof value === 'string' || isBuffer(value) || isStream(value))) {throw new ArgumentError(- 'The "value" parameter must be a String, Buffer or Stream when "options.contentType" is specified.',+ 'The "value" parameter must be a String, Buffer, ArrayBuffer, TypedArray, or Stream when "options.contentType" is specified.',this.setValue,);}@@ -417,12 +428,12 @@ export class KeyValueStore {// In this case delete the record.if (value === null) return this.client.deleteValue(key);- value = maybeStringify(value, optionsCopy);+ const serialized = serializeValue(value, optionsCopy.contentType);return this.client.setValue({key,- value,- contentType: optionsCopy.contentType,+ value: serialized.value,+ contentType: serialized.contentType,});}@@ -745,6 +756,23 @@ export class KeyValueStore {return store.getValue<T>(key, defaultValue as T);}+ /**+ * Reads a record from the default {@apilink KeyValueStore} associated with the current crawler run+ * without parsing the value.+ *+ * This is just a convenient shortcut for {@apilink KeyValueStore.getRecord}. Returns `null` if the+ * record does not exist.+ *+ * @param key+ * Unique key of the record. It can be at most 256 characters long and only consist+ * of the following characters: `a`-`z`, `A`-`Z`, `0`-`9` and `!-_.'()`+ * @ignore+ */+ static async getRecord(key: string): Promise<KeyValueStoreRawRecord | null> {+ const store = await this.open();+ return store.getRecord(key);+ }+/*** Tests whether a record with the given key exists in the default {@apilink KeyValueStore} associated with the current crawler run.* @param key The queried record key.@@ -865,6 +893,15 @@ export interface KeyValueStoreOptions {client: KeyValueStoreClient;}+/**+ * A raw, unparsed key-value store record as returned by {@apilink KeyValueStore.getRecord}: the+ * verbatim bytes plus the content type, with parsing left to the caller.+ */+export interface KeyValueStoreRawRecord {+ value: Buffer | ArrayBuffer;+ contentType: string | null;+}+export interface RecordOptions {/*** Specifies a custom MIME content type of the record.diff --git a/packages/core/src/storages/key_value_store_codec.ts b/packages/core/src/storages/key_value_store_codec.tsnew file mode 100644index 000000000..07e6faec4--- /dev/null+++ b/packages/core/src/storages/key_value_store_codec.ts@@ -0,0 +1,138 @@+import type { Dictionary } from '@crawlee/types';+import contentTypeParser from 'content-type';+import { isBuffer, isStream } from '@crawlee/utils';+import JSON5 from 'json5';++import { jsonStringifyExtended } from '@apify/utilities';++const CONTENT_TYPE_JSON = 'application/json';+const STRINGIFIABLE_CONTENT_TYPE_RXS = [new RegExp(`^${CONTENT_TYPE_JSON}$`, 'i'), /^application\/.*xml$/i, /^text\//i];++/**+ * Canonical write path for key-value store records.+ *+ * When a content type is provided, the value passes through unchanged — it is the caller's+ * responsibility to supply a String/Buffer/Stream (the frontend validates this).+ *+ * When no content type is provided, it is inferred from the value's shape:+ * - Buffer / typed array / ArrayBuffer / stream → `application/octet-stream` (passthrough)+ * - `string` → `text/plain; charset=utf-8` (passthrough)+ * - anything else → `application/json; charset=utf-8` (serialized via `jsonStringifyExtended`)+ *+ * Does NOT drain streams — that is storage mechanics and stays in the storage client.+ *+ * Backend-independent.+ */+export function serializeValue(+ value: unknown,+ contentType?: string,+): {+ value: Buffer | ArrayBuffer | ArrayBufferView | string | NodeJS.ReadableStream | ReadableStream;+ contentType: string;+} {+ if (contentType !== null && contentType !== undefined) {+ return { value: value as Buffer | string | NodeJS.ReadableStream | ReadableStream, contentType };+ }++ if (isStream(value) || isBuffer(value)) {+ return {+ value,+ contentType: 'application/octet-stream',+ };+ }++ if (typeof value === 'string') {+ return { value, contentType: 'text/plain; charset=utf-8' };+ }++ let serialized: string;+ try {+ // Format JSON to simplify debugging, the overheads with compression is negligible+ serialized = jsonStringifyExtended(value as Dictionary, null, 2);+ } catch (e) {+ const error = e as Error;+ // Give more meaningful error message+ if (error.message?.includes('Invalid string length')) {+ error.message = 'Object is too large';+ }+ throw new Error(`The "value" parameter cannot be stringified to JSON: ${error.message}`);+ }++ if (serialized === undefined) {+ throw new Error(+ 'The "value" parameter was stringified to JSON and returned undefined. ' ++ "Make sure you're not trying to stringify an undefined value.",+ );+ }++ return { value: serialized, contentType: 'application/json; charset=utf-8' };+}++/**+ * Parses a Buffer or ArrayBuffer using the provided content type header.+ *+ * - application/json is returned as a parsed object.+ * - application/*xml and text/* are returned as strings.+ * - everything else is returned as original body.+ *+ * If the header includes a charset, the body will be stringified only+ * if the charset represents a known encoding to Node.js or Browser.+ *+ * Backend-independent — this is the canonical read path for the {@apilink KeyValueStore} frontend.+ */+export function parseValue(+ body: Buffer | ArrayBuffer | string,+ contentTypeHeader: string | null,+): string | Buffer | ArrayBuffer | Record<string, unknown> {+ // No content type at all → we have no basis for interpretation; hand back the raw value.+ if (contentTypeHeader === null) return body;++ let contentType: string;+ let charset: BufferEncoding;+ try {+ const result = contentTypeParser.parse(contentTypeHeader);+ contentType = result.type;+ charset = result.parameters.charset as BufferEncoding;+ } catch {+ // Unparseable header → keep the original value rather than a mangled string.+ return body;+ }++ // If we can't successfully interpret it, we return the original value rather than mangling it.+ if (!areDataStringifiable(contentType, charset)) return body;++ // Decode raw bytes using the resolved charset. An already-decoded string passes through (callers+ // may hand us one directly), avoiding a needless re-encode round-trip.+ const dataString = typeof body === 'string' ? body : isomorphicBufferToString(body, charset);++ return contentType === CONTENT_TYPE_JSON ? JSON5.parse(dataString) : dataString;+}++function isomorphicBufferToString(buffer: Buffer | ArrayBuffer, encoding: BufferEncoding): string {+ if (buffer.constructor.name !== ArrayBuffer.name) {+ return (buffer as Buffer).toString(encoding);+ }++ // In Node, wrap the ArrayBuffer in a Buffer so the resolved charset is honored (the caller already+ // checked it via `Buffer.isEncoding`). Only the browser, which lacks Buffer, is limited to UTF-8.+ if (typeof Buffer !== 'undefined') {+ return Buffer.from(buffer as ArrayBuffer).toString(encoding);+ }++ const decoder = new TextDecoder(encoding);+ return decoder.decode(new Uint8Array(buffer as ArrayBuffer));+}++function isCharsetStringifiable(charset: string): charset is BufferEncoding {+ if (!charset) return true; // hope that it's utf-8+ return Buffer.isEncoding(charset);+}++function isContentTypeStringifiable(contentType: string): boolean {+ if (!contentType) return false; // keep buffer+ return STRINGIFIABLE_CONTENT_TYPE_RXS.some((rx) => rx.test(contentType));+}++function areDataStringifiable(contentType: string, charset: string): boolean {+ return isContentTypeStringifiable(contentType) && isCharsetStringifiable(charset);+}diff --git a/packages/fs-storage/package.json b/packages/fs-storage/package.jsonindex ef6c35e52..75915cba8 100644--- a/packages/fs-storage/package.json+++ b/packages/fs-storage/package.json@@ -43,6 +43,7 @@},"dependencies": {"@crawlee/types": "workspace:*",+ "@crawlee/utils": "workspace:*","@sapphire/async-queue": "^1.5.5","@sapphire/shapeshift": "^4.0.0","content-type": "^1.0.5",diff --git a/packages/fs-storage/src/fs/key-value-store/fs.ts b/packages/fs-storage/src/fs/key-value-store/fs.tsindex e0d662801..03ff48ae6 100644--- a/packages/fs-storage/src/fs/key-value-store/fs.ts+++ b/packages/fs-storage/src/fs/key-value-store/fs.ts@@ -30,14 +30,15 @@ export class KeyValueFileSystemEntry implements StorageImplementation<InternalKeasync get(): Promise<InternalKeyRecord> {await this.fsQueue.wait();- let file: Buffer | string;+ let file: Buffer;try {file = await readFile(this.filePath);} catch {try {const noExtFilePath = resolveWithinDirectory(this.storeDirectory, this.rawRecord.key);- // Try without extension+ // Try without extension. Keep the raw bytes — interpretation (text vs. JSON) is the+ // KeyValueStore frontend's job; this client is a plain byte transport.file = await readFile(noExtFilePath);this.logger?.warning([@@ -47,7 +48,6 @@ export class KeyValueFileSystemEntry implements StorageImplementation<InternalKe'If you want to have correct interpretation of the file, you should add a file extension to the entry.',].join('\n'),);- file = file.toString('utf-8');this.filePath = noExtFilePath;} catch {// This is impossible to happen, but just in casediff --git a/packages/fs-storage/src/resource-clients/key-value-store.ts b/packages/fs-storage/src/resource-clients/key-value-store.tsindex be02b7cba..6fd58ac17 100644--- a/packages/fs-storage/src/resource-clients/key-value-store.ts+++ b/packages/fs-storage/src/resource-clients/key-value-store.ts@@ -6,11 +6,10 @@ import type * as storage from '@crawlee/types';import { s } from '@sapphire/shapeshift';import { scheduleBackgroundTask } from '../background-handler/index.js';-import { maybeParseBody } from '../body-parser.js';import type { StorageImplementation } from '../fs/common.js';import { createKeyValueStorageImplementation } from '../fs/key-value-store/index.js';import type { FileSystemStorageClient } from '../index.js';-import { isBuffer, isStream, resolveWithinDirectory } from '../utils.js';+import { isStream, resolveWithinDirectory, toBuffer } from '../utils.js';import { BaseClient } from './common/base-client.js';import mime from 'mime-types';@@ -170,21 +169,23 @@ export class KeyValueStoreClient extends BaseClient implements storage.KeyValueSconst entry = await storageEntry.get();+ // Return raw bytes + verbatim content type. Parsing is the frontend's job (see the+ // KeyValueStore codec); this client is a plain byte transport. The mime fallback+ // reconstructs the content type for on-disk records that lack one.const record: storage.KeyValueStoreRecord = {key: entry.key,- value: entry.value,- contentType: entry.contentType ?? (mime.contentType(entry.extension) as string),+ value: typeof entry.value === 'string' ? Buffer.from(entry.value, 'utf-8') : entry.value,+ // mime.contentType returns `false` for unknown extensions; fall back to undefined so the+ // frontend treats it as "no content type" rather than a bogus value.+ contentType: entry.contentType ?? (mime.contentType(entry.extension) || undefined),};- // Auto-parse the body (JSON → object, text → string, etc.)- record.value = maybeParseBody(record.value, record.contentType!);-this.updateTimestamps(false);return record;}- async setValue(record: storage.KeyValueStoreRecord): Promise<void> {+ async setValue(record: storage.KeyValueStoreInputRecord): Promise<void> {s.object({key: s.string().lengthGreaterThan(0),value: s.union([@@ -201,43 +202,31 @@ export class KeyValueStoreClient extends BaseClient implements storage.KeyValueS}).parse(record);const { key } = record;- let { value, contentType } = record;-- const valueIsStream = isStream(value);-- const isValueStreamOrBuffer = valueIsStream || isBuffer(value);- // To allow saving Objects to JSON without providing content type- if (!contentType) {- if (isValueStreamOrBuffer) contentType = 'application/octet-stream';- else if (typeof value === 'string') contentType = 'text/plain; charset=utf-8';- else contentType = 'application/json; charset=utf-8';- }+ let { value } = record;+ // The frontend (KeyValueStore codec) serializes the value and resolves its content type+ // before it reaches the client. We only need it here for on-disk extension bookkeeping.+ const contentType = record.contentType ?? 'application/octet-stream';const extension = mime.extension(contentType) || DEFAULT_LOCAL_FILE_EXTENSION;- const isContentTypeJson = extension === 'json';-- if (isContentTypeJson && !isValueStreamOrBuffer && typeof value !== 'string') {- try {- value = JSON.stringify(value, null, 2);- } catch (err: any) {- const msg = `The record value cannot be stringified to JSON. Please provide other content type.\nCause: ${err.message}`;- throw new Error(msg);- }- }-- if (valueIsStream) {+ // Draining a stream into a Buffer for storage is the client's responsibility.+ if (isStream(value)) {const chunks = [];for await (const chunk of value) {chunks.push(chunk);}- value = Buffer.concat(chunks);+ value = Buffer.concat(chunks as Buffer[]);}+ // The on-disk record holds raw bytes (or a string). Streams were drained above, so any+ // remaining non-string value is byte-like; normalize ArrayBuffer / typed-array views to Buffer.+ const normalizedValue: Buffer | string =+ typeof value === 'string' ? value : toBuffer(value as Buffer | ArrayBuffer | ArrayBufferView);+const _record = {extension,key,- value,+ value: normalizedValue,contentType,} satisfies InternalKeyRecord;diff --git a/packages/fs-storage/src/utils.ts b/packages/fs-storage/src/utils.tsindex 45686cd06..e4695949f 100644--- a/packages/fs-storage/src/utils.ts+++ b/packages/fs-storage/src/utils.ts@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';import { resolve, sep } from 'node:path';import type * as storage from '@crawlee/types';-import { s } from '@sapphire/shapeshift';+import { isBuffer, isStream, toBuffer } from '@crawlee/utils';import { REQUEST_ID_LENGTH } from './consts.js';@@ -51,23 +51,7 @@ export function uniqueKeyToRequestId(uniqueKey: string): string {return str.length > REQUEST_ID_LENGTH ? str.slice(0, REQUEST_ID_LENGTH) : str;}-export function isBuffer(value: unknown): boolean {- try {- s.union([s.instance(Buffer), s.instance(ArrayBuffer), s.typedArray()]).parse(value);-- return true;- } catch {- return false;- }-}--export function isStream(value: any): boolean {- return (- typeof value === 'object' &&- value &&- ['on', 'pipe'].every((key) => key in value && typeof value[key] === 'function')- );-}+export { isBuffer, isStream, toBuffer };export type BackgroundHandlerReceivedMessage = BackgroundHandlerUpdateMetadataMessage;diff --git a/packages/fs-storage/test/async-iteration.test.ts b/packages/fs-storage/test/async-iteration.test.tsindex c37d45470..616427f24 100644--- a/packages/fs-storage/test/async-iteration.test.ts+++ b/packages/fs-storage/test/async-iteration.test.ts@@ -71,7 +71,12 @@ describe('Async iteration support', () => {kvStore = await storage.createKeyValueStoreClient({ name: 'async-iteration-kvs' });for (const key of keys) {- await kvStore.setValue({ key, value: { data: key } });+ // The client is a byte-transport: pass serialized bytes + content type.+ await kvStore.setValue({+ key,+ value: JSON.stringify({ data: key }),+ contentType: 'application/json; charset=utf-8',+ });}});diff --git a/packages/fs-storage/test/fs-fallback.test.ts b/packages/fs-storage/test/fs-fallback.test.tsindex 908dab207..56d42f3da 100644--- a/packages/fs-storage/test/fs-fallback.test.ts+++ b/packages/fs-storage/test/fs-fallback.test.ts@@ -61,10 +61,12 @@ describe('fallback to fs for reading', () => {expect(defaultStoreInfo.name).toEqual('default');expect(defaultStoreInfo.createdAt).toEqual(expectedFsDate);+ // The client is a byte transport: it returns the raw on-disk bytes verbatim and leaves+ // parsing to the KeyValueStore frontend codec. So we expect a Buffer, not a parsed object.const input = await defaultStore.getValue('INPUT');expect(input).toStrictEqual<KeyValueStoreRecord>({key: 'INPUT',- value: { foo: 'bar but from fs' },+ value: Buffer.from(JSON.stringify({ foo: 'bar but from fs' })),contentType: 'application/json; charset=utf-8',});});@@ -72,10 +74,11 @@ describe('fallback to fs for reading', () => {test('attempting to read "other" key value store with no "__metadata__" present should read from fs, even if accessed without generating id first', async () => {const otherStore = await storage.createKeyValueStoreClient({ name: 'other' });+ // Byte transport: raw bytes out, parsing is the frontend's job.const input = await otherStore.getValue('INPUT');expect(input).toStrictEqual<KeyValueStoreRecord>({key: 'INPUT',- value: { foo: 'bar but from fs' },+ value: Buffer.from(JSON.stringify({ foo: 'bar but from fs' })),contentType: 'application/json; charset=utf-8',});});@@ -89,10 +92,11 @@ describe('fallback to fs for reading', () => {test('attempting to read "no-ext" key value store should load the missing extension file correctly', async () => {const noExtStore = await storage.createKeyValueStoreClient({ name: 'no-ext' });+ // Byte transport: the no-extension fallback also returns raw bytes now, not a decoded string.const input = await noExtStore.getValue('INPUT');expect(input).toStrictEqual<KeyValueStoreRecord>({key: 'INPUT',- value: JSON.stringify({ foo: 'bar but from fs' }),+ value: Buffer.from(JSON.stringify({ foo: 'bar but from fs' })),contentType: 'text/plain',});});diff --git a/packages/fs-storage/test/write-metadata.test.ts b/packages/fs-storage/test/write-metadata.test.tsindex d2a357f4f..901224935 100644--- a/packages/fs-storage/test/write-metadata.test.ts+++ b/packages/fs-storage/test/write-metadata.test.ts@@ -30,7 +30,8 @@ describe('writeMetadata option', () => {test('creating a key-value pair in a key-value store should not write __metadata__.json file for the value', async () => {const keyValueStore = await storage.createKeyValueStoreClient();- await keyValueStore.setValue({ key: 'foo', value: 'test' });+ // The client is a byte-transport: pass the content type so the on-disk extension is `txt`.+ await keyValueStore.setValue({ key: 'foo', value: 'test', contentType: 'text/plain; charset=utf-8' });const keyValueStoreInfo = await keyValueStore.getMetadata();const expectedFilePath = resolve(storage.keyValueStoresDirectory, `${keyValueStoreInfo.id}/foo.txt`);@@ -62,7 +63,8 @@ describe('writeMetadata option', () => {test('creating a key-value pair in a key-value store should write __metadata__.json file for the value', async () => {const keyValueStore = await storage.createKeyValueStoreClient();- await keyValueStore.setValue({ key: 'foo', value: 'test' });+ // The client is a byte-transport: pass the content type so the on-disk extension is `txt`.+ await keyValueStore.setValue({ key: 'foo', value: 'test', contentType: 'text/plain; charset=utf-8' });const keyValueStoreInfo = await keyValueStore.getMetadata();const expectedFilePath = resolve(storage.keyValueStoresDirectory, `${keyValueStoreInfo.id}/foo.txt`);diff --git a/packages/memory-storage/package.json b/packages/memory-storage/package.jsonindex 6bcc98532..086b89172 100644--- a/packages/memory-storage/package.json+++ b/packages/memory-storage/package.json@@ -43,6 +43,7 @@},"dependencies": {"@crawlee/types": "workspace:*",+ "@crawlee/utils": "workspace:*","@sapphire/async-queue": "^1.5.5","@sapphire/shapeshift": "^4.0.0","content-type": "^1.0.5",diff --git a/packages/memory-storage/src/body-parser.ts b/packages/memory-storage/src/body-parser.tsdeleted file mode 100644index 92c6ce172..000000000--- a/packages/memory-storage/src/body-parser.ts+++ /dev/null@@ -1,62 +0,0 @@-import contentTypeParser from 'content-type';-import JSON5 from 'json5';--const CONTENT_TYPE_JSON = 'application/json';-const STRINGIFIABLE_CONTENT_TYPE_RXS = [new RegExp(`^${CONTENT_TYPE_JSON}$`, 'i'), /^application\/.*xml$/i, /^text\//i];--/**- * Parses a Buffer or ArrayBuffer using the provided content type header.- *- * - application/json is returned as a parsed object.- * - application/*xml and text/* are returned as strings.- * - everything else is returned as original body.- *- * If the header includes a charset, the body will be stringified only- * if the charset represents a known encoding to Node.js or Browser.- */-export function maybeParseBody(- body: Buffer | ArrayBuffer,- contentTypeHeader: string,-): string | Buffer | ArrayBuffer | Record<string, unknown> {- let contentType: string;- let charset: BufferEncoding;- try {- const result = contentTypeParser.parse(contentTypeHeader);- contentType = result.type;- charset = result.parameters.charset as BufferEncoding;- } catch {- // can't parse, keep original body- return body;- }-- // If we can't successfully parse it, we return- // the original buffer rather than a mangled string.- if (!areDataStringifiable(contentType, charset)) return body;- const dataString = isomorphicBufferToString(body, charset);-- return contentType === CONTENT_TYPE_JSON ? JSON5.parse(dataString) : dataString;-}--function isomorphicBufferToString(buffer: Buffer | ArrayBuffer, encoding: BufferEncoding): string {- if (buffer.constructor.name !== ArrayBuffer.name) {- return buffer.toString(encoding);- }-- // Browser decoding only works with UTF-8.- const utf8decoder = new TextDecoder();- return utf8decoder.decode(new Uint8Array(buffer));-}--function isCharsetStringifiable(charset: string): charset is BufferEncoding {- if (!charset) return true; // hope that it's utf-8- return Buffer.isEncoding(charset);-}--function isContentTypeStringifiable(contentType: string): boolean {- if (!contentType) return false; // keep buffer- return STRINGIFIABLE_CONTENT_TYPE_RXS.some((rx) => rx.test(contentType));-}--function areDataStringifiable(contentType: string, charset: string): boolean {- return isContentTypeStringifiable(contentType) && isCharsetStringifiable(charset);-}diff --git a/packages/memory-storage/src/resource-clients/key-value-store.ts b/packages/memory-storage/src/resource-clients/key-value-store.tsindex 14e8ef273..a10103ab9 100644--- a/packages/memory-storage/src/resource-clients/key-value-store.ts+++ b/packages/memory-storage/src/resource-clients/key-value-store.ts@@ -3,9 +3,8 @@ import { randomUUID } from 'node:crypto';import type * as storage from '@crawlee/types';import { s } from '@sapphire/shapeshift';-import { maybeParseBody } from '../body-parser.js';import type { MemoryStorageClient } from '../index.js';-import { isBuffer, isStream } from '../utils.js';+import { isStream, toBuffer } from '../utils.js';import { BaseClient } from './common/base-client.js';import mime from 'mime-types';@@ -31,7 +30,7 @@ export interface KeyValueStoreClientOptions {export interface InternalKeyRecord {key: string;- value: Buffer | string;+ value: Buffer;contentType?: string;extension: string;}@@ -168,21 +167,22 @@ export class KeyValueStoreClient extends BaseClient implements storage.KeyValueSreturn undefined;}+ // Return raw bytes + verbatim content type. Parsing is the frontend's job (see the+ // KeyValueStore codec). The mime fallback reconstructs the content type for on-disk records.const record: storage.KeyValueStoreRecord = {key: entry.key,value: entry.value,- contentType: entry.contentType ?? (mime.contentType(entry.extension) as string),+ // mime.contentType returns `false` for unknown extensions; fall back to undefined so the+ // frontend treats it as "no content type" rather than a bogus value.+ contentType: entry.contentType ?? (mime.contentType(entry.extension) || undefined),};- // Auto-parse the body (JSON → object, text → string, etc.)- record.value = maybeParseBody(record.value, record.contentType!);-this.updateTimestamps(false);return record;}- async setValue(record: storage.KeyValueStoreRecord): Promise<void> {+ async setValue(record: storage.KeyValueStoreInputRecord): Promise<void> {s.object({key: s.string().lengthGreaterThan(0),value: s.union([@@ -199,32 +199,15 @@ export class KeyValueStoreClient extends BaseClient implements storage.KeyValueS}).parse(record);const { key } = record;- let { value, contentType } = record;-- const valueIsStream = isStream(value);-- const isValueStreamOrBuffer = valueIsStream || isBuffer(value);- // To allow saving Objects to JSON without providing content type- if (!contentType) {- if (isValueStreamOrBuffer) contentType = 'application/octet-stream';- else if (typeof value === 'string') contentType = 'text/plain; charset=utf-8';- else contentType = 'application/json; charset=utf-8';- }+ let { value } = record;+ // The frontend (KeyValueStore codec) serializes the value and resolves its content type+ // before it reaches the client. We only need it here for on-disk extension bookkeeping.+ const contentType = record.contentType ?? 'application/octet-stream';const extension = mime.extension(contentType) || DEFAULT_LOCAL_FILE_EXTENSION;- const isContentTypeJson = extension === 'json';-- if (isContentTypeJson && !isValueStreamOrBuffer && typeof value !== 'string') {- try {- value = JSON.stringify(value, null, 2);- } catch (err: any) {- const msg = `The record value cannot be stringified to JSON. Please provide other content type.\nCause: ${err.message}`;- throw new Error(msg);- }- }-- if (valueIsStream) {+ // Draining a stream into a Buffer for storage is the client's responsibility.+ if (isStream(value)) {const chunks = [];for await (const chunk of value) {chunks.push(chunk);@@ -232,10 +215,18 @@ export class KeyValueStoreClient extends BaseClient implements storage.KeyValueSvalue = Buffer.concat(chunks);}+ // This client is a byte transport: it stores and returns raw bytes regardless of the input+ // shape. Streams were drained above; encode strings to UTF-8 bytes and normalize+ // ArrayBuffer / typed-array views to a Buffer over the same memory.+ const normalizedValue: Buffer =+ typeof value === 'string'+ ? Buffer.from(value, 'utf-8')+ : toBuffer(value as Buffer | ArrayBuffer | ArrayBufferView);+const _record = {extension,key,- value,+ value: normalizedValue,contentType,} satisfies InternalKeyRecord;diff --git a/packages/memory-storage/src/utils.ts b/packages/memory-storage/src/utils.tsindex 0991b0af7..36cded92e 100644--- a/packages/memory-storage/src/utils.ts+++ b/packages/memory-storage/src/utils.ts@@ -1,7 +1,7 @@import { createHash } from 'node:crypto';import { resolve, sep } from 'node:path';-import { s } from '@sapphire/shapeshift';+import { isBuffer, isStream, toBuffer } from '@crawlee/utils';import { REQUEST_ID_LENGTH } from './consts.js';@@ -50,20 +50,4 @@ export function uniqueKeyToRequestId(uniqueKey: string): string {return str.length > REQUEST_ID_LENGTH ? str.slice(0, REQUEST_ID_LENGTH) : str;}-export function isBuffer(value: unknown): boolean {- try {- s.union([s.instance(Buffer), s.instance(ArrayBuffer), s.typedArray()]).parse(value);-- return true;- } catch {- return false;- }-}--export function isStream(value: any): boolean {- return (- typeof value === 'object' &&- value &&- ['on', 'pipe'].every((key) => key in value && typeof value[key] === 'function')- );-}+export { isBuffer, isStream, toBuffer };diff --git a/packages/memory-storage/test/async-iteration.test.ts b/packages/memory-storage/test/async-iteration.test.tsindex 3105c1b46..b7553e017 100644--- a/packages/memory-storage/test/async-iteration.test.ts+++ b/packages/memory-storage/test/async-iteration.test.ts@@ -61,7 +61,12 @@ describe('Async iteration support', () => {kvStore = await storage.createKeyValueStoreClient({ name: 'async-iteration-kvs' });for (const key of keys) {- await kvStore.setValue({ key, value: { data: key } });+ // The client is a byte-transport: pass serialized bytes + content type.+ await kvStore.setValue({+ key,+ value: JSON.stringify({ data: key }),+ contentType: 'application/json; charset=utf-8',+ });}});diff --git a/packages/memory-storage/test/key-value-store/purge.test.ts b/packages/memory-storage/test/key-value-store/purge.test.tsindex e64a5371a..fc4a8452d 100644--- a/packages/memory-storage/test/key-value-store/purge.test.ts+++ b/packages/memory-storage/test/key-value-store/purge.test.ts@@ -6,14 +6,22 @@ describe('MemoryStorageClient.purge preserves the default key-value store input'const storage = new MemoryStorageClient();const store: KeyValueStoreClient = await storage.createKeyValueStoreClient({ name: 'default' });- await store.setValue({ key: 'INPUT', value: { hello: 'world' } });- await store.setValue({ key: 'some-other-key', value: { foo: 'bar' } });+ await store.setValue({+ key: 'INPUT',+ value: JSON.stringify({ hello: 'world' }),+ contentType: 'application/json; charset=utf-8',+ });+ await store.setValue({+ key: 'some-other-key',+ value: JSON.stringify({ foo: 'bar' }),+ contentType: 'application/json; charset=utf-8',+ });await storage.purge();// INPUT must survive the purge (parity with FileSystemStorageClient)...const input = await store.getValue('INPUT');- expect(input?.value).toEqual({ hello: 'world' });+ expect(input?.value.toString()).toBe(JSON.stringify({ hello: 'world' }));// ...while every other record is removed.expect(await store.getValue('some-other-key')).toBeUndefined();@@ -25,11 +33,15 @@ describe('MemoryStorageClient.purge preserves the default key-value store input'const storage = new MemoryStorageClient();const store: KeyValueStoreClient = await storage.createKeyValueStoreClient({ name: 'not-default' });- await store.setValue({ key: 'INPUT', value: { hello: 'world' } });+ await store.setValue({+ key: 'INPUT',+ value: JSON.stringify({ hello: 'world' }),+ contentType: 'application/json; charset=utf-8',+ });// `purge` on the storage client only touches default storages, so a named store keeps its data.await storage.purge();- expect((await store.getValue('INPUT'))?.value).toEqual({ hello: 'world' });+ expect((await store.getValue('INPUT'))?.value.toString()).toBe(JSON.stringify({ hello: 'world' }));// Purging the store directly clears everything, including INPUT.await store.purge();diff --git a/packages/types/src/storages.ts b/packages/types/src/storages.tsindex 1bda98559..21e9b3bf1 100644--- a/packages/types/src/storages.ts+++ b/packages/types/src/storages.ts@@ -96,9 +96,41 @@ export interface KeyValueStoreInfo {stats?: KeyValueStoreStats;}+/**+ * The value a serialized record carries on the way *into* a storage client (`setValue`).+ *+ * The `KeyValueStore` frontend has already serialized by this point, so it is a pre-serialized+ * string, raw bytes (`Buffer` / `ArrayBuffer` / typed array), or a stream the client drains.+ */+export type KeyValueStoreRecordInputValue =+ | Buffer+ | ArrayBuffer+ | ArrayBufferView+ | string+ | NodeJS.ReadableStream+ | ReadableStream;++/**+ * A record as returned by a storage client (`getValue`).+ *+ * Storage clients are byte transports: they persist and return bytes verbatim and never serialize+ * or parse. Interpretation is the `KeyValueStore` frontend's job (it parses according to the content+ * type via `parseValue`). The value is therefore always raw bytes — a `Buffer` (Node) or an+ * `ArrayBuffer` (browser backends).+ */export interface KeyValueStoreRecord {key: string;- value: any;+ value: Buffer | ArrayBuffer;+ contentType?: string;+}++/**+ * A record passed to a storage client for writing (`setValue`). Like {@link KeyValueStoreRecord} but+ * with the lenient, pre-serialized {@link KeyValueStoreRecordInputValue} for the value.+ */+export interface KeyValueStoreInputRecord {+ key: string;+ value: KeyValueStoreRecordInputValue;contentType?: string;}@@ -135,11 +167,16 @@ export interface KeyValueStoreClient {/** Remove all records from the store but keep the store itself. */purge(): Promise<void>;- /** Get a record value by key. Returns the parsed value or `undefined` if not found. */+ /**+ * Get a record by key. Returns the raw bytes plus content type, or `undefined` if not found.+ *+ * Clients are byte transports and must not parse the body — the `KeyValueStore` frontend+ * interprets it according to the content type.+ */getValue(key: string): Promise<KeyValueStoreRecord | undefined>;/** Set a record value. */- setValue(record: KeyValueStoreRecord): Promise<void>;+ setValue(record: KeyValueStoreInputRecord): Promise<void>;/** Delete a record by key. */deleteValue(key: string): Promise<void>;diff --git a/packages/utils/src/internals/general.ts b/packages/utils/src/internals/general.tsindex 6df1da439..cb623691c 100644--- a/packages/utils/src/internals/general.ts+++ b/packages/utils/src/internals/general.ts@@ -193,3 +193,55 @@ export function expandShadowRoots(document: Document): string {return document.documentElement.outerHTML;}++/**+ * Checks if the given value is a Node.js Stream or a Web API ReadableStream.+ * @ignore+ */+export function isStream(value: unknown): value is NodeJS.ReadableStream | ReadableStream {+ if (typeof value !== 'object' || value === null) {+ return false;+ }++ // A Node.js Readable is both pipeable and async-iterable; a Web ReadableStream exposes pipeTo.+ // Requiring async-iterability for the `pipe` branch rejects plain `{ pipe }` ducks that would+ // otherwise blow up later in the storage clients' drain loop with a cryptic TypeError.+ const isNodeStream =+ typeof (value as any).pipe === 'function' && typeof (value as any)[Symbol.asyncIterator] === 'function';+ const isWebStream = typeof (value as any).pipeTo === 'function';++ return isNodeStream || isWebStream;+}++/**+ * Checks if the given value is a Node.js Buffer, ArrayBuffer, or TypedArray.+ * @ignore+ */+export function isBuffer(value: unknown): value is Buffer | ArrayBuffer | ArrayBufferView {+ return (+ value != null &&+ typeof value === 'object' &&+ (Buffer.isBuffer(value) ||+ value instanceof ArrayBuffer ||+ ArrayBuffer.isView(value) ||+ (value as any).constructor?.name === 'Buffer')+ );+}++/**+ * Converts a byte-like value (Buffer, ArrayBuffer, or any typed-array / DataView) into a Buffer over+ * the exact same bytes, honoring `byteOffset` / `byteLength` for views. Existing Buffers are returned+ * as-is. Used by storage clients, which persist raw bytes regardless of the input's concrete shape.+ * @ignore+ */+export function toBuffer(value: Buffer | ArrayBuffer | ArrayBufferView): Buffer {+ if (Buffer.isBuffer(value)) {+ return value;+ }++ if (value instanceof ArrayBuffer) {+ return Buffer.from(value);+ }++ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 07ea31362..86056940d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -449,6 +449,9 @@ importers:'@vladfrangu/async_event_emitter':specifier: ^2.4.6version: 2.4.7+ content-type:+ specifier: ^1.0.5+ version: 1.0.5csv-stringify:specifier: ^6.5.2version: 6.7.0@@ -548,6 +551,9 @@ importers:'@crawlee/types':specifier: workspace:*version: link:../types+ '@crawlee/utils':+ specifier: workspace:*+ version: link:../utils'@sapphire/async-queue':specifier: ^1.5.5version: 1.5.5@@ -725,6 +731,9 @@ importers:'@crawlee/types':specifier: workspace:*version: link:../types+ '@crawlee/utils':+ specifier: workspace:*+ version: link:../utils'@sapphire/async-queue':specifier: ^1.5.5version: 1.5.5diff --git a/test/core/crawlers/adaptive_playwright_crawler.test.ts b/test/core/crawlers/adaptive_playwright_crawler.test.tsindex e01344e0b..ff2e6d95a 100644--- a/test/core/crawlers/adaptive_playwright_crawler.test.ts+++ b/test/core/crawlers/adaptive_playwright_crawler.test.ts@@ -1,7 +1,7 @@import type { Server } from 'node:http';import type { AddressInfo } from 'node:net';-import { Configuration, type Dictionary, EventType, KeyValueStore, serviceLocator } from '@crawlee/core';+import { type Dictionary, EventType, KeyValueStore, serviceLocator } from '@crawlee/core';import type {AdaptivePlaywrightCrawlerContext,AdaptivePlaywrightCrawlerOptions,@@ -452,8 +452,8 @@ describe('AdaptivePlaywrightCrawler', () => {);await crawler.run();- const state = await localStorageEmulator.getState();- expect(state!.value).toEqual({ count: 3 });+ // getState reads through the frontend, so the value is already parsed.+ expect(await localStorageEmulator.getState()).toEqual({ count: 3 });});test('should return deeply equal but not identical state objects across handler runs', async () => {@@ -524,11 +524,12 @@ describe('AdaptivePlaywrightCrawler', () => {);await crawler.run();- const store = await localStorageEmulator.getKeyValueStore();- expect((await store.getValue('1'))!.value).toEqual({ content: 42 });- expect((await store.getValue('2'))!.value).toEqual({ content: 42 });- expect((await store.getValue('3'))!.value).toEqual({ content: 42 });+ const store = await KeyValueStore.open();++ await expect(store.getValue('1')).resolves.toEqual({ content: 42 });+ await expect(store.getValue('2')).resolves.toEqual({ content: 42 });+ await expect(store.getValue('3')).resolves.toEqual({ content: 42 });});test('should not allow direct key-value store manipulation', async () => {diff --git a/test/core/crawlers/rendering_type_predictor.test.ts b/test/core/crawlers/rendering_type_predictor.test.tsindex 9abedb8a5..d64af886d 100644--- a/test/core/crawlers/rendering_type_predictor.test.ts+++ b/test/core/crawlers/rendering_type_predictor.test.ts@@ -1,4 +1,4 @@-import { Request } from '@crawlee/core';+import { KeyValueStore, Request } from '@crawlee/core';import { RenderingTypePredictor } from '@crawlee/playwright';import { afterEach, beforeEach, describe, expect, it } from 'vitest';@@ -34,16 +34,15 @@ describe('RenderingTypePredictor', () => {predictor.storeResult(clientRequest, 'clientOnly');// Persist the state- const store = await localStorageEmulator.getKeyValueStore();+ const store = await KeyValueStore.open();// eslint-disable-next-line dot-notationawait predictor['state'].persistState(); // Access private state for persistence- // Verify state was persisted- const persistedRecord = await store.getValue(persistStateKey);- expect(persistedRecord).not.toBeNull();- expect(persistedRecord?.value).toBeDefined();-- const parsedState = JSON.parse(persistedRecord!.value as string);+ // RecoverableState persists with a `text/plain` content type on purpose (it owns+ // (de)serialization), so the frontend hands back the raw serialized string here.+ const serializedState = await store.getValue<string>(persistStateKey);+ expect(serializedState).not.toBeNull();+ const parsedState = JSON.parse(serializedState!);expect(parsedState).toHaveProperty('logreg');expect(parsedState).toHaveProperty('detectionResults');diff --git a/test/core/recoverable_state.test.ts b/test/core/recoverable_state.test.tsindex c5a659d3e..2bb567e46 100644--- a/test/core/recoverable_state.test.ts+++ b/test/core/recoverable_state.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { KeyValueStore } from '../../packages/core/src/index.js';import { RecoverableState } from '../../packages/core/src/recoverable_state.js';import { MemoryStorageEmulator } from '../shared/MemoryStorageEmulator.js';@@ -179,10 +180,10 @@ describe('RecoverableState', () => {recoverableState.currentValue.data.value = 'updated';await recoverableState.persistState();- const persistedState = JSON.parse(- (await (await localStorageEmulator.getKeyValueStore()).getValue('test-key'))?.value,- );- expect(persistedState).toMatchObject({+ // RecoverableState persists with a `text/plain` content type on purpose (it owns+ // (de)serialization), so the frontend hands back the raw serialized string here.+ const persistedState = await (await KeyValueStore.open()).getValue<string>('test-key');+ expect(JSON.parse(persistedState!)).toMatchObject({data: { value: 'updated' },});diff --git a/test/core/storages/key_value_store.test.ts b/test/core/storages/key_value_store.test.tsindex 41f0ed767..6c46efff3 100644--- a/test/core/storages/key_value_store.test.ts+++ b/test/core/storages/key_value_store.test.ts@@ -1,7 +1,8 @@import { PassThrough } from 'node:stream';-import { KeyValueStore, maybeStringify, serviceLocator } from '@crawlee/core';+import { KeyValueStore, serviceLocator } from '@crawlee/core';import type { Dictionary } from '@crawlee/utils';+import { toBuffer } from '@crawlee/utils';import { MemoryStorageEmulator } from '../../shared/MemoryStorageEmulator.js';const localStorageEmulator = new MemoryStorageEmulator();@@ -52,7 +53,8 @@ describe('KeyValueStore', () => {.spyOn(store.client, 'getValue').mockResolvedValueOnce({key: 'key-1',- value: record,+ // The client now returns raw bytes; the frontend parses them.+ value: Buffer.from(recordStr),contentType: 'application/json; charset=utf-8',});@@ -182,7 +184,7 @@ describe('KeyValueStore', () => {);const valueErrMsg =- 'The "value" parameter must be a String, Buffer or Stream when "options.contentType" is specified';+ 'The "value" parameter must be a String, Buffer, ArrayBuffer, TypedArray, or Stream when "options.contentType" is specified';await expect(store.setValue('key', {}, { contentType: 'image/png' })).rejects.toThrow(valueErrMsg);await expect(store.setValue('key', 12345, { contentType: 'image/png' })).rejects.toThrow(valueErrMsg);await expect(store.setValue('key', () => {}, { contentType: 'image/png' })).rejects.toThrow(valueErrMsg);@@ -214,12 +216,12 @@ describe('KeyValueStore', () => {const contTypeRedundantErrMsg = 'Expected property string `contentType` to not be empty in object';await expect(store.setValue('key', null, { contentType: 'image/png' })).rejects.toThrow(- 'The "value" parameter must be a String, Buffer or Stream when "options.contentType" is specified.',+ 'The "value" parameter must be a String, Buffer, ArrayBuffer, TypedArray, or Stream when "options.contentType" is specified.',);await expect(store.setValue('key', null, { contentType: '' })).rejects.toThrow(contTypeRedundantErrMsg);// @ts-expect-error Type '{}' is not assignable to type 'string'.await expect(store.setValue('key', null, { contentType: {} })).rejects.toThrow(- 'The "value" parameter must be a String, Buffer or Stream when "options.contentType" is specified.',+ 'The "value" parameter must be a String, Buffer, ArrayBuffer, TypedArray, or Stream when "options.contentType" is specified.',);// @ts-expect-error Type 'number' is not assignable to type 'string'.@@ -354,6 +356,112 @@ describe('KeyValueStore', () => {});});+ describe('round-trips through the real storage client (no content type)', () => {+ test('object: setValue → getValue returns the same object, stored as application/json', async () => {+ const store = await KeyValueStore.open();+ const original = { foo: 'bar', n: 1 };+ await store.setValue('obj', original);++ await expect(store.getValue('obj')).resolves.toEqual(original);+ const record = await store.getRecord('obj');+ expect(record!.contentType).toBe('application/json; charset=utf-8');+ });++ test('string: setValue → getValue returns the same string, stored as text/plain (not JSON-wrapped)', async () => {+ const store = await KeyValueStore.open();+ await store.setValue('str', 'hello world');++ await expect(store.getValue('str')).resolves.toBe('hello world');+ const record = await store.getRecord('str');+ expect(record!.contentType).toBe('text/plain; charset=utf-8');+ // Bytes are the raw string, not the JSON-wrapped `'"hello world"'` the old code produced.+ expect(record!.value.toString()).toBe('hello world');+ });++ test('Buffer: setValue → getValue returns the same Buffer, stored as octet-stream (not JSON-mangled)', async () => {+ const store = await KeyValueStore.open();+ const original = Buffer.from([0xde, 0xad, 0xbe, 0xef]);+ await store.setValue('buf', original);++ const value = await store.getValue('buf');+ expect(Buffer.isBuffer(value)).toBe(true);+ expect((value as Buffer).equals(original)).toBe(true);++ const record = await store.getRecord('buf');+ expect(record!.contentType).toBe('application/octet-stream');+ expect(toBuffer(record!.value).equals(original)).toBe(true);+ });+ });++ describe('pre-serialized JSON via setValue (caller owns the bytes)', () => {+ test('Buffer containing JSON + explicit application/json CT round-trips as a parsed object', async () => {+ const store = await KeyValueStore.open();+ const original = { foo: 'bar', n: 1 };+ const preSerialized = Buffer.from(JSON.stringify(original));++ await store.setValue('k', preSerialized, { contentType: 'application/json; charset=utf-8' });++ // getValue parses the bytes back into the original object.+ expect(await store.getValue('k')).toEqual(original);+ });++ test('string containing JSON + explicit application/json CT round-trips as a parsed object', async () => {+ const store = await KeyValueStore.open();+ const original = [1, 2, 3];++ await store.setValue('k', JSON.stringify(original), {+ contentType: 'application/json; charset=utf-8',+ });++ expect(await store.getValue('k')).toEqual(original);+ });+ });++ describe('getRecord', () => {+ test('returns null for a missing key', async () => {+ const store = await KeyValueStore.open();+ expect(await store.getRecord('missing')).toBeNull();+ });++ test('returns raw bytes + content type without parsing JSON', async () => {+ const store = await KeyValueStore.open();+ const original = { foo: 'bar', n: 1 };+ await store.setValue('obj', original);++ const record = await store.getRecord('obj');+ expect(record).not.toBeNull();+ expect(record!.contentType).toMatch(/^application\/json/);+ // Bytes are the serialized JSON, not the parsed object — the caller does the parsing.+ const asText = toBuffer(record!.value).toString('utf-8');+ expect(JSON.parse(asText)).toEqual(original);+ });++ test('returns the exact bytes a caller wrote with an explicit content type', async () => {+ const store = await KeyValueStore.open();+ const preSerialized = Buffer.from(JSON.stringify({ a: 1 }));++ await store.setValue('k', preSerialized, { contentType: 'application/json; charset=utf-8' });++ const record = await store.getRecord('k');+ expect(record).not.toBeNull();+ expect(record!.contentType).toBe('application/json; charset=utf-8');+ const asText = toBuffer(record!.value).toString('utf-8');+ expect(asText).toBe(preSerialized.toString());+ });++ test('returns a Buffer for octet-stream records', async () => {+ const store = await KeyValueStore.open();+ const original = Buffer.from([0xde, 0xad, 0xbe, 0xef]);+ await store.setValue('buf', original);++ const record = await store.getRecord('buf');+ expect(record).not.toBeNull();+ expect(record!.contentType).toBe('application/octet-stream');+ expect(Buffer.isBuffer(record!.value)).toBe(true);+ expect((record!.value as Buffer).equals(original)).toBe(true);+ });+ });+// TODO move to actor sdk tests before splitting the repos// describe('getPublicUrl', () => {// test('should return the url of a file in apify cloud', async () => {@@ -371,22 +479,6 @@ describe('KeyValueStore', () => {// });// });- describe('maybeStringify()', () => {- test('should work', () => {- expect(maybeStringify({ foo: 'bar' }, { contentType: null as any })).toBe('{\n "foo": "bar"\n}');- expect(maybeStringify({ foo: 'bar' }, { contentType: undefined })).toBe('{\n "foo": "bar"\n}');-- expect(maybeStringify('xxx', { contentType: undefined })).toBe('"xxx"');- expect(maybeStringify('xxx', { contentType: 'something' })).toBe('xxx');-- const obj = {} as Dictionary;- obj.self = obj;- expect(() => maybeStringify(obj, { contentType: null as any })).toThrow(- 'The "value" parameter cannot be stringified to JSON: Converting circular structure to JSON',- );- });- });-describe('getFileNameRegexp()', () => {const getFileNameRegexp = (key: string) => {const safeKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');diff --git a/test/core/storages/key_value_store_codec.test.ts b/test/core/storages/key_value_store_codec.test.tsnew file mode 100644index 000000000..bb10d41a1--- /dev/null+++ b/test/core/storages/key_value_store_codec.test.ts@@ -0,0 +1,153 @@+import { Readable } from 'node:stream';++import { parseValue, serializeValue } from '@crawlee/core';++describe('key_value_store_codec', () => {+ describe('serializeValue()', () => {+ test('no content type → JSON-serializes object and infers json content type', () => {+ const { value, contentType } = serializeValue({ foo: 'bar' });+ expect(value).toBe('{\n "foo": "bar"\n}');+ expect(contentType).toBe('application/json; charset=utf-8');+ });++ test('no content type + string → text/plain passthrough', () => {+ const { value, contentType } = serializeValue('xxx');+ expect(value).toBe('xxx');+ expect(contentType).toBe('text/plain; charset=utf-8');+ });++ test('no content type + Buffer → octet-stream passthrough', () => {+ const buf = Buffer.from([0xde, 0xad, 0xbe, 0xef]);+ const { value, contentType } = serializeValue(buf);+ expect(value).toBe(buf);+ expect(contentType).toBe('application/octet-stream');+ });++ test('no content type + typed array → octet-stream passthrough', () => {+ const u8 = new Uint8Array([1, 2, 3]);+ const { value, contentType } = serializeValue(u8);+ expect(value).toBe(u8);+ expect(contentType).toBe('application/octet-stream');+ });++ test('no content type + stream → octet-stream passthrough', () => {+ const stream = Readable.from(Buffer.from('data'));+ const { value, contentType } = serializeValue(stream);+ expect(value).toBe(stream);+ expect(contentType).toBe('application/octet-stream');+ });++ test('explicit content type → value passes through unchanged', () => {+ const { value, contentType } = serializeValue('xxx', 'text/plain; charset=utf-8');+ expect(value).toBe('xxx');+ expect(contentType).toBe('text/plain; charset=utf-8');++ const buf = Buffer.from('bytes');+ const buffered = serializeValue(buf, 'image/jpeg');+ expect(buffered.value).toBe(buf);+ expect(buffered.contentType).toBe('image/jpeg');+ });++ test('"Object is too large" remap', () => {+ const tooLong = {+ toJSON() {+ throw new Error('Invalid string length');+ },+ };+ expect(() => serializeValue(tooLong)).toThrow(+ 'The "value" parameter cannot be stringified to JSON: Object is too large',+ );+ });++ test('circular structure error is surfaced', () => {+ const obj: Record<string, unknown> = {};+ obj.self = obj;+ expect(() => serializeValue(obj)).toThrow(+ 'The "value" parameter cannot be stringified to JSON: Converting circular structure to JSON',+ );+ });++ test('undefined-after-stringify guard', () => {+ expect(() => serializeValue(undefined)).toThrow(+ 'The "value" parameter was stringified to JSON and returned undefined.',+ );+ });+ });++ describe('parseValue()', () => {+ test('json content type → parsed object', () => {+ const body = Buffer.from('{"foo":"bar"}');+ expect(parseValue(body, 'application/json; charset=utf-8')).toEqual({ foo: 'bar' });+ });++ test('text/* → string', () => {+ const body = Buffer.from('plain text');+ expect(parseValue(body, 'text/plain; charset=utf-8')).toBe('plain text');+ });++ test('application/*xml → string', () => {+ const body = Buffer.from('<root/>');+ expect(parseValue(body, 'application/xml')).toBe('<root/>');+ });++ test('unknown content type → raw buffer', () => {+ const body = Buffer.from([0, 1, 2, 3]);+ expect(parseValue(body, 'application/octet-stream')).toBe(body);+ });++ test('unknown charset → raw buffer', () => {+ const body = Buffer.from('text');+ expect(parseValue(body, 'text/plain; charset=not-a-real-charset')).toBe(body);+ });++ test('null content type → raw buffer', () => {+ const body = Buffer.from('text');+ expect(parseValue(body, null)).toBe(body);+ });++ test('unparseable content type header → raw buffer', () => {+ const body = Buffer.from('text');+ expect(parseValue(body, 'this is not a valid header')).toBe(body);+ });++ test('ArrayBuffer input is decoded as UTF-8', () => {+ const source = Buffer.from('{"a":1}');+ const arrayBuffer = source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);+ expect(parseValue(arrayBuffer, 'application/json')).toEqual({ a: 1 });+ });+ });++ describe('round-trips', () => {+ test('object → json → object', () => {+ const original = { foo: 'bar', nested: { n: 1 } };+ const { value, contentType } = serializeValue(original);+ expect(parseValue(Buffer.from(value as string), contentType)).toEqual(original);+ });++ test('string → text → string', () => {+ const original = 'hello world';+ const { value, contentType } = serializeValue(original, 'text/plain; charset=utf-8');+ expect(parseValue(Buffer.from(value as string), contentType)).toBe(original);+ });++ test('Buffer → octet-stream → Buffer', () => {+ const original = Buffer.from([1, 2, 3, 4]);+ const { value, contentType } = serializeValue(original, 'application/octet-stream');+ expect(parseValue(value as Buffer, contentType)).toBe(original);+ });++ test('no content type: string round-trips as a string', () => {+ const original = 'hello world';+ const { value, contentType } = serializeValue(original);+ expect(parseValue(Buffer.from(value as string), contentType)).toBe(original);+ });++ test('no content type: Buffer round-trips as a Buffer (not JSON-mangled)', () => {+ const original = Buffer.from([0xde, 0xad, 0xbe, 0xef]);+ const { value, contentType } = serializeValue(original);+ const parsed = parseValue(value as Buffer, contentType);+ expect(Buffer.isBuffer(parsed)).toBe(true);+ expect((parsed as Buffer).equals(original)).toBe(true);+ });+ });+});diff --git a/test/core/storages/key_value_store_fs_roundtrip.test.ts b/test/core/storages/key_value_store_fs_roundtrip.test.tsnew file mode 100644index 000000000..ddd7e899d--- /dev/null+++ b/test/core/storages/key_value_store_fs_roundtrip.test.ts@@ -0,0 +1,96 @@+import { resolve } from 'node:path';++import { KeyValueStore, serviceLocator } from '@crawlee/core';+import { FileSystemStorageClient } from '@crawlee/fs-storage';+import { ensureDir, rm } from 'fs-extra';++import { cryptoRandomObjectId } from '@apify/utilities';++/**+ * Regression guard for the "centralize KVS value semantics" refactor.+ *+ * The core unit tests run against {@link MemoryStorageEmulator}, so they never exercise the+ * default {@link FileSystemStorageClient} backend. After moving serialize/parse into the+ * `KeyValueStore` frontend, the backend must be a pure byte transport — if a backend still parses+ * the body itself, the frontend would double-parse (`JSON5.parse("[object Object]")`) and throw.+ *+ * These tests wire the real frontend to the real fs-storage backend and assert a clean round-trip.+ */+describe('KeyValueStore frontend over FileSystemStorageClient (byte-transport contract)', () => {+ const localStorageDir = resolve(import.meta.dirname, '..', 'tmp', 'fs-kvs-roundtrip', cryptoRandomObjectId(10));++ beforeEach(async () => {+ serviceLocator.reset();+ await ensureDir(localStorageDir);+ serviceLocator.setStorageClient(new FileSystemStorageClient({ localDataDirectory: localStorageDir }));+ });++ afterAll(async () => {+ await rm(localStorageDir, { force: true, recursive: true });+ serviceLocator.getStorageInstanceManager().clearCache();+ });++ test('round-trips a JSON object without double-parsing', async () => {+ const store = await KeyValueStore.open();+ await store.setValue('OUTPUT', { foo: 'bar', nested: { count: 42 } });++ await expect(store.getValue('OUTPUT')).resolves.toEqual({ foo: 'bar', nested: { count: 42 } });+ });++ test('round-trips a string with an explicit content type', async () => {+ const store = await KeyValueStore.open();+ await store.setValue('TEXT', 'hello world', { contentType: 'text/plain; charset=utf-8' });++ await expect(store.getValue('TEXT')).resolves.toBe('hello world');+ });++ test('round-trips a Buffer verbatim', async () => {+ const store = await KeyValueStore.open();+ const bytes = Buffer.from([0xde, 0xad, 0xbe, 0xef]);+ await store.setValue('BYTES', bytes, { contentType: 'application/octet-stream' });++ await expect(store.getValue('BYTES')).resolves.toStrictEqual(bytes);+ });++ test('round-trips a typed array (with byteOffset) as the correct bytes', async () => {+ const store = await KeyValueStore.open();+ // A view into a larger buffer, so byteOffset / byteLength matter.+ const backing = new Uint8Array([0x00, 0x11, 0x22, 0x33, 0x44]).buffer;+ const view = new Uint8Array(backing, 1, 3); // -> [0x11, 0x22, 0x33]+ await store.setValue('VIEW', view, { contentType: 'application/octet-stream' });++ await expect(store.getValue('VIEW')).resolves.toStrictEqual(Buffer.from([0x11, 0x22, 0x33]));+ });++ test('round-trips an ArrayBuffer as the correct bytes', async () => {+ const store = await KeyValueStore.open();+ const buf = new Uint8Array([0x01, 0x02, 0x03]).buffer;+ await store.setValue('AB', buf, { contentType: 'application/octet-stream' });++ await expect(store.getValue('AB')).resolves.toStrictEqual(Buffer.from([0x01, 0x02, 0x03]));+ });++ test('getRecord returns the raw bytes, not a parsed object', async () => {+ const store = await KeyValueStore.open();+ await store.setValue('OUTPUT', { foo: 'bar' });++ const record = await store.getRecord('OUTPUT');+ expect(record).not.toBeNull();+ expect(Buffer.isBuffer(record!.value) || record!.value instanceof ArrayBuffer).toBe(true);+ expect(JSON.parse(Buffer.from(record!.value as Buffer).toString('utf-8'))).toEqual({ foo: 'bar' });+ expect(record!.contentType).toMatch(/application\/json/);+ });++ test('iterates JSON records via forEachKey without double-parsing', async () => {+ const store = await KeyValueStore.open();+ await store.setValue('a', { idx: 1 });+ await store.setValue('b', { idx: 2 });++ const seen: Record<string, unknown> = {};+ await store.forEachKey(async (key) => {+ seen[key] = await store.getValue(key);+ });++ expect(seen).toEqual({ a: { idx: 1 }, b: { idx: 2 } });+ });+});diff --git a/test/shared/MemoryStorageEmulator.ts b/test/shared/MemoryStorageEmulator.tsindex 7660ba00d..2d46beac7 100644--- a/test/shared/MemoryStorageEmulator.ts+++ b/test/shared/MemoryStorageEmulator.ts@@ -1,7 +1,7 @@import { resolve } from 'node:path';import { MemoryStorageClient } from '@crawlee/memory-storage';-import { Configuration, serviceLocator } from 'crawlee';+import { Configuration, KeyValueStore, serviceLocator } from 'crawlee';import { ensureDir } from 'fs-extra';import log from '@apify/log';@@ -77,8 +77,12 @@ export class MemoryStorageEmulator extends StorageEmulator {return this.storage.createKeyValueStoreClient(id ? { id } : { alias: '__default__' });}- async getState() {- return await (await this.getKeyValueStore()).getValue('CRAWLEE_STATE');+ /**+ * Reads the crawler state through the `KeyValueStore` frontend, so the JSON value is parsed for+ * you (the raw client returns bytes — parsing is the frontend's job).+ */+ async getState<T = unknown>() {+ return (await KeyValueStore.open()).getValue<T>('CRAWLEE_STATE');}}