Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bigint & HTMLElement serialization #46

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

davidkpiano
Copy link
Member

No description provided.

@jwyoo
Copy link

jwyoo commented Mar 17, 2025

Performance improvement issues, but performance problems still exist.

function deepCopyAndPrepareForSafeStringify(
  obj: any,
  hash = new WeakMap()
): any {
  // check circular
  if (hash.has(obj)) {
    return hash.get(obj);
  }

  if (typeof obj === "bigint") {
    return { type: "bigint", value: obj.toString() };
  }

  if (obj === null || typeof obj !== "object") {
    return obj;
  }

  if (obj instanceof HTMLElement) {
    const element = {
      tag: obj.tagName,
      outerHTML: obj.outerHTML,
    };
    hash.set(obj, element);
    return element;
  }

  if (Object.prototype.hasOwnProperty.call(obj, "toJSON")) {
    const json = obj.toJSON();
    for (const key in json) {
      json[key] = deepCopyAndPrepareForSafeStringify(json[key], hash);
    }
    hash.set(obj, json);
    return json;
  }

  const copy = Array.isArray(obj)
    ? ([] as any[])
    : ({ __proto__: obj.__proto__ } as any);
  hash.set(obj, copy);
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      copy[key] = deepCopyAndPrepareForSafeStringify(obj[key], hash);
    }
  }
  return copy;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants