-
Notifications
You must be signed in to change notification settings - Fork 0
/
serde.ts
86 lines (74 loc) · 1.8 KB
/
serde.ts
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { inflate, deflate } from "pako";
import { toUint8Array, fromUint8Array, toBase64, fromBase64 } from "js-base64";
export interface LiveGistLoaderConfig {
url: string;
}
export interface LiveFileLoaderConfig {
codeURL: string;
configURL?: string;
}
export interface LiveLoaderConfig {
type: "gist" | "files";
config: LiveGistLoaderConfig | LiveFileLoaderConfig;
}
export interface LiveState {
code: string;
mermaid?: string;
updateEditor?: boolean;
updateDiagram?: boolean;
autoSync?: boolean;
loader?: LiveLoaderConfig;
}
export interface Serde {
serialize(state: string): string;
deserialize(state: string): string;
}
export const base64Serde: Serde = {
serialize: (state) => {
return toBase64(state, true);
},
deserialize: (state) => {
return fromBase64(state);
},
};
export const pakoSerde: Serde = {
serialize: (state) => {
const data = new TextEncoder().encode(state);
const compressed = deflate(data, { level: 9 });
return fromUint8Array(compressed, true);
},
deserialize: (state) => {
const data = toUint8Array(state);
return inflate(data, { to: "string" });
},
};
export type Code = LiveState | string;
export function intoCode(data: string): Code {
try {
return JSON.parse(data);
} catch (e) {
return data;
}
}
export function fromCode(code: Code): string {
if (typeof code === "string") {
return code;
} else {
return JSON.stringify(code);
}
}
export function asLiveState(code: Code): LiveState {
if (typeof code === "string") {
const mermaidConfig = { theme: "default" };
return { code: code, mermaid: JSON.stringify(mermaidConfig) };
} else {
return code;
}
}
export function getSource(code: Code): string {
if (typeof code === "string") {
return code;
} else {
return code.code;
}
}