computers
Version:
computer←→computer
66 lines (62 loc) • 2.31 kB
TypeScript
/**
* Used to access the internal unsubscribe function that exists on a wrapped client
*
* We might eventually move the unsubscribe method to a single "internals" object
* which could contain the `.call()` method among other internal functionality.
*
* @internal
*/
declare const SYMBOL_TRANSPORT_UNSUBSCRIBE: unique symbol;
type API = {
[Key in string]: API | ((...args: any[]) => unknown);
};
type WrapAPIToClient<T> = {
[K in keyof T]-?: T[K] extends (...args: any[]) => any ? ReturnType<T[K]> extends Promise<any> ? T[K] : (...args: Parameters<T[K]>) => Promise<ReturnType<T[K]>> : T[K] extends object ? WrapAPIToClient<T[K]> : never;
} & {
[SYMBOL_TRANSPORT_UNSUBSCRIBE]: () => void;
};
declare namespace Protocol {
interface Request {
type: 'request';
nonce: string;
path: string;
args: unknown[];
}
namespace Response {
interface Success extends CallerResultSuccess {
type: 'response';
nonce: string;
}
interface Failure extends CallerResultFailure {
type: 'response';
nonce: string;
}
}
type Response = Response.Success | Response.Failure;
type Message = Request | Response;
}
interface TransportOptions {
call: (path: string, args: unknown[]) => Promise<CallerResult>;
send: (message: Protocol.Message) => void;
subscribe: (listener: (event: Protocol.Message) => void) => () => void;
}
interface CallerResultSuccess {
success: true;
data: unknown;
}
interface CallerResultFailure {
success: false;
message: string;
}
type CallerResult = CallerResultSuccess | CallerResultFailure;
/**
* Calls a function by looking up the path in the API
*
* @param api The API to call
* @param path The path to the function to call
* @param args The arguments to pass to the function
*
* @returns A result type that is either a success with the result of the function call or a failure with an error message
*/
declare function call(api: API, path: string, args: unknown[]): Promise<CallerResult>;
export { type API as A, type CallerResultSuccess as C, Protocol as P, SYMBOL_TRANSPORT_UNSUBSCRIBE as S, type TransportOptions as T, type WrapAPIToClient as W, type CallerResultFailure as a, type CallerResult as b, call as c };