2025-06-27 17:08:09 +00:00
|
|
|
/**
|
|
|
|
|
* @license
|
|
|
|
|
* Copyright Google LLC All Rights Reserved.
|
|
|
|
|
*
|
|
|
|
|
* Use of this source code is governed by an MIT-style license that can be
|
|
|
|
|
* found in the LICENSE file at https://angular.dev/license
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
export function sanitizeObject(obj: any): any {
|
2025-10-04 06:48:04 +00:00
|
|
|
// Keep track of visited objects to detect circular references.
|
|
|
|
|
const seen = new WeakSet();
|
2025-06-27 17:08:09 +00:00
|
|
|
|
2025-10-04 06:48:04 +00:00
|
|
|
function recurse(value: any): any {
|
|
|
|
|
// Primitives and null
|
|
|
|
|
if (value === null || typeof value !== 'object') {
|
|
|
|
|
// Some primitives are not serializable
|
|
|
|
|
if (
|
|
|
|
|
typeof value === 'function' ||
|
|
|
|
|
typeof value === 'symbol' ||
|
|
|
|
|
typeof value === 'bigint' ||
|
|
|
|
|
value === undefined
|
|
|
|
|
) {
|
|
|
|
|
return '[Non-serializable data]';
|
|
|
|
|
}
|
2025-06-27 17:08:09 +00:00
|
|
|
|
2025-10-04 06:48:04 +00:00
|
|
|
// Most other primitives are serializable
|
|
|
|
|
return value;
|
|
|
|
|
}
|
2025-06-27 17:08:09 +00:00
|
|
|
|
2025-10-04 06:48:04 +00:00
|
|
|
// Down here we only have objects
|
|
|
|
|
// Check for circular references
|
|
|
|
|
if (seen.has(value)) {
|
|
|
|
|
return '[Circular]';
|
|
|
|
|
}
|
|
|
|
|
seen.add(value);
|
|
|
|
|
|
|
|
|
|
// Recursively serialize arrays
|
|
|
|
|
if (Array.isArray(value)) {
|
|
|
|
|
return value.map(recurse);
|
|
|
|
|
}
|
2025-06-27 17:08:09 +00:00
|
|
|
|
2025-10-04 06:48:04 +00:00
|
|
|
// Recursively serialize objects
|
|
|
|
|
const result: Record<string, any> = {};
|
|
|
|
|
for (const [key, propValue] of Object.entries(value)) {
|
|
|
|
|
result[key] = recurse(propValue);
|
|
|
|
|
}
|
|
|
|
|
return result;
|
2025-06-27 17:08:09 +00:00
|
|
|
}
|
2025-10-04 06:48:04 +00:00
|
|
|
|
|
|
|
|
return recurse(obj);
|
2025-06-27 17:08:09 +00:00
|
|
|
}
|