// adapted from fast-json-stable-stringify (https://github.com/epoberezkin/fast-json-stable-stringify) export type Stringified = string & { __type: T }; export function stableStringify(data: T): Stringified; export function stableStringify(data: undefined): undefined; export function stableStringify( data: T | undefined, ): Stringified | undefined { const cycles = false; // eslint-disable-next-line @typescript-eslint/no-explicit-any const seen: any[] = []; // eslint-disable-next-line @typescript-eslint/no-explicit-any let node = data as any; if (node && node.toJSON && typeof node.toJSON === "function") { node = node.toJSON(); } if (node === undefined) return; if (typeof node == "number") return (isFinite(node) ? "" + node : "null") as Stringified; if (typeof node !== "object") { if ( typeof node === "string" && (node.startsWith("encrypted_U") || node.startsWith("binary_U")) ) { return `"${node}"` as Stringified; } return JSON.stringify(node) as Stringified; } let i, out; if (Array.isArray(node)) { out = "["; for (i = 0; i < node.length; i++) { if (i) out += ","; out += stableStringify(node[i]) || "null"; } return (out + "]") as Stringified; } if (node === null) return "null" as Stringified; if (seen.indexOf(node) !== -1) { if (cycles) return JSON.stringify("__cycle__") as Stringified; throw new TypeError("Converting circular structure to JSON"); } const seenIndex = seen.push(node) - 1; const keys = Object.keys(node).sort(); out = ""; for (i = 0; i < keys.length; i++) { const key = keys[i]!; const value = stableStringify(node[key]); if (!value) continue; if (out) out += ","; out += JSON.stringify(key) + ":" + value; } seen.splice(seenIndex, 1); return ("{" + out + "}") as Stringified; } export function parseJSON(json: Stringified): T { return JSON.parse(json); } export function safeParseJSON(json: Stringified): T | undefined { try { return JSON.parse(json); } catch (e) { return undefined; } }