-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathjson.ts
More file actions
68 lines (59 loc) · 1.65 KB
/
json.ts
File metadata and controls
68 lines (59 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { Codec } from './types';
const encoder = new TextEncoder();
const decoder = new TextDecoder();
// Convert Uint8Array to base64
function uint8ArrayToBase64(uint8Array: Uint8Array) {
let binary = '';
uint8Array.forEach((byte) => {
binary += String.fromCharCode(byte);
});
return btoa(binary);
}
// Convert base64 to Uint8Array
function base64ToUint8Array(base64: string) {
const binaryString = atob(base64);
const uint8Array = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
uint8Array[i] = binaryString.charCodeAt(i);
}
return uint8Array;
}
interface Base64EncodedValue {
$t: string;
}
/**
* Naive JSON codec implementation using JSON.stringify and JSON.parse.
* @type {Codec}
*/
export const NaiveJsonCodec: Codec = {
toBuffer: (obj: object) => {
return encoder.encode(
JSON.stringify(obj, function replacer<
T extends object,
>(this: T, key: keyof T) {
const val = this[key];
if (val instanceof Uint8Array) {
return { $t: uint8ArrayToBase64(val) } satisfies Base64EncodedValue;
} else {
return val;
}
}),
);
},
fromBuffer: (buff: Uint8Array) => {
const parsed = JSON.parse(
decoder.decode(buff),
function reviver(_key, val: unknown) {
if ((val as Base64EncodedValue | undefined)?.$t !== undefined) {
return base64ToUint8Array((val as Base64EncodedValue).$t);
} else {
return val;
}
},
) as unknown;
if (typeof parsed !== 'object' || parsed === null) {
throw new Error('unpacked msg is not an object');
}
return parsed;
},
};