| 1013 | } |
| 1014 | |
| 1015 | const copyOrThrow = (value: unknown, seen: Map<object, unknown>): any => { |
| 1016 | if (typeof value === "function") throw uncopyable |
| 1017 | if (typeof value !== "object" || value === null) return value |
| 1018 | if (seen.has(value)) return seen.get(value) |
| 1019 | const proto = Object.getPrototypeOf(value) |
| 1020 | if (!copiedProtos.includes(proto)) throw uncopyable |
| 1021 | const copy = |
| 1022 | Array.isArray(value) ? [] |
| 1023 | : value instanceof Date ? new Date(value.getTime()) |
| 1024 | : value instanceof Map || value instanceof Set ? new proto.constructor() |
| 1025 | : Object.create(proto) |
| 1026 | seen.set(value, copy) |
| 1027 | if (value instanceof Map) { |
| 1028 | for (const [k, v] of value) |
| 1029 | copy.set(copyOrThrow(k, seen), copyOrThrow(v, seen)) |
| 1030 | } |
| 1031 | if (value instanceof Set) |
| 1032 | for (const v of value) copy.add(copyOrThrow(v, seen)) |
| 1033 | if (isIndexed(value)) { |
| 1034 | for (let i = 0; i < value.length; i++) |
| 1035 | copy.push(copyOrThrow(value[i], seen)) |
| 1036 | } else { |
| 1037 | for (const k of Reflect.ownKeys(value)) { |
| 1038 | const descriptor = Object.getOwnPropertyDescriptor(value, k)! |
| 1039 | if (!("value" in descriptor)) throw uncopyable |
| 1040 | const copied = copyOrThrow(descriptor.value, seen) |
| 1041 | if ( |
| 1042 | descriptor.writable && |
| 1043 | descriptor.enumerable && |
| 1044 | descriptor.configurable |
| 1045 | ) |
| 1046 | copy[k] = copied |
| 1047 | else Object.defineProperty(copy, k, { ...descriptor, value: copied }) |
| 1048 | } |
| 1049 | } |
| 1050 | if (Object.isFrozen(value)) Object.freeze(copy) |
| 1051 | else if (!Object.isExtensible(value)) Object.preventExtensions(copy) |
| 1052 | return copy |
| 1053 | } |
| 1054 | |
| 1055 | const isIndexed = (value: object): value is unknown[] => { |
| 1056 | if ( |