Monkey patch toString on proxyInner and proxyLazy

This commit is contained in:
Nuckyz 2024-05-23 22:20:24 -03:00
parent 23c8818ed2
commit 6f25005057
No known key found for this signature in database
GPG key ID: 440BF8296E1C4AD9
2 changed files with 25 additions and 13 deletions

View file

@ -83,6 +83,10 @@ export function proxyLazy<T = AnyObject>(factory: () => T, attempts = 5, isChild
if (!proxyDummy[proxyLazyCache]) {
throw new Error(`proxyLazy factory failed:\n\n${factory}`);
} else {
if (typeof proxyDummy[proxyLazyCache] === "function") {
proxy.toString = proxyDummy[proxyLazyCache].toString.bind(proxyDummy[proxyLazyCache]);
}
}
}
@ -91,7 +95,7 @@ export function proxyLazy<T = AnyObject>(factory: () => T, attempts = 5, isChild
[proxyLazyCache]: void 0 as T | undefined
});
return new Proxy(proxyDummy, {
const proxy = new Proxy(proxyDummy, {
...handler,
get(target, p, receiver) {
if (p === proxyLazyGet) return target[proxyLazyGet];
@ -117,4 +121,6 @@ export function proxyLazy<T = AnyObject>(factory: () => T, attempts = 5, isChild
throw new Error("proxyLazy called on a primitive value. This can happen if you try to destructure a primitive at the same tick as the proxy was created.");
}
});
return proxy;
}

View file

@ -65,17 +65,7 @@ export function proxyInner<T = AnyObject>(
[proxyInnerValue]: void 0 as T | undefined
});
// Values destructured in the same tick the proxy was created will push their setInnerValue here
const recursiveSetInnerValues = [] as Array<(innerValue: T) => void>;
// Once we set the parent inner value, we will call the setInnerValue functions of the destructured values,
// for them to get the proper value from the parent and use as their inner instead
function setInnerValue(innerValue: T) {
proxyDummy[proxyInnerValue] = innerValue;
recursiveSetInnerValues.forEach(setInnerValue => setInnerValue(innerValue));
}
return [new Proxy(proxyDummy, {
const proxy = new Proxy(proxyDummy, {
...handler,
get(target, p, receiver) {
if (p === proxyInnerValue) return target[proxyInnerValue];
@ -104,5 +94,21 @@ export function proxyInner<T = AnyObject>(
throw new Error(primitiveErrMsg);
}
}), setInnerValue];
});
// Values destructured in the same tick the proxy was created will push their setInnerValue here
const recursiveSetInnerValues = [] as Array<(innerValue: T) => void>;
// Once we set the parent inner value, we will call the setInnerValue functions of the destructured values,
// for them to get the proper value from the parent and use as their inner instead
function setInnerValue(innerValue: T) {
proxyDummy[proxyInnerValue] = innerValue;
recursiveSetInnerValues.forEach(setInnerValue => setInnerValue(innerValue));
if (typeof innerValue === "function") {
proxy.toString = innerValue.toString.bind(innerValue);
}
}
return [proxy, setInnerValue];
}