From 3ccdd306a5c40a81087f1eae29a7a73d83f8413c Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Fri, 19 Sep 2025 12:40:42 +0900 Subject: [PATCH] Preserve complex values during deserialization Fixes #76 --- index.js | 8 ++++++-- test.js | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 29dd979..f1c050c 100644 --- a/index.js +++ b/index.js @@ -102,17 +102,21 @@ const destroyCircular = ({ for (const [key, value] of Object.entries(from)) { if (value && value instanceof Uint8Array && value.constructor.name === 'Buffer') { - to[key] = '[object Buffer]'; + to[key] = serialize ? '[object Buffer]' : value; continue; } // TODO: Use `stream.isReadable()` when targeting Node.js 18. if (value !== null && typeof value === 'object' && typeof value.pipe === 'function') { - to[key] = '[object Stream]'; + to[key] = serialize ? '[object Stream]' : value; continue; } if (typeof value === 'function') { + if (!serialize) { + to[key] = value; + } + continue; } diff --git a/test.js b/test.js index db7864e..596970a 100644 --- a/test.js +++ b/test.js @@ -273,6 +273,29 @@ test('should deserialize plain object', t => { t.is(deserialized.code, 'code'); }); +test('should preserve buffers when deserializing', t => { + const buffer = Buffer.from([1, 2, 3]); + const deserialized = deserializeError({ + message: 'buffer', + stack: '', + data: buffer, + }); + + t.true(Buffer.isBuffer(deserialized.data)); + t.is(deserialized.data, buffer); +}); + +test('should preserve functions when deserializing', t => { + const sideEffect = () => 'no-op'; + const deserialized = deserializeError({ + message: 'function', + stack: '', + callback: sideEffect, + }); + + t.is(deserialized.callback, sideEffect); +}); + for (const property of ['cause', 'any']) { // `cause` is treated differently from other properties in the code test(`should deserialize errors on ${property} property`, t => {