|
1 | | -import { Options, Packr } from 'msgpackr'; |
| 1 | +import { DecodeError, ExtensionCodec, decode, encode } from '@msgpack/msgpack'; |
2 | 2 | import { Codec } from './types'; |
3 | 3 |
|
4 | | -const packr = new Packr({ |
5 | | - useRecords: false, |
6 | | - moreTypes: true, |
7 | | - bundleStrings: true, |
8 | | - useTimestamp32: false, |
9 | | - useBigIntExtension: true, |
10 | | - skipValues: [undefined], |
11 | | -} as Options); |
| 4 | +const BIGINT_EXT_TYPE = 0; |
| 5 | +const extensionCodec = new ExtensionCodec(); |
| 6 | +extensionCodec.register({ |
| 7 | + type: BIGINT_EXT_TYPE, |
| 8 | + encode(input: unknown): Uint8Array | null { |
| 9 | + if (typeof input === 'bigint') { |
| 10 | + if ( |
| 11 | + input <= Number.MAX_SAFE_INTEGER && |
| 12 | + input >= Number.MIN_SAFE_INTEGER |
| 13 | + ) { |
| 14 | + return encode(Number(input)); |
| 15 | + } else { |
| 16 | + return encode(String(input)); |
| 17 | + } |
| 18 | + } else { |
| 19 | + return null; |
| 20 | + } |
| 21 | + }, |
| 22 | + decode(data: Uint8Array): bigint { |
| 23 | + const val = decode(data); |
| 24 | + if (!(typeof val === 'string' || typeof val === 'number')) { |
| 25 | + throw new DecodeError(`unexpected BigInt source: ${typeof val}`); |
| 26 | + } |
| 27 | + |
| 28 | + return BigInt(val); |
| 29 | + }, |
| 30 | +}); |
12 | 31 |
|
13 | 32 | /** |
14 | | - * Binary codec, uses [msgpackr](https://www.npmjs.com/package/msgpackr) under the hood |
| 33 | + * Binary codec, uses [msgpack](https://www.npmjs.com/package/@msgpack/msgpack) under the hood |
15 | 34 | * @type {Codec} |
16 | 35 | */ |
17 | 36 | export const BinaryCodec: Codec = { |
18 | 37 | toBuffer(obj) { |
19 | | - return packr.pack(obj); |
| 38 | + return encode(obj, { ignoreUndefined: true, extensionCodec }); |
20 | 39 | }, |
21 | 40 | fromBuffer: (buff: Uint8Array) => { |
22 | | - const res: unknown = packr.unpack(buff); |
| 41 | + const res = decode(buff, { extensionCodec }); |
23 | 42 | if (typeof res !== 'object' || res === null) { |
24 | 43 | throw new Error('unpacked msg is not an object'); |
25 | 44 | } |
|
0 commit comments