diff --git a/packages/utils/package.json b/packages/utils/package.json index 3dc909f..edd0f04 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -1,6 +1,6 @@ { "name": "@holochain-open-dev/utils", - "version": "0.15.1", + "version": "0.15.2", "description": "Common utilities to build Holochain web applications", "author": "guillem.cordoba@gmail.com", "main": "dist/index.js", @@ -12,7 +12,8 @@ "url": "git+https://github.com/holochain-open-dev/common.git" }, "exports": { - ".": "./dist/index.js" + ".": "./dist/index.js", + "./dist/*": "./dist/*" }, "scripts": { "build": "npm run lint && tsc --incremental", diff --git a/packages/utils/src/clean-node-decoding.ts b/packages/utils/src/clean-node-decoding.ts new file mode 100644 index 0000000..9559022 --- /dev/null +++ b/packages/utils/src/clean-node-decoding.ts @@ -0,0 +1,39 @@ +/** + * Deeply convert nulls into undefineds, and buffers into Uint8Array + * + * When msgpack is used to decode() in nodejs, it returns hashes as buffers + * and nulls instead of undefineds. + * This is mostly fine, except in tryorama tests when using deepEqual. This function + * is useful in that case, to allow objects constructed in the tests to deeply equal + * the return of calls to @holochain/client + */ +export function cleanNodeDecoding(object: any): any { + return deepMap(object, (value) => { + if (Buffer.isBuffer(value)) return new Uint8Array(value); + if (value === null) return undefined; + return value; + }); +} + +function mapObject(obj, fn) { + return Object.keys(obj).reduce((res, key) => { + res[key] = fn(obj[key]); + return res; + }, {}); +} + +function deepMap(obj, fn) { + const deepMapper = (val) => + typeof val === "object" && !Buffer.isBuffer(val) + ? deepMap(val, fn) + : fn(val); + if (Array.isArray(obj)) { + return obj.map(deepMapper); + } + if (obj === null) { + return fn(obj); + } else if (typeof obj === "object") { + return mapObject(obj, deepMapper); + } + return obj; +} diff --git a/packages/utils/tests/clean-node-decoding.test.ts b/packages/utils/tests/clean-node-decoding.test.ts new file mode 100644 index 0000000..8d85b63 --- /dev/null +++ b/packages/utils/tests/clean-node-decoding.test.ts @@ -0,0 +1,14 @@ +import { encodeHashToBase64 } from "@holochain/client"; +import { test, assert } from "vitest"; +import { cleanNodeDecoding } from "../src/clean-node-decoding.js"; + +test("test clean", async () => { + const hi = { + hi: null, + bu: Buffer.from(new Uint8Array([1, 1, 1])), + }; + assert.deepEqual(cleanNodeDecoding(hi), { + hi: undefined, + bu: new Uint8Array([1, 1, 1]), + }); +});