clonegur/src/server/serialize.ts
2023-06-26 17:07:14 +03:00

28 lines
947 B
TypeScript

const undefinedBuff = new Blob([new TextEncoder().encode('undefined')]);
const nullBuff = new Blob([new TextEncoder().encode('null')]);
export default async function serialize(val: unknown, depth = 16): Promise<Blob> {
while(true) {
if(depth <= 0) throw new Error("Call depth exceeded limit.");
if(val instanceof Promise) val = await val;
else if(val instanceof Function) {
if(val.length !== 0) throw new Error('Can\'t serialize an argument-accepting function');
val = val();
}
else break;
depth--;
}
if(val === undefined) return undefinedBuff;
if(val === null) return nullBuff;
if(val instanceof Blob) return val;
while(typeof val !== 'string' && val && val.toString !== Object.prototype.toString && val.toString instanceof Function) {
val = val.toString();
}
return new Blob([new TextEncoder().encode(JSON.stringify(val))]);
}