diff --git a/src/bytes/bytes.ts b/src/bytes/bytes.ts index b2748c7..fad0976 100644 --- a/src/bytes/bytes.ts +++ b/src/bytes/bytes.ts @@ -154,12 +154,19 @@ export class Bytes { } /** - * Decodes the bytes as UTF-8 JSON. + * Parses the bytes as UTF-8 JSON. */ - public toJSON(): unknown { + public parseJson(): unknown { return JSON.parse(this.toUtf8()) } + /** + * Serialized as its hex string by `JSON.stringify`. + */ + public toJSON(): string { + return this.toHex() + } + /** * Byte-wise equality against another Bytes instance, raw bytes, or hex string. */ @@ -173,4 +180,11 @@ export class Bytes { public represent(): string { return this.toHex() } + + /** + * Printed as its hex string by `console.log` and `util.inspect` in Node. + */ + public [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.represent() + } } diff --git a/test/typed-bytes.test.ts b/test/typed-bytes.test.ts index c3fca99..3361efc 100644 --- a/test/typed-bytes.test.ts +++ b/test/typed-bytes.test.ts @@ -1,3 +1,4 @@ +import { inspect } from 'node:util' import { describe, expect, it } from 'vitest' import { keccak256 } from '../src/crypto/keccak.js' import { BatchId } from '../src/bytes/batch-id.js' @@ -63,7 +64,22 @@ describe('Bytes', () => { it('parses JSON from its UTF-8 content', () => { const bytes = Bytes.fromUtf8(JSON.stringify({ a: 1 })) - expect(bytes.toJSON()).toEqual({ a: 1 }) + expect(bytes.parseJson()).toEqual({ a: 1 }) + }) + + it('stringifies to hex, standalone and as a property', () => { + const id = new BatchId('ab'.repeat(32)) + expect(id.toJSON()).toBe('ab'.repeat(32)) + expect(JSON.stringify(id)).toBe(`"${'ab'.repeat(32)}"`) + expect(JSON.stringify({ id })).toBe(`{"id":"${'ab'.repeat(32)}"}`) + expect(`${id}`).toBe('ab'.repeat(32)) + }) + + it('inspects as hex, standalone and nested', () => { + const id = new BatchId('ab'.repeat(32)) + expect(inspect(id)).toBe('ab'.repeat(32)) + expect(inspect({ id }, { breakLength: Infinity })).toBe(`{ id: ${'ab'.repeat(32)} }`) + expect(inspect([new Span('0102030405060708')])).toBe('[ 0102030405060708 ]') }) it('static keccak256 matches the direct function', () => {