2023-09-06 00:28:11 -04:00
|
|
|
import { compatto } from './compatto';
|
|
|
|
import dictionary from './dictionary';
|
|
|
|
|
|
|
|
const { compress, decompress } = compatto({ dictionary });
|
|
|
|
|
2023-08-23 21:44:59 -04:00
|
|
|
const replacer = (_key: any, value: any) => {
|
|
|
|
if (value instanceof Map) {
|
|
|
|
return {
|
2023-08-25 18:48:17 -04:00
|
|
|
dataType: 'Map',
|
|
|
|
value: Array.from(value.entries())
|
2023-08-23 21:44:59 -04:00
|
|
|
};
|
|
|
|
} else {
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-08-29 14:05:02 -04:00
|
|
|
const sortObj = (obj: any): any =>
|
|
|
|
obj === null || typeof obj !== 'object'
|
|
|
|
? obj
|
|
|
|
: Array.isArray(obj)
|
|
|
|
? obj.map(sortObj)
|
|
|
|
: Object.assign(
|
|
|
|
{},
|
|
|
|
...Object.entries(obj)
|
|
|
|
.sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
|
|
|
|
.map(([k, v]) => ({ [k]: sortObj(v) }))
|
|
|
|
);
|
|
|
|
|
2023-08-23 21:44:59 -04:00
|
|
|
const reviver = (_key: any, value: any) => {
|
2023-08-25 18:48:17 -04:00
|
|
|
if (typeof value === 'object' && value !== null) {
|
|
|
|
if (value.dataType === 'Map') {
|
2023-08-23 21:44:59 -04:00
|
|
|
return new Map(value.value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return value;
|
|
|
|
};
|
|
|
|
|
2023-08-29 14:05:02 -04:00
|
|
|
// "deterministic" stringify
|
2023-09-06 00:28:11 -04:00
|
|
|
|
|
|
|
export const stringify = (obj: any): string => {
|
2023-08-29 14:05:02 -04:00
|
|
|
return JSON.stringify(sortObj(obj), replacer);
|
2023-08-23 21:44:59 -04:00
|
|
|
};
|
|
|
|
|
2023-09-06 00:28:11 -04:00
|
|
|
export const serialize = (obj: any): Uint8Array => {
|
|
|
|
//return new Uint8Array(new TextEncoder().encode(stringify(obj)));
|
|
|
|
return compress(stringify(obj));
|
|
|
|
};
|
|
|
|
|
|
|
|
export const parse = <T>(serialized: Uint8Array): T => {
|
|
|
|
//return JSON.parse(new TextDecoder().decode(serialized), reviver) as T;
|
|
|
|
return JSON.parse(decompress(serialized), reviver) as T;
|
2023-08-23 21:44:59 -04:00
|
|
|
};
|