UNPKG

@xtr-dev/zod-rpc

Version:

Simple, type-safe RPC library with Zod validation and automatic TypeScript inference

76 lines 2.93 kB
import { z, ZodSchema } from 'zod'; import { MethodDefinition, MethodInfo, ServiceInfo, Transport } from './types'; import { ServiceDefinition, ServiceImplementation } from './service'; /** * Core communication channel that manages RPC method calls, message routing, and transport connections. * This is the central orchestrator for all RPC communication between clients and servers. * * @example * ```typescript * const channel = new Channel('client-123', 30000); * * // Connect to transport * const transport = createWebSocketTransport('ws://localhost:8080'); * await channel.connect(transport); * * // Call remote method * const result = await channel.invoke( * 'server', * 'user.get', * { userId: '123' }, * inputSchema, * outputSchema * ); * ``` * * @group Core Classes */ export declare class Channel { private channelId; private defaultTimeout; private methods; private pendingCalls; private services; private transports; private connected; constructor(channelId: string, defaultTimeout?: number); connect(...transports: Transport[]): Promise<void>; disconnect(): Promise<void>; publishMethod<T extends ZodSchema, U extends ZodSchema>(definition: MethodDefinition<T, U>): void; /** * Publish a service implementation to this channel, making all its methods available for RPC calls. * This is a convenience method that combines implementService and publishMethod. * * @template T - Service methods record type * @param service - The service definition with schemas * @param implementation - The actual implementation functions * @param targetId - Optional target identifier (defaults to channelId) * * @example * ```typescript * const channel = new Channel('server'); * * // Instead of: * // const methods = implementService(userService, implementation, 'server'); * // methods.forEach(method => channel.publishMethod(method)); * * // Just do: * channel.publishService(userService, { * get: async ({ userId }) => ({ name: `User ${userId}`, email: `user${userId}@example.com` }), * create: async ({ name, email }) => ({ id: '123', success: true }) * }); * ``` */ publishService<T extends Record<string, any>>(service: ServiceDefinition<T>, implementation: ServiceImplementation<T>, targetId?: string): void; invoke<T extends ZodSchema, U extends ZodSchema>(targetId: string, methodId: string, input: z.infer<T>, inputSchema?: T, outputSchema?: U, timeout?: number): Promise<z.infer<U>>; getAvailableMethods(serviceId: string): MethodInfo[]; getConnectedServices(): ServiceInfo[]; private handleMessage; private handleRequest; private handleResponse; private handleError; private sendError; private publishServiceInfo; private generateTraceId; } //# sourceMappingURL=channel.d.ts.map