summaryrefslogtreecommitdiffhomepage
path: root/packages/server/src/helpers/decodeCbor.ts
blob: 37e8ab2b26036f754fdf8984f9d972437e1339e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import cbor from 'cbor';

export function decodeCborFirst(input: string | Buffer | ArrayBufferView): any {
  try {
    // throws if there are extra bytes
    return cbor.decodeFirstSync(input);
  } catch (err) {
    const _err = err as CborDecoderError;
    // if the error was due to extra bytes, return the unpacked value
    if (_err.value) {
      return _err.value;
    }
    throw err;
  }
}

/**
 * Intuited from a quick scan of `cbor.decodeFirstSync()` here:
 *
 * https://github.com/hildjj/node-cbor/blob/v5.1.0/lib/decoder.js#L189
 */
class CborDecoderError extends Error {
  value: any;
}