import type { z } from 'zod'; /** * Type representing a Zod RPC method contract with request, response, and optional update schemas */ export interface ZodRpcMethodContract< TRequest extends z.ZodType = z.ZodType, TResponse extends z.ZodType = z.ZodType, TUpdate extends z.ZodType = z.ZodType, > { request: TRequest; response: TResponse; update?: TUpdate; } /** * Type for a map of endpoint methods using Zod schemas */ export type ZodEndpointMethodMap = Record; /** * Type for the complete bridge contract with optional server and client method maps */ export interface ZodBridgeContract { server?: ZodEndpointMethodMap; client?: ZodEndpointMethodMap; } /** * Helper type to infer the TypeScript type from a Zod schema */ export type InferZodType = z.infer; /** * Helper type to extract the request type from a Zod method contract */ export type InferRequestType = InferZodType< T['request'] >; /** * Helper type to extract the response type from a Zod method contract */ export type InferResponseType = InferZodType< T['response'] >; /** * Helper type to extract the update type from a Zod method contract */ export type InferUpdateType = T['update'] extends z.ZodType ? InferZodType : never; /** * Creates a strongly-typed bridge contract with Zod schemas */ export function createBridgeContract( contract: T, ): T { return contract; } /** * Type for method implementations using inferred types from Zod schemas */ export type ZodMethodImplementations = { [K in keyof T]: ( request: InferRequestType, context: { sendUpdate: T[K]['update'] extends z.ZodType ? (update: InferUpdateType) => void : never; }, ) => Promise>; }; /** * Type for method calls using inferred types from Zod schemas */ export type ZodMethodCalls = { [K in keyof T]: T[K]['update'] extends z.ZodType ? ( request: InferRequestType, options: { onUpdate: (update: InferUpdateType) => void }, ) => Promise> : (request: InferRequestType) => Promise>; }; /** * Validates data against a Zod schema and throws if validation fails */ export function validateWithZod( schema: T, data: unknown, context: string, silent = false, ): z.infer { const result = schema.safeParse(data); if (!result.success) { const error = new Error( `Validation failed for ${context}: ${result.error.message}`, ); if (silent) { console.error(error); return data as z.infer; // Return original data for silent validation } throw error; } return result.data; }