Files
archived-orca/src/shared/node-bounded-json-stringify.test.ts
T

68 lines
2.3 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import {
JsonStringifyByteLimitError,
stringifyJsonWithinByteLimit
} from './node-bounded-json-stringify'
describe('stringifyJsonWithinByteLimit', () => {
it('matches native JSON for nested values, escaping, and omitted fields', () => {
const shared = { label: 'same object' }
const value = {
text: 'quote " slash \\ control\n emoji 🐋 lone \ud800',
nested: [1, undefined, Number.NaN, { omitted: undefined, kept: true }],
repeated: [shared, shared]
}
const native = JSON.stringify(value)
const result = stringifyJsonWithinByteLimit(value, Buffer.byteLength(native))
expect(result.serialized).toBe(native)
expect(result.byteLength).toBe(Buffer.byteLength(native, 'utf8'))
expect(() => stringifyJsonWithinByteLimit(value, result.byteLength - 1)).toThrow(
JsonStringifyByteLimitError
)
})
it('matches native indented JSON and counts whitespace before materializing it', () => {
const value = { nested: [{ quote: '"', unicode: '🐋' }], empty: {} }
const native = JSON.stringify(value, null, 2)
expect(stringifyJsonWithinByteLimit(value, Buffer.byteLength(native), 2)).toEqual({
byteLength: Buffer.byteLength(native),
serialized: native
})
expect(() => stringifyJsonWithinByteLimit(value, Buffer.byteLength(native) - 1, 2)).toThrow(
JsonStringifyByteLimitError
)
})
it('measures values after toJSON without invoking it twice', () => {
let calls = 0
const value = {
toJSON() {
calls += 1
return { rendered: 'value' }
}
}
expect(stringifyJsonWithinByteLimit(value, 100).serialized).toBe('{"rendered":"value"}')
expect(calls).toBe(1)
})
it('rejects a large root string before materializing escaped JSON', () => {
const value = '\n'.repeat(1024 * 1024)
expect(() => stringifyJsonWithinByteLimit(value, 1024)).toThrow(JsonStringifyByteLimitError)
})
it('measures raw JSON values before native serialization materializes them', () => {
const createRawJson = (JSON as { rawJSON?: (value: string) => unknown }).rawJSON
if (!createRawJson) {
return
}
const value = createRawJson(JSON.stringify('x'.repeat(1024)))
expect(() => stringifyJsonWithinByteLimit(value, 32)).toThrow(JsonStringifyByteLimitError)
})
})