1 | ;
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.DefaultTranscoder = void 0;
|
4 | const NF_JSON = 0x00;
|
5 | const NF_RAW = 0x02;
|
6 | const NF_UTF8 = 0x04;
|
7 | const NF_MASK = 0xff;
|
8 | const NF_UNKNOWN = 0x100;
|
9 | const CF_NONE = 0x00 << 24;
|
10 | const CF_PRIVATE = 0x01 << 24;
|
11 | const CF_JSON = 0x02 << 24;
|
12 | const CF_RAW = 0x03 << 24;
|
13 | const CF_UTF8 = 0x04 << 24;
|
14 | const CF_MASK = 0xff << 24;
|
15 | /**
|
16 | * The default transcoder implements cross-sdk transcoding capabilities by
|
17 | * taking advantage of the common flags specification to ensure compatibility.
|
18 | * This transcoder is capable of encoding/decoding any value which is encodable
|
19 | * to JSON, and additionally has special-case handling for Buffer objects.
|
20 | *
|
21 | * @category Key-Value
|
22 | */
|
23 | class DefaultTranscoder {
|
24 | /**
|
25 | * Encodes the specified value, returning a buffer and flags that are
|
26 | * stored to the server and later used for decoding.
|
27 | *
|
28 | * @param value The value to encode.
|
29 | */
|
30 | encode(value) {
|
31 | // If its a buffer, write that directly as raw.
|
32 | if (Buffer.isBuffer(value)) {
|
33 | return [value, CF_RAW | NF_RAW];
|
34 | }
|
35 | // If its a string, encode it as a UTF8 string.
|
36 | if (typeof value === 'string') {
|
37 | return [Buffer.from(value), CF_UTF8 | NF_UTF8];
|
38 | }
|
39 | // Encode it to JSON and save that otherwise.
|
40 | return [Buffer.from(JSON.stringify(value)), CF_JSON | NF_JSON];
|
41 | }
|
42 | /**
|
43 | * Decodes a buffer and flags tuple back to the original type of the
|
44 | * document.
|
45 | *
|
46 | * @param bytes The bytes that were previously encoded.
|
47 | * @param flags The flags associated with the data.
|
48 | */
|
49 | decode(bytes, flags) {
|
50 | let format = flags & NF_MASK;
|
51 | const cfformat = flags & CF_MASK;
|
52 | if (cfformat !== CF_NONE) {
|
53 | if (cfformat === CF_JSON) {
|
54 | format = NF_JSON;
|
55 | }
|
56 | else if (cfformat === CF_RAW) {
|
57 | format = NF_RAW;
|
58 | }
|
59 | else if (cfformat === CF_UTF8) {
|
60 | format = NF_UTF8;
|
61 | }
|
62 | else if (cfformat !== CF_PRIVATE) {
|
63 | // Unknown CF Format! The following will force
|
64 | // fallback to reporting RAW data.
|
65 | format = NF_UNKNOWN;
|
66 | }
|
67 | }
|
68 | if (format === NF_UTF8) {
|
69 | return bytes.toString('utf8');
|
70 | }
|
71 | else if (format === NF_RAW) {
|
72 | return bytes;
|
73 | }
|
74 | else if (format === NF_JSON) {
|
75 | try {
|
76 | return JSON.parse(bytes.toString('utf8'));
|
77 | }
|
78 | catch (e) {
|
79 | // If we encounter a parse error, assume that we need
|
80 | // to return bytes instead of an object.
|
81 | return bytes;
|
82 | }
|
83 | }
|
84 | // Default to returning a Buffer if all else fails.
|
85 | return bytes;
|
86 | }
|
87 | }
|
88 | exports.DefaultTranscoder = DefaultTranscoder;
|