// tslint:disable:interface-over-type-literal export type DefaultRequestTypes = {}; export type DefaultResponseTypes = {}; export type DefaultErrorType = { code: number; message: string; data?: any; }; export type DefaultNotificationTypes = {}; // tslint:enable:interface-over-type-literal // export interface RpcTypes { // RequestTypes: DefaultRequestTypes; // ResponseTypes: DefaultResponseTypes; // NotificationTypes: DefaultNotificationTypes; // ErrorType: DefaultErrorType; // } export interface Request { type: "request"; id: number; method: Method; params: RequestTypes[Method]; } export interface ResponseBase { type: "response"; id: number; method: Method; } export interface SuccessData { result: "success"; data: ResponseType; } export interface ErrorData { result: "error"; error: ErrorType; } export type ResponseData = SuccessData | ErrorData; export type Response = ResponseBase & ResponseData; export interface Notification { type: "notification"; method: Method; data: NotificationTypes[Method]; } export type Message = Request | Response | Notification; // export type TypesMessage = // Message; export function isRequestMethod( message: Request, method: Method, ): message is Request { return message.method === method; } export function isResponseMethod( message: Response, method: Method, ): message is Response { return message.method === method; } export function isNotificationMethod( message: Notification, method: Method, ): message is Notification { return message.method === method; } export type IRequestHandler = (request: RequestTypes[Method]) => Promise>; export type RequestHandlers = { [Method in keyof RequestTypes]: IRequestHandler; }; export type IResponseHandler = (response: ResponseData) => void; export interface ResponseHandlers { [id: number]: IResponseHandler; } export type NotificationHandler = (notification: NotificationTypes[Method]) => void; export type NotificationHandlers = { [Method in keyof NotificationTypes]: NotificationHandler; }; export function listRequestHandlerMethods( handlers: RequestHandlers, ): Array { return Object.keys(handlers) as any; } export function listNotificationHandlerMethods( handlers: NotificationHandlers, ): Array { return Object.keys(handlers) as any; } export async function handleRequest( handlers: RequestHandlers, message: Request, ): Promise> { const handler = handlers[message.method]; if (!handler) { throw new Error("No handler for request method " + message.method); } return handler(message.params); } export function handleResponse( handlers: ResponseHandlers, message: Response) { const handler = handlers[message.id]; if (!handler) { return; } return handler(message); } export function handleNotification( handlers: NotificationHandlers, message: Notification) { const handler = handlers[message.method]; if (!handler) { throw new Error("No handler for notification method " + message.method); } return handler(message.data); }