Support object references and deep proxying

Introduce remote object references (refId) and deep proxy support across client, server, serializer and types. Key changes:

- Add refId propagation in client proxies so child proxies inherit and include refId on RPC requests.
- Extend serializer to handle a new SerializedValueType.OBJECT_REF, add refResolver and pass refId to proxyCreator.
- Server: store object references in a Map with generated ref IDs, resolve paths with optional refId, serialize results to OBJECT_REF when shouldProxyResult returns true, and release cleans up references. Add defaultShouldProxyResult heuristic to decide which return values should remain proxied (class instances and objects with methods).
- Types: add refId fields and ObjectRef shape, expose shouldProxyResult option on RpcServerOptions, and include refId in ProxyMeta and serialized values.
- Tests updated across the suite to expect proxied return values (arrays/objects/class instances) and to await property access or method calls; add comprehensive tests for deep return value proxying, chained calls, callbacks, constructors on returned proxies, and lifecycle of remote object proxies.

These changes enable returning live/proxied remote objects (including class instances and objects with methods) from RPC calls, preserving remote behavior and allowing subsequent operations to target the same server-side object.
This commit is contained in:
手瓜一十雪 committed 2026-02-02 18:43:37 +08:00
1 parent fa74176160
commit a27df71f5d
5 files changed
+655 -54

No files matched your search

+18 -2
View File
@@ -61,7 +61,9 @@ export interface DeserializeContext {
/** 回调解析器 */
callbackResolver?: (id: string) => Function;
/** 代理创建器 */
proxyCreator?: (path: PropertyKey[]) => unknown;
proxyCreator?: (path: PropertyKey[], refId?: string) => unknown;
/** 对象引用解析器 */
refResolver?: (refId: string) => unknown;
}
/**
@@ -263,7 +265,7 @@ export function serialize (value: unknown, context: SerializeContext = {}): Seri
* 将序列化数据还原为值
*/
export function deserialize (data: SerializedValue, context: DeserializeContext = {}): unknown {
const { callbackResolver, proxyCreator } = context;
const { callbackResolver, proxyCreator, refResolver } = context;
switch (data.type) {
case SerializedValueType.UNDEFINED:
@@ -357,6 +359,20 @@ export function deserialize (data: SerializedValue, context: DeserializeContext
}
return {};
case SerializedValueType.OBJECT_REF:
// 对象引用:在客户端创建代理,在服务端解析为实际对象
if (data.refId) {
// 优先使用 refResolver(服务端场景)
if (refResolver) {
return refResolver(data.refId);
}
// 否则创建代理(客户端场景)
if (proxyCreator) {
return proxyCreator([], data.refId);
}
}
return {};
case SerializedValueType.OBJECT: {
const obj: Record<string, unknown> = {};
if (data.properties) {