From a0453d0dd148e8ced33be18395ce761f46789b59 Mon Sep 17 00:00:00 2001 From: Aomkoyo Date: Wed, 6 Nov 2024 15:26:39 +0700 Subject: [PATCH] feat: remove in class and add to Utils getCircularReplacer(), ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value --- src/Utils.ts | 19 +++++++++++++++++++ src/node/Rest.ts | 15 ++------------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/Utils.ts b/src/Utils.ts index 68c3a3a7..9553db3a 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -56,3 +56,22 @@ export function mergeDefault>(def: T, given: T): R export function wait(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } + + +export function getCircularReplacer(): (key: string, value: any) => any { + const ancestors: any[] = []; + return function (this: any, key: string, value: any): any { + if (typeof value !== "object" || value === null) { + return value; + } + while (ancestors.length > 0 && ancestors.at(-1) !== this) { + ancestors.pop(); + } + if (ancestors.includes(value)) { + return "[Circular]"; + } + ancestors.push(value); + return value; + }; + } + \ No newline at end of file diff --git a/src/node/Rest.ts b/src/node/Rest.ts index cfcf16b5..753596c6 100644 --- a/src/node/Rest.ts +++ b/src/node/Rest.ts @@ -2,6 +2,7 @@ import { Versions } from '../Constants'; import { FilterOptions } from '../guild/Player'; import { NodeOption } from '../Shoukaku'; +import { getCircularReplacer } from '../Utils'; import { Node, NodeInfo, Stats } from './Node'; export type Severity = 'common' | 'suspicious' | 'fault'; @@ -379,7 +380,7 @@ export class Rest { }; if (!['GET', 'HEAD'].includes(method) && options.body) - finalFetchOptions.body = JSON.stringify(options.body, this.removeCircularReferences()); + finalFetchOptions.body = JSON.stringify(options.body, getCircularReplacer()); const request = await fetch(url.toString(), finalFetchOptions) .finally(() => clearTimeout(timeout)); @@ -402,18 +403,6 @@ export class Rest { return; } } - private removeCircularReferences() { - const seen = new WeakSet(); - return (key: string, value: unknown) => { - if (typeof value === "object" && value !== null) { - if (seen.has(value)) { - return; // Skip circular reference - } - seen.add(value); - } - return value; - }; - } } interface LavalinkRestError {