{"version":3,"file":"jsonStringify.mjs","names":[],"sources":["../../../src/tools/serialisation/jsonStringify.ts"],"sourcesContent":["import { noop } from '../utils/functionUtils'\n\n/**\n * Custom implementation of JSON.stringify that ignores some toJSON methods. We need to do that\n * because some sites badly override toJSON on certain objects. Removing all toJSON methods from\n * nested values would be too costly, so we just detach them from the root value, and native classes\n * used to build JSON values (Array and Object).\n *\n * Note: this still assumes that JSON.stringify is correct.\n */\nexport function jsonStringify(\n  value: unknown,\n  replacer?: Array<string | number>,\n  space?: string | number\n): string | undefined {\n  if (typeof value !== 'object' || value === null) {\n    return JSON.stringify(value)\n  }\n\n  // Note: The order matter here. We need to detach toJSON methods on parent classes before their\n  // subclasses.\n  const restoreObjectPrototypeToJson = detachToJsonMethod(Object.prototype)\n  const restoreArrayPrototypeToJson = detachToJsonMethod(Array.prototype)\n  const restoreValuePrototypeToJson = detachToJsonMethod(Object.getPrototypeOf(value))\n  const restoreValueToJson = detachToJsonMethod(value)\n\n  try {\n    return JSON.stringify(value, replacer, space)\n  } catch {\n    return '<error: unable to serialize object>'\n  } finally {\n    restoreObjectPrototypeToJson()\n    restoreArrayPrototypeToJson()\n    restoreValuePrototypeToJson()\n    restoreValueToJson()\n  }\n}\n\nexport interface ObjectWithToJsonMethod {\n  toJSON?: () => unknown\n}\n\nexport function detachToJsonMethod(value: object) {\n  const object = value as ObjectWithToJsonMethod\n  const objectToJson = object.toJSON\n  if (objectToJson) {\n    delete object.toJSON\n    return () => {\n      object.toJSON = objectToJson\n    }\n  }\n  return noop\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,cACd,OACA,UACA,OACoB;CACpB,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO,KAAK,UAAU,KAAK;CAK7B,MAAM,+BAA+B,mBAAmB,OAAO,SAAS;CACxE,MAAM,8BAA8B,mBAAmB,MAAM,SAAS;CACtE,MAAM,8BAA8B,mBAAmB,OAAO,eAAe,KAAK,CAAC;CACnF,MAAM,qBAAqB,mBAAmB,KAAK;CAEnD,IAAI;EACF,OAAO,KAAK,UAAU,OAAO,UAAU,KAAK;CAC9C,QAAQ;EACN,OAAO;CACT,UAAU;EACR,6BAA6B;EAC7B,4BAA4B;EAC5B,4BAA4B;EAC5B,mBAAmB;CACrB;AACF;AAMA,SAAgB,mBAAmB,OAAe;CAChD,MAAM,SAAS;CACf,MAAM,eAAe,OAAO;CAC5B,IAAI,cAAc;EAChB,OAAO,OAAO;EACd,aAAa;GACX,OAAO,SAAS;EAClB;CACF;CACA,OAAO;AACT"}