fontcolor_theme
package

API @deepkit/rpc

npm install @deepkit/rpc

Classes

RpcControllerState [source]
export class RpcControllerState {
    peerId?: string;
    constructor(public controller: string);
    getState(method: string): ControllerStateActionState;
}
RpcActionClient [source]
export class RpcActionClient {
    entityState;
    fastHost?: RpcFastHost;
    /**  A transfer was aborted: nothing will be answered anymore. */
    abort(id: number, error: Error): void;
    /**
     * The connection is gone, nothing on it can be answered anymore.
     */
    onDisconnect(error?: Error): void;
    /**
     * A call to the connection itself: authentication, peers and the like.
     */
    systemCall(op: ControlOp, serialize?: AutoBufferSerializer, value?: any, deserialize?: ReturnDeserializer): Promise<any>;
    action<T>(controller: RpcControllerState, method: string, args: any[], options: {
        timeout?: number;
        dontWaitForConnection?: true;
        typeReuseDisabled?: boolean;
    } = {}): Promise<any>;
    /**  The types of an action, as they are described by the server. */
    async loadActionTypes(controller: RpcControllerState, method: string, options: {
        timeout?: number;
        dontWaitForConnection?: true;
        typeReuseDisabled?: boolean;
    } = {}): Promise<ControllerStateActionTypes>;
}
DirectClient [source]
export class DirectClient extends RpcClient {
    constructor(rpcKernel: RpcKernel, injector?: InjectorContext);
}
RpcDirectClientAdapter [source]
export class RpcDirectClientAdapter implements ClientTransportAdapter {
    constructor(public rpcKernel: RpcKernel, protected injector?: InjectorContext);
    async connect(connection: TransportClientConnection);
}
AsyncDirectClient [source]
export class AsyncDirectClient extends RpcClient {
    constructor(rpcKernel: RpcKernel, injector?: InjectorContext);
}

This direct client includes in each outgoing/incoming message an async hop making the communication asynchronous.

RpcAsyncDirectClientAdapter [source]
export class RpcAsyncDirectClientAdapter implements ClientTransportAdapter {
    constructor(public rpcKernel: RpcKernel, protected injector?: InjectorContext);
    async connect(connection: TransportClientConnection);
}
RpcWebSocketClient [source]
export class RpcWebSocketClient extends RpcClient {
    constructor(url: string);
    static fromCurrentHost<T extends ClassType<RpcClient>>(this: T, baseUrl: string = ): InstanceType<T>;
}

A RpcClient that connects via WebSocket transport.

DeepkitClient [source]
export class DeepkitClient extends RpcWebSocketClient {
}
RpcWebSocketClientAdapter [source]
export class RpcWebSocketClientAdapter implements ClientTransportAdapter {
    constructor(public url: string, protected webSocketConstructor: typeof WebSocket = WebSocket);
    async getWebSocketConstructor(): Promise<typeof WebSocket>;
    async connect(connection: TransportClientConnection);
}
RpcClientToken [source]
export class RpcClientToken {
    constructor(protected token: any);
    get();
    set(v: any);
    has();
}
RpcClientTransporter [source]
export class RpcClientTransporter {
    connectionId: number;
    writerOptions: TransportOptions;
    id?: Uint8Array;
    /**
     * When the connection is established (including handshake and authentication).
     */
    readonly connection;
    /**
     * When the connection was reconnected. This is not called for the very first connection.
     */
    readonly reconnected;
    /**
     * When the connection was disconnected (due to error or close).
     * This increases the connectionId by one.
     */
    readonly disconnected;
    /**
     * Triggered for any onError call from the transporter.
     * Right after this event, onDisconnect is called (and thus connection.next(false) and disconnected.next()).
     */
    readonly errored;
    reader;
    /**  Hash of the action schema the handshake delivered, to not transfer it again. */
    schemaHash: number;
    constructor(public transport: ClientTransportAdapter, protected stats: RpcStats);
    bufferedAmount(): number;
    clientAddress(): string;
    /**
     * True when fully connected (after successful handshake and authentication)
     */
    isConnected(): boolean;
    onClose(error?: Error);
    /**
     * Optional handshake.
     * When peer messages are allowed, this needs to request the client id and returns id.
     */
    async onHandshake(): Promise<Uint8Array | undefined>;
    async onAuthenticate(token?: any): Promise<void>;
    /**
     * Receives all frames that are not chunks. The buffer is only valid during this call.
     */
    onFrame(buffer: Uint8Array, start: number, end: number): void;
    onSchema(mapping: ParsedSchemaMapping, hash: number): void;
    /**
     * Reads the handshake reply: the protocol version of the server, and the action schema if it is new to us.
     */
    onHelloReply(buffer: Uint8Array, start: number, end: number): void;
    /**  Whether a connection exists to send frames on. */
    canSend(): boolean;
    /**  Asks for the actions of the server again. */
    async refreshSchema(): Promise<void>;
    /**
     * Sends the frame in the range 0 to size of the buffer, see RpcFrameSender.
     */
    sendFrame(buffer: Uint8Array, size: number, progress?: SingleProgress): void;
    async disconnect();
    /**
     * Simply connect with login using the token, without auto re-connect.
     */
    async connect(token?: any): Promise<void>;
}
RpcClientPeer [source]
export class RpcClientPeer {
    constructor(protected actionClient: RpcActionClient, protected peerId: string, protected onDisconnect: (peerId: string) => void);
    controller<T>(nameOrDefinition: string | ControllerDefinition<T>, options: {
        timeout?: number;
        dontWaitForConnection?: true;
    } = {}): RemoteController<T>;
    disconnect();
}
RpcBaseClient [source]
export class RpcBaseClient implements RpcFastHost {
    clientStats: RpcStats;
    actionClient;
    readonly token;
    readonly transporter: RpcClientTransporter;
    username?: string;
    typeReuseDisabled: boolean;
    events;
    constructor(protected transport: ClientTransportAdapter);
    onFrame(buffer: Uint8Array, start: number, end: number): void;
    /**
     * Receives the frames of a push channel, see writePushFrameTransient. The range of the values is only valid during the call.
     */
    onPush(channel: number, handler: RpcPushHandler): void;
    getSchemaMapping(): ParsedSchemaMapping | undefined;
    getSchemaEpoch(): number;
    isActionReady(dontWaitForConnection?: boolean): boolean;
    getContexts(): SequentialContextDispatcher<FrameHandler>;
    getChunkSize(): number;
    sendActionFrame(buffer: Uint8Array, size: number, progress?: SingleProgress): void;
    registerDownloadProgress(id: number, progress: SingleProgress): void;
    isObserved(): boolean;
    emitEvent(event: RpcClientEvent): void;
    connectForAction(): Promise<unknown>;
    refreshSchema(): Promise<unknown>;
    hasBinaryTransport(): boolean;
    getHttpTransport(): RpcHttpTransport | undefined;
    getToken(): any;
    currentConnectionId(): number;
    getRoute(): RouteFlag;
    onClose(error?: Error);
    /**
     * Per default entity types with a name (@entity.name()) will be reused. If a entity with a given name
     * was not loaded and error is thrown. This to ensure nominal typing (object instanceof T).
     * Use this method to disable this behavior and construct new nominal types if an entity is not loaded.
     */
    disableTypeReuse(): this;
    getId(): Uint8Array;
    debug();
    async connect(): Promise<this>;
    async disconnect();
}
RpcClient [source]
export class RpcClient extends RpcBaseClient {
    /**
     * For server->client (us) communication.
     * This is automatically created when registerController is called.
     * Set this property earlier to work with a custom RpcKernel.
     */
    clientKernel?: RpcKernel;
    /**
     * For peer->client(us) communication.
     * This is automatically created when registerAsPeer is called.
     * Set this property earlier to work with a custom RpcKernel.
     */
    peerKernel?: RpcKernel;
    async ping(): Promise<void>;
    getPeerRoute(peerId: string): Uint8Array;
    getId(): Uint8Array;
    /**
     * Registers a new controller for the peer's RPC kernel.
     * Use `registerAsPeer` first.
     */
    registerPeerController<T>(classType: ClassType<T>, nameOrDefinition: string | ControllerDefinition<T>);
    /**
     * Registers a new controller for the server's RPC kernel.
     * This is when the server wants to communicate actively with the client (us).
     */
    registerController<T>(classType: ClassType<T>, nameOrDefinition: string | ControllerDefinition<T>);
    async registerAsPeer(id: string);
    /**
     * Creates a new peer connection, or re-uses an existing non-disconnected one.
     *
     * Make sure to call disconnect() on it once you're done using it, otherwise the peer
     * will leak memory. (connection will be dropped if idle for too long automatically tough)
     */
    peer(peerId: string): RpcClientPeer;
    controller<T>(nameOrDefinition: string | ControllerDefinition<T>, options: {
        timeout?: number;
        dontWaitForConnection?: true;
        typeReuseDisabled?: boolean;
    } = {}): RemoteController<T>;
}
RpcClientPool [source]
export class RpcClientPool {
    constructor(public readonly clients: RpcClient[]);
    /**  Calls in flight per client. */
    get load(): readonly number[];
    controller<T>(nameOrDefinition: string | ControllerDefinition<T>, options?: {
        timeout?: number;
        dontWaitForConnection?: true;
    }): RemoteController<T>;
    async disconnect(): Promise<void>;
}

Spreads the calls of its controllers over several clients, for example one per worker thread, so that the work runs in parallel. Each call goes to the client with the fewest calls in flight.

const pool = new RpcClientPool(
    Array.from({ length: 4 }, () => {
        const worker = new Worker('./server.js');
        return new RpcClient(new RpcChannelClientAdapter(createMessagePortChannel(worker)));
    }),
);
const image = pool.controller<ImageController>('image');
await Promise.all(files.map(file => image.resize(file, 200)));

A call that returns an Observable or Collection stays with its client. Calls of one controller are not ordered among each other, since they may run on different clients.

RpcHttpFetch [source]
export class RpcHttpFetch implements RpcHttpInterface {
    constructor(private baseUrl: string | ((url: string) => string) = );
    async fetch(url: string, options: {
        headers: {
            [name: string]: string;
        };
        method: string;
        body: any;
    }): Promise<RpcHttpResponseInterface>;
}
RpcHttpClientAdapter [source]
export class RpcHttpClientAdapter implements ClientTransportAdapter, RpcHttpTransport {
    constructor(public url: string, public headers: {
        [name: string]: string;
    } = {}, public http: RpcHttpInterface = new RpcHttpFetch());
    supportsPeers();
    supportsAuthentication();
    httpTransport(): RpcHttpTransport;
    async connect(connection: TransportClientConnection): Promise<void>;
    requestTypes(controller: string, method: string, token: any): Promise<RpcHttpActionTypes>;
    requestCall(controller: string, method: string, args: any[], token: any): Promise<any>;
}
RpcChannelMessageWriter [source]
export class RpcChannelMessageWriter implements BinarySocket {
    readonly writableLength;
    constructor(protected send: (data: Uint8Array) => void, protected capacity: number =  * );
    write(buffer: Uint8Array): void;
    writeRange(buffer: Uint8Array, start: number, end: number): void;
    flush(): void;
}

Collects the frames written in one tick into one message. Every message is a new buffer of the exact size, so that channels can transfer it to the other side instead of copying it.

RpcChannelClientAdapter [source]
export class RpcChannelClientAdapter implements ClientTransportAdapter {
    constructor(public channel: RpcChannel);
    async connect(connection: TransportClientConnection): Promise<void>;
}

Connects to a RpcKernel on the other side of a channel.

const worker = new Worker('./server.js');
const client = new RpcClient(new RpcChannelClientAdapter(createMessagePortChannel(worker)));

The channel can carry one connection at a time. After a disconnect the client connects again over the same channel.

SharedMemoryChannel [source]
export class SharedMemoryChannel implements RpcChannel {
    readonly name;
    readonly binarySocket: BinarySocket;
    constructor(memory: SharedArrayBuffer, side:  | , options: SharedMemoryChannelOptions = {});
    send(data: Uint8Array): void;
    end(): void;
    listen(onData: (data: Uint8Array, bytes?: number) => void, onEnd: (reason: string) => void): () => void;
    /**  Ends listening and the current connection, when the other thread is gone. */
    close(): void;
}

A channel between two threads over shared memory, without messages: the sender copies the frames directly into a ring buffer, the receiver reads them from there. It's the fastest channel between threads, in node's worker_threads as in the browser's Web Workers. In the browser, SharedArrayBuffer needs a page with cross-origin isolation (the headers Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp), and both sides need Atomics.waitAsync.

// main thread
const memory = createRpcSharedMemory();
const worker = new Worker('./server.js', { workerData: { memory } });
const client = new RpcClient(new RpcChannelClientAdapter(createSharedMemoryChannel(memory, 'client')));

// worker
serveRpcChannel(kernel, createSharedMemoryChannel(workerData.memory, 'server'));

The memory doesn't tell when the other thread ends: call close() of the channel then, for example on the exit event of the worker.

EntitySubjectStore [source]
export class EntitySubjectStore<T extends IdVersionInterface> {
    store;
    onCreation;
    constructor(protected classType: ClassType);
    isRegistered(id: IdType): boolean;
    register(item: T): void;
    deregister(id: IdType): void;
    getItem(id: IdType): T | undefined;
    onDelete(id: IdType): void;
    onSet(id: IdType, item: T): void;
    onPatch(id: IdType, version: number, patch: EntityPatch): void;
    /**
     * Before calling createFork you must be sure the item is already registered.
     */
    createFork(id: IdType): EntitySubject<T>;
    getForkCount(id: IdType): number;
    getEntitySubjectCount(): number;
}
EntityState [source]
export class EntityState {
    getStore<T extends IdVersionInterface>(classType: ClassType<T>): EntitySubjectStore<T>;
    getStoreByName<T extends IdVersionInterface>(name: string): EntitySubjectStore<T>;
    onEntityPatch(body: rpcEntityPatch): void;
    onEntityRemove(body: rpcEntityRemove): void;
}
RpcServerAction [source]
export class RpcServerAction {
    constructor(protected stats: RpcStats, protected cache: RpcCache, protected connection: RpcKernelBaseConnection, protected controllers: Map<string, {
        controller: ClassType;
        module?: InjectorModule;
    }>, protected injector: InjectorContext, protected eventDispatcher: EventDispatcher, protected security: RpcKernelSecurity, protected sessionState: SessionState, protected logger: LoggerInterface, protected dispatcher?: ActionDispatcher);
    /**
     * Frees everything held for a stream context. Returns false when nothing was held,
     * which also means the context already ended and no end frame must be sent again.
     */
    closeContext(id: number): boolean;
    async onClose();
    /**  A control frame of a stream. The frame is only valid during this call. */
    handleControl(op: ControlOp, id: number, buffer: Uint8Array, offset: number, end: number): void;
    /**
     * Runs the action of a fast path frame. Everything needed from the frame is read synchronously.
     */
    execute(buffer: Uint8Array, id: number, actionId: number, bodyOffset: number, end: number): void;
    /**
     * Calls an action with everything that observes or guards it. An error is what should be sent to the client.
     */
    async invoke(cache: RpcCacheAction, args: any[], decodeError?: any): Promise<any>;
    /**  An action called over HTTP: the arguments are JSON, and so is what is returned. */
    async invokeJson(controllerName: string, methodName: string, args: any[]): Promise<{
        value: any;
        type: Type;
    }>;
    /**  What the HTTP client needs to know to call an action, without the handshake a connection has. */
    jsonTypes(controllerName: string, methodName: string): ActionTypes;
}
RpcPeerExchange [source]
export class RpcPeerExchange {
    async isRegistered(id: string): Promise<boolean>;
    async deregister(id: string | Uint8Array): Promise<void>;
    register(id: string | Uint8Array, writer: TransportConnection): void;
    /**  Sends a whole frame on to where its route data says, nothing of it is read. */
    redirect(frame: Uint8Array);
}

This is a reference implementation and only works in a single process. A real-life implementation would use an external message-bus, like Redis & co.

RpcKernelBaseConnection [source]
export abstract class RpcKernelBaseConnection implements RpcFastHost {
    sessionState;
    /**
     * Statistics about the server->client communication.
     */
    clientStats: RpcStats;
    transportOptions: TransportOptions;
    readonly onClose: Promise<void>;
    closed: boolean;
    /**  The route data frames of this connection need, set when it answers a peer. */
    routeData?: Uint8Array;
    constructor(public stats: RpcStats, protected logger: Logger, public transportConnection: TransportConnection, protected connections: RpcKernelConnections, protected injector: InjectorContext, protected eventDispatcher: EventDispatcher);
    /**
     * Sends a frame. Valid only for transports with a binary connection.
     */
    sendFrame(buffer: Uint8Array, size: number, progress?: SingleProgress): void;
    get routeFlag(): RouteFlag;
    /**  Tells the client entities changed. */
    sendEntityPatch(patch: rpcEntityPatch): void;
    sendEntityRemove(remove: rpcEntityRemove): void;
    clientAddress(): string | undefined;
    /**
     * Creates a regular timer using setTimeout() and automatically cancel it once the connection breaks or server stops.
     */
    setTimeout(cb: () => void, timeout: number): any;
    close(reason: string | Error = ): void;
    feed(buffer: Uint8Array, bytes?: number): void;
    /**  A frame from an already split up stream. The buffer is only valid during this call. */
    feedFrame(buffer: Uint8Array, start: number, end: number): void;
    getSchemaMapping(): ParsedSchemaMapping | undefined;
    getSchemaEpoch(): number;
    isActionReady(): boolean;
    getContexts(): SequentialContextDispatcher<FrameHandler>;
    getChunkSize(): number;
    sendActionFrame(buffer: Uint8Array, size: number, progress?: SingleProgress): void;
    isObserved(): boolean;
    emitEvent(event: any): void;
    /**  The other side may have registered controllers since it was last asked. */
    refreshSchema(): Promise<unknown>;
    connectForAction(): Promise<unknown>;
    hasBinaryTransport(): boolean;
    currentConnectionId(): number;
    getRoute(): RouteFlag;
    onRequest(basePath: string, request: RpcHttpRequest, response: RpcHttpResponse): void | Promise<void>;
    controller<T>(nameOrDefinition: string | ControllerDefinition<T>, timeoutInSeconds = ): RemoteController<T>;
}
RpcKernelConnections [source]
export class RpcKernelConnections {
    connections: RpcKernelBaseConnection[];
    stats: RpcTransportStats;
}
RpcCache [source]
export class RpcCache {
    actionsTypes: {
        [id: string]: ActionTypes;
    };
    actions: {
        [id: string]: RpcCacheAction;
    };
}
RpcKernelConnection [source]
export class RpcKernelConnection extends RpcKernelBaseConnection {
    myPeerId?: string;
    routeType: MessageFlag.RouteClient | MessageFlag.RouteServer;
    constructor(stats: RpcStats, logger: Logger, transport: TransportConnection, connections: RpcKernelConnections, injector: InjectorContext, eventDispatcher: EventDispatcher, protected cache: RpcCache, protected controllers: Map<string, {
        controller: ClassType;
        module?: InjectorModule;
    }>, protected security = new RpcKernelSecurity(), protected peerExchange: RpcPeerExchange, protected actionDispatcher?: ActionDispatcher);
    close(): void;
    get routeFlag(): RouteFlag;
    async onRequest(basePath: string, request: RpcHttpRequest, response: RpcHttpResponse);
}
RpcKernel [source]
export class RpcKernel {
    readonly controllers;
    stats;
    injector: InjectorContext;
    constructor(injector?: InjectorContext | NormalizedProvider[], protected logger: Logger = new Logger());
    /**
     * Register a new event listener for given token.
     *
     * order: The lower the order, the sooner the listener is called. Default is 0.
     */
    listen<T extends EventToken<any>>(eventToken: T, callback: EventListenerCallback<T>, order: number = ): EventDispatcherUnsubscribe;
    getEventDispatcher(): EventDispatcher;
    onConnection(callback: OnConnectionCallback);
    /**
     * This registers the controller and when no custom InjectorContext was given adds it as provider to the injector.
     *
     * Note: Controllers can not be added to the injector when the injector was already built.
     */
    registerController(controller: ClassType, id?: string | ControllerDefinition<any>, module?: InjectorModule);
    createConnection(transport: TransportConnection, injector?: InjectorContext): RpcKernelBaseConnection;
}

The kernel is responsible for parsing the message header, redirecting to peer if necessary, loading the body parser, and encode/send outgoing messages.

Session [source]
export class Session {
    constructor(public readonly username: string, public readonly token: any);
    isAnonymous(): boolean;
}
RpcKernelSecurity [source]
export class RpcKernelSecurity {
    async hasControllerAccess(session: Session, controllerAccess: RpcControllerAccess, connection: RpcKernelBaseConnection): Promise<boolean>;
    async isAllowedToRegisterAsPeer(session: Session, peerId: string): Promise<boolean>;
    async isAllowedToSendToPeer(session: Session, peerId: string): Promise<boolean>;
    async authenticate(token: any, connection: RpcKernelBaseConnection): Promise<Session>;
    transformError(err: Error);
}
SessionState [source]
export class SessionState {
    setSession(session: Session);
    getSession(): Session;
}
ActionDispatcher [source]
export class ActionDispatcher {
    entries: ActionEntry[];
    /**  Set by the kernel: rebuilds when a controller was registered since the last build. */
    rebuild?: () => void;
    schemaMessage: Uint8Array;
    schemaHash: number;
    build(controllers: Iterable<[
        string,
        {
            controller: ClassType;
            module?: InjectorModule;
        }
    ]>, loadTypes: (controller: string, method: string) => ActionTypes): void;
    prepare(entry: ActionEntry, cache: RpcCacheAction, strict: boolean): void;
}

Maps numeric action ids to controller actions and holds the schema that is sent to clients in the handshake. Ids are never reassigned: a client may be connected while a controller is registered later.

PreSerialized [source]
export class PreSerialized {
    /**  BSON element for key "v": type byte, key, value. */
    constructor(public readonly element: Uint8Array);
}

A value serialized once, to be sent in many messages. It is what preSerialize() returns. The bytes are identical to serializing the value in place.

CollectionQueryModel [source]
export class CollectionQueryModel<T> implements CollectionQueryModelInterface<T> {
    filter?: FilterQuery<T>;
    skip?: number;
    itemsPerPage: number;
    limit?: number;
    parameters: {
        [name: string]: any;
    };
    sort?: Sort<T>;
    readonly change;
    set(model: CollectionQueryModelInterface<any>);
    changed(): void;
    hasSort(): boolean;
    /**
     * Whether limit/skip is activated.
     */
    hasPaging(): boolean;
}

internal note: This is aligned with

CollectionState [source]
export class CollectionState {
    /**
     * Total count in the database for the current query, regardless of paging (skip/limit) count.
     *
     * Use count() to get the items count on the current page (which is equal to all().length)
     */
    total: number;
}
Collection [source]
export class Collection<T extends IdInterface> extends ReplaySubject<T[]> {
    readonly event: Subject<CollectionEvent<T>>;
    readonly removed;
    readonly added;
    state: CollectionState;
    readonly deepChange;
    model: CollectionQueryModel<T>;
    readonly entitySubjects;
    constructor(public readonly classType: ClassType<T>);
    getTotal();
    getItemsPerPage();
    getPages();
    getSort();
    getParameter(name: string);
    setParameter(name: string, value: any): this;
    orderByField(name: keyof T & string, order: SORT_ORDER = );
    setPage(page: number);
    getPage();
    apply();
    getEntitySubject(idOrItem: string | number | T): EntitySubject<T> | undefined;
    has(id: string | number);
    get(id: string | number): T | undefined;
    setState(state: CollectionState);
    setSort(ids: (string | number)[]);
    /**
     * Resolves when next change happened.
     */
    get nextStateChange(): Promise<void>;
    unsubscribe();
    addTeardown(teardown: TeardownLogic);
    index(item: T): number;
    /**
     * Returns the page zero-based of the current item.
     */
    getPageOf(item: T, itemsPerPage = ): number;
    reset();
    all(): T[];
    /**
     * Count of current page if paging is used, otherwise total count.
     */
    count();
    ids(): (string | number)[];
    empty();
    /**
     * All items from id -> value map.
     */
    map();
    loaded();
    set(items: T[], withEvent = true);
    removeMany(ids: (string | number)[], withEvent = true);
    update(items: T | T[], withEvent = true);
    add(items: T | T[], withEvent = true);
    remove(ids: (string | number) | (string | number)[], withEvent = true);
}
RpcController [source]
export class RpcController {
    name: string;
    classType?: ClassType;
    definition?: ControllerDefinition<any>;
    strictSerialization: boolean;
    logValidationErrors: boolean;
    actions;
    getPath(): string;
}
RpcAction [source]
export class RpcAction {
    name: string;
    classType: ClassType;
    category: string;
    description: string;
    strictSerialization?: boolean;
    logValidationErrors?: boolean;
    groups: string[];
    data: {
        [name: string]: any;
    };
}
RpcTransportStats [source]
export class RpcTransportStats {
    readonly incomingBytes: number;
    readonly outgoingBytes: number;
    /**
     * Amount of incoming and outgoing messages.
     */
    readonly incoming: number;
    readonly outgoing: number;
    increase(name: NumericKeys<RpcTransportStats>, count: number);
    /**  One incoming message. The same as increase(), without looking up a property by name per message. */
    addIncoming(): void;
    /**  One outgoing message of the given size. */
    addOutgoing(bytes: number): void;
}
ActionStats [source]
export class ActionStats {
    readonly observables: number;
    readonly subjects: number;
    readonly behaviorSubjects: number;
    readonly progressTrackers: number;
    readonly subscriptions: number;
    increase(name: NumericKeys<ActionStats>, count: number);
}
ForwardedActionStats [source]
export class ForwardedActionStats extends ActionStats {
    constructor(protected forward: ActionStats);
    increase(name: NumericKeys<ActionStats>, count: number);
}
RpcStats [source]
export class RpcStats extends RpcTransportStats {
    readonly connections: number;
    readonly totalConnections: number;
    /**
     * How many actions have been executed.
     */
    readonly actions: number;
    readonly active: ActionStats;
    readonly total: ActionStats;
    increase(name: NumericKeys<RpcStats>, count: number);
    /**  One executed action. */
    addAction(): void;
}
ForwardedRpcStats [source]
export class ForwardedRpcStats extends RpcStats {
    readonly active;
    readonly total;
    constructor(protected forward: RpcStats);
    increase(name: NumericKeys<RpcStats>, count: number);
    addIncoming(): void;
    addOutgoing(bytes: number): void;
    addAction(): void;
}
StreamBehaviorSubject [source]
export class StreamBehaviorSubject<T> extends BehaviorSubject<T> {
    readonly appendSubject;
    constructor(item: T, teardown?: TeardownLogic);
    isUnsubscribed(): boolean;
    get nextStateChange();
    addTearDown(teardown: TeardownLogic);
    /**
     * This method differs to BehaviorSubject in the way that this does not throw an error
     * when the subject is closed/unsubscribed.
     */
    getValue(): T;
    next(value: T): void;
    activateNextOnAppend();
    toUTF8();
    append(value: T): void;
    unsubscribe(): void;
}
EntitySubject [source]
export class EntitySubject<T extends IdInterface> extends StreamBehaviorSubject<T> {
    /**
     * Patches are in class format.
     */
    readonly patches;
    readonly delete;
    [IsEntitySubject];
    deleted: boolean;
    get id(): string | number;
    get onDeletion(): Observable<void>;
    next(value: T | undefined): void;
}
ControllerDefinition [source]
export class ControllerDefinition<T> {
    constructor(public path: string, public entities: ClassType[] = []);
}
JSONError [source]
@entity.name()
export class JSONError {
    constructor(public readonly json: any);
}
RpcBinaryMessageReader [source]
export class RpcBinaryMessageReader extends FrameReader {
    /**
     * Receives every frame except chunks. Only valid during the call.
     */
    onRawFrame?: (buffer: Uint8Array, start: number, end: number) => void;
    /**  A transfer of the context was aborted. */
    onAbort?: (id: number, error: Error) => void;
    constructor(protected readonly onChunk?: (id: number, abort: boolean, route: RouteFlag) => void);
    cleanUp();
    onChunkAck(id: number, callback: (active: boolean) => void, route: RouteFlag = MessageFlag.RouteClient);
    removeChunkAck(id: number, aborted = false, route: RouteFlag = MessageFlag.RouteClient);
    registerProgress(id: number, progress: SingleProgress);
    feed(buffer: Uint8Array, length: number = buffer.byteLength);
}

Splits the byte stream into frames. Frames are passed on with no copy and nothing allocated: the owner sets onRawFrame and decodes what it needs inside the call. Chunked frames are put together here.

SingleProgress [source]
export class SingleProgress extends Subject<SingleProgress> {
    done;
    total;
    current;
    stats;
    abortController: AbortController;
    finished;
    constructor();
    /**
     * Aborts the current progress (either upload or download).
     */
    abort();
    get aborted();
    /**
     * Acts like a BehaviorSubject.
     */
    _subscribe(subscriber: Subscriber<SingleProgress>): Subscription;
    setStart(total: number);
    setBatch(size: number);
    get progress(): number;
    set(total: number, current: number);
}
Progress [source]
export class Progress extends BehaviorSubject<number> {
    readonly upload;
    readonly download;
    /**
     * Aborts both upload and download progress.
     */
    abort();
    constructor();
}
ClientProgress [source]
export class ClientProgress {
    static nextProgress?: Progress;
    /**
     * Returns the current stack and sets a new one.
     */
    static getNext(): Progress | undefined;
    /**
     * Sets up a new Progress object for the next API request to be made.
     * Only the very next API call will be tracked.
     *
     * @example
     * ```typescript
     *
     * const progress = ClientProgress.track();
     * await api.myMethod();
     *
     * ```
     */
    static track(): Progress;
}
TransportOptions [source]
export class TransportOptions {
    /**
     * Stores big buffers to the file system and stream it from there.
     * In bytes.
     * note: not implemented yet
     */
    cacheOnFileSystemWhenSizeIsAtLeast: number;
    /**
     * When back-pressure is bigger than this value, we wait with sending new data.
     * In bytes.
     * note: not implemented yet
     */
    stepBackWhenBackPressureBiggerThan: number;
    /**
     * Chunk size.
     * In bytes.
     */
    chunkSize: number;
    /**
     * How long a client waits for the reply to its handshake before it gives up.
     * In milliseconds, 0 disables it.
     */
    handshakeTimeout: number;
}
TransportBinaryMessageChunkWriter [source]
export class TransportBinaryMessageChunkWriter {
    constructor(protected reader: RpcBinaryMessageReader, protected options: TransportOptions);
    /**
     * A small message has to wait as well while a large one of its context is sent in chunks, or it would overtake it.
     */
    needsWriteFull(size: number): boolean;
    /**
     * Writes a message buffer to the connection and chunks if necessary.
     */
    write(writer: RpcBinaryWriter, message: Uint8Array, progress?: SingleProgress): void;
    async writeFull(writer: RpcBinaryWriter, buffer: Uint8Array, progress?: SingleProgress): Promise<void>;
}

This class acts as a layer between kernel/client and a connection writer. It automatically chunks long messages into multiple smaller one using the RpcType.Chunks type.

todo: It keeps track of the back-pressure and sends only when the pressure is not too big. It automatically saves big buffer to the file system and streams data from there to not block valuable memory.

Events

onRpcConnection [source]
EventTokenSync<DataEvent<RpcConnectionEvent>>
onRpcConnectionClose [source]
EventTokenSync<DataEvent<RpcConnectionCloseEvent>>
onRpcAction [source]
EventTokenSync<DataEvent<RpcActionEvent>>
onRpcAuth [source]
EventToken<DataEvent<RpcAuthEvent>>
onRpcControllerAccess [source]
EventToken<DataEvent<RpcControllerAccessEvent>>

Errors

RpcError [source]
export class RpcError extends CustomError {
}
AuthenticationError [source]
export class AuthenticationError extends CustomError {
}
RpcProtocolVersionError [source]
export class RpcProtocolVersionError extends RpcError {
}

Const

RpcHttpHeaderNames [source]
string[]
maxActions [source]
65535
anyType [source]
Type
anyParametersType [source]
TypeTuple
schemaMapping [source]
{ encode: BSONSerializer; decode: BSONDeserializer<SchemaMapping>; }
routeMask [source]
3
contextMask [source]
12
typeMask [source]
112
framePrefixSize [source]
5
contextIdSize [source]
2
actionIdSize [source]
2
rpcProtocolVersion [source]
2
connectionContextBase [source]
61440

Context ids from here on are calls to the connection itself (see ControlOp) and schema requests. They are a range of their own so that they don't disturb the implicit counting of TypeAction.

rpcErrorSettings [source]
{ exposeStack: boolean; exposeCause: boolean; }

Functions

createRemoteController [source]
<T>(actionClient: RpcActionClient, controller: RpcControllerState, options: { timeout?: number; dontWaitForConnection?: true; typeReuseDisabled?: boolean; }): T

The proxy behind client.controller

webSocketFromBaseUrl [source]
(baseUrl: string, portMapping?: { [name: number]: number; }): string

Returns the WebSocket URL for the given base URL and allows port mapping. Default port-mapping maps Angular server :4200 to :8080

provideRpcWebSocketClient [source]
(baseUrl?: string, portMapping?: { [name: number]: number; }): { provide: typeof RpcWebSocketClient; useFactory: () => RpcWebSocketClient; }

Creates a provider for RpcWebSocketClient that is compatible with Angular and Deepkit. baseUrl needs to be absolute.

createRpcHttpClientProvider [source]
(baseUrl?: string, headers?: { [name: string]: string; }, http?: RpcHttpInterface): { provide: typeof RpcClient; useFactory: () => RpcClient; }
serveRpcChannel [source]
(kernel: RpcKernel, channel: RpcChannel, injector?: InjectorContext): RpcChannelServer

Serves the RpcKernel to the other side of a channel, where a RpcClient connects with RpcChannelClientAdapter.

// in the worker
import { parentPort } from 'node:worker_threads';
serveRpcChannel(kernel, createMessagePortChannel(parentPort!));

Each connection gets its own scope rpc of the kernel's injector, unless an injector is given.

createMessagePortChannel [source]
(port: RpcMessagePortLike, name?: string): RpcChannel

A channel over a MessagePort, a MessageChannel's port, a Worker, or self in a Web Worker, of the browser or of node's worker_threads. Messages are transferred, not copied.

Other messages may share the port: messages that are not a Uint8Array are ignored.

createProcessChannel [source]
(process: RpcProcessLike, name?: string): RpcChannel

A channel over the IPC channel of a forked child process: the ChildProcess in the parent, and process in the child. The child has to be started with serialization: 'advanced', so that bytes are sent as bytes:

const child = fork('./server.js', { serialization: 'advanced' });
const client = new RpcClient(new RpcChannelClientAdapter(createProcessChannel(child)));

Other messages may share the channel: messages that are not a Uint8Array are ignored. createStreamChannel() over an extra pipe of the child is faster.

createStreamChannel [source]
(stream: RpcStreamLike, name?: string): RpcChannel

A channel over a byte stream, for example an extra pipe of a child process:

// parent
const child = spawn('node', ['server.js'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe'] });
const client = new RpcClient(new RpcChannelClientAdapter(createStreamChannel(child.stdio[3] as Socket)));

// child
serveRpcChannel(kernel, createStreamChannel(new Socket({ fd: 3, readable: true, writable: true })));

A stream carries one connection: ending it ends the stream.

createRpcSharedMemory [source]
(capacity?: number): SharedArrayBuffer

Creates the shared memory for createSharedMemoryChannel(). Pass it to the other thread, for example as workerData or with postMessage().

createSharedMemoryChannel [source]
(memory: SharedArrayBuffer, side: "client" | "server", options?: SharedMemoryChannelOptions): SharedMemoryChannel
loadActionTypes [source]
(cache: RpcCache, controllers: Map<string, { controller: ClassType; module?: InjectorModule; }>, controller: string, methodName: string): ActionTypes
nextValueType [source]
(types: ActionTypes): Type
createParameterSerializer [source]
(parameters: TypeTuple): AutoBufferSerializer
createParameterDeserializer [source]
(parameters: TypeTuple): ParameterDeserializer

Reads the arguments into an array that is reused for every call unless there is a rest parameter, so the caller has to be done with it before the next call. Must not be called re-entrantly.

createReturnSerializer [source]
(type: Type): AutoBufferSerializer
createReturnDeserializer [source]
(type: Type): ReturnDeserializer
getBodyCodec [source]
(type: Type): BodyCodec

How the body of a message of the given type is written: the values of its properties one after the other in the order they are declared, exactly like the arguments of a call. A property that isn't given keeps its position, see setSerializerCode. Any other type is a single value.

fnv1aHash [source]
(buffer: Uint8Array): number
parseSchemaMapping [source]
(mapping: SchemaMapping): ParsedSchemaMapping
getActions [source]
<T>(target: ClassType<T>): Map<string, RpcAction>
rpcClass [source]
ClassDecoratorResult<typeof RpcClass>
rpcProperty [source]
PropertyDecoratorResult<typeof RpcProperty>
rpc [source]
FluidDecorator<RpcClass, ClassDecoratorFn> & ClassDecoratorFn & { _fetch: (classType: AbstractClassType, property?: string | undefined, parameterIndexOrDescriptor?: any) => RpcController | undefined; } & FluidDecorator<...> & PropertyDecoratorFn & { ...; }
isEntitySubject [source]
(v: any): v is EntitySubject<any>
ControllerSymbol [source]
<T>(path: string, entities?: ClassType[]): ControllerDefinition<T>
isRouteFlag [source]
(flags: number, route: RouteFlag): boolean
isContextFlag [source]
(flags: number, context: ContextFlag): boolean
hasContext [source]
(flags: number): boolean

Whether the frame carries a context id: ContextExisting or ContextEnd.

isTypeFlag [source]
(flags: number, type: TypeFlag): boolean
setRouteFlag [source]
(buffer: Uint8Array, route: RouteFlag, start?: number): void
setContextFlag [source]
(buffer: Uint8Array, context: ContextFlag, start?: number): void
setTypeFlag [source]
(buffer: Uint8Array, type: TypeFlag, start?: number): void
writeUint16LE [source]
(buffer: Uint8Array, offset: number, value: number): void
readUint16LE [source]
(buffer: Uint8Array, offset: number): number
readUint32LE [source]
(buffer: Uint8Array, offset?: number): number
getRouteDataSize [source]
(buffer: Uint8Array, start?: number): number

The bytes that route data takes at the start of the frame at start.

getContextIdOffset [source]
(buffer: Uint8Array, start?: number): number
getContextId [source]
(buffer: Uint8Array, start?: number): number
getActionOffset [source]
(buffer: Uint8Array, start?: number): number
getAction [source]
(buffer: Uint8Array, start?: number): number
getBodyOffset [source]
(buffer: Uint8Array, start?: number): number

Offset of the body of a frame. For TypeChannel and TypeControl that is the offset of their type header.

getPeerId [source]
(buffer: Uint8Array, start?: number): string

The peer a frame routed via peer goes to.

copyFrame [source]
(buffer: Uint8Array, start: number, end: number): Uint8Array

Copy of a frame that outlives the read buffer. A Buffer's own slice() would only be a view.

frameContextId [source]
(buffer: Uint8Array): number

The context id of a frame that has one, without route data.

getFrameContext [source]
(buffer: Uint8Array, start?: number): number

The context id of a frame, 0 when it has none.

frameMemory [source]
(): Uint8Array

The memory the frames are written to: a frame is the range 0 to the size returned by the write function. Only valid until the next frame is written.

copyWrittenFrame [source]
(size: number): Uint8Array

A copy of the frame that was just written, which stays valid after the next one is written.

releaseMessageBuffer [source]
(): void

Has to be called when something still holds on to the memory of a frame.

releaseMessageBufferIfLarge [source]
(): void
readVarint [source]
(buffer: Uint8Array, offset: number): number

The value of the varint at the offset.

varintEnd [source]
(buffer: Uint8Array, offset: number): number

The offset after the varint at the offset.

channelBodyOffset [source]
(buffer: Uint8Array, offset: number): number

The offset of the value of a TypeChannel frame, given the offset of its sub byte.

readChannelSubscription [source]
(buffer: Uint8Array, offset: number): number

The subscription of a TypeChannel frame that is a value.

writeActionFrameTransient [source]
(id: number, action: number, serialize: ValueSerializer, args: any[], context?: ContextFlag, route?: RouteFlag, routeData?: Uint8Array): number

The frames are written into the shared buffer, see frameMemory. They return the size of the frame.

writeResultFrameTransient [source]
(id: number, route: RouteFlag, serialize: ValueSerializer, value: any, routeData?: Uint8Array): number
writeChannelFrameTransient [source]
(id: number, route: RouteFlag, subscription: number, serialize: ValueSerializer, value: any, routeData?: Uint8Array): number
writeChannelAnnounceFrameTransient [source]
(id: number, route: RouteFlag, kind: ChannelSubType, routeData?: Uint8Array): number
writePushFrameTransient [source]
(channel: number, serialize: ValueSerializer, values: any[]): number

A value the server sends on the connection without the client having called anything for it, for protocols built on RPC that push many small values. There is no stream to set up and no context:

writeControlFrameTransient [source]
(id: number, route: RouteFlag, op: ControlOp, serialize?: ValueSerializer, value?: any, routeData?: Uint8Array, context?: ContextFlag): number

A control frame, with a body written by the given serializer, if any.

writeControlIdFrameTransient [source]
(id: number, route: RouteFlag, op: ControlOp, value: number, routeData?: Uint8Array): number

A control frame whose body is a subscription or token.

readErrorTuple [source]
(buffer: Uint8Array, offset: number, end: number): EncodedError

The error of a TypeError frame, at the offset of its body.

errorFromTuple [source]
(error: EncodedErrorTuple): EncodedError
writeErrorFrameTransient [source]
(id: number, route: RouteFlag, error: EncodedError, routeData?: Uint8Array): number
writeStreamErrorFrameTransient [source]
(id: number, route: RouteFlag, subscription: number, error: EncodedError, routeData?: Uint8Array): number

The error of one subscription of a stream, or of the stream when it is a subject.

writeAckFrameTransient [source]
(id: number, route: RouteFlag, routeData?: Uint8Array): number
writePreSerializedResultFrameTransient [source]
(id: number, route: RouteFlag, value: PreSerialized, tuple?: boolean, routeData?: Uint8Array): number

A result that was serialized once with preSerialize().

writePreSerializedChannelFrameTransient [source]
(id: number, route: RouteFlag, subscription: number, value: PreSerialized, tuple?: boolean, routeData?: Uint8Array): number

One value of an observable that was serialized once with preSerialize().

writeHelloFrameTransient [source]
(schemaHash: number, route?: RouteFlag, id?: number, routeData?: Uint8Array): number

The first frame of a connection:

Also how a controller of the other side or of a peer asks for its action schema, then with a route and a context.

writeHelloReplyFrameTransient [source]
(version: number, schemaHash: number, schema?: Uint8Array, route?: RouteFlag, id?: number, routeData?: Uint8Array): number

helloOffset [source]
(buffer: Uint8Array, start?: number): number

The offset of the version of a TypeSchema frame.

writeChunkFrameTransient [source]
(id: number, route: RouteFlag, seq: number, total: number, bytes: Uint8Array, start: number, end: number): number
writeChunkControlFrameTransient [source]
(id: number, route: RouteFlag, op: ChunkOp): number
preSerialize [source]
<T>(value: T, type?: ReceiveType<T>): PreSerialized

Serializes value once, to be sent as the result of an action or as a value of an observable without serializing it again, for example the same value to many connections.

rpcEncodeError [source]
(error: Error | string, depth?: number): EncodedError
rpcDecodeError [source]
(error: EncodedError): Error
createFrameSender [source]
(transport: TransportConnection, chunkWriter: TransportBinaryMessageChunkWriter, options: TransportOptions, stats: RpcTransportStats): RpcFrameSender | undefined

Sends the frames of the fast path. Transports without a binary socket get their own copy, as they may hold on to the memory.

createSubject [source]
<T>(producer: (subject: Subject<T>) => void | Promise<void>, teardown?: () => void): Subject<T>

Create a Subject with teardown function that is called when client disconnects or completes the subject.

The producer is called in the next tick, no matter if the client subscribes to the subject or not. This is fundamentally different from Observables, where the producer is only called when the Observable is subscribed to.

Teardown is also called when the producer errors or completes.

You should normally prefer using Observables (with instantObservable) over Subjects, as Subjects are not lazy and start emitting values immediately when created.

class Controller {
instantSubject [source]
<T>(producer: InstanceProducer<Subject<T>>): Subject<T>

Returns a Subject that is immediately subscribed to the given producer.

The producer can be a Promise or a function that returns a Promise.

Note that the Subject will be requested from the Promise right away.

const client = new RpcClient();
const controller = client.controller<MyController>('controller');

// normally you would do this:
const subject = await controller.subscribeChats('asd');

// but with instantSubject you can do this, allowing you to get
// a Subject in a synchronous way.
const subject = instantSubject(controller.subscribeChats('asd'));

Types

RpcFastHost [source]
interface RpcFastHost {
    getSchemaMapping(): ParsedSchemaMapping | undefined;

    getSchemaEpoch(): number;

    isActionReady(dontWaitForConnection?: boolean): boolean;

    getContexts(): SequentialContextDispatcher<FrameCallback>;

    getChunkSize(): number;

    sendActionFrame(buffer: Uint8Array, size: number, progress?: SingleProgress): void;

    /** Whether somebody listens to client.events, which is built for that only. */
    isObserved(): boolean;

    emitEvent(event: any): void;

    connectForAction(): Promise<unknown>;

    hasBinaryTransport(): boolean;

    currentConnectionId(): number;

    /** The route of what this side sends: client to server, or server to client. */
    getRoute(): RouteFlag;

    /** Controllers can be registered while connected, this asks for the actions again. */
    refreshSchema?(): Promise<unknown>;

    registerDownloadProgress?(id: number, progress: SingleProgress): void;

    /** <source:16><peerId>\0 for a frame to the given peer. */
    getPeerRoute?(peerId: string): Uint8Array;

    getHttpTransport?(): RpcHttpTransport | undefined;

    getToken?(): any;
}
RpcHttpActionTypes [source]
interface RpcHttpActionTypes {
    mode: ActionMode;
    type: any;
    parameters: any;
}
RpcHttpTransport [source]
interface RpcHttpTransport {
    requestTypes(controller: string, method: string, token: any): Promise<RpcHttpActionTypes>;

    requestCall(controller: string, method: string, args: any[], token: any): Promise<any>;
}

A transport that calls actions by name, one request per call, without a connection or streams.

RemoteController [source]
type RemoteController<T> = {
    [P in keyof T]: T[P] extends (...args: any[]) => any ? PromisifyFn<T[P]> : never;
};
ClientTransportAdapter [source]
interface ClientTransportAdapter {
    connect(connection: TransportClientConnection): Promise<void> | void;

    /**
     * Whether ClientId call is needed to get a client id.
     * This is disabled for http adapter.
     */
    supportsPeers?(): boolean;

    /**
     * Whether Authentication call is needed to authenticate the client.
     * This is disabled for http adapter (Authorization header is used).
     */
    supportsAuthentication?(): boolean;

    /** When set, actions are called through this instead of frames on a connection. */
    httpTransport?(): RpcHttpTransport;
}
RpcPushHandler [source]
type RpcPushHandler = (buffer: Uint8Array, offset: number, end: number) => void;
RpcEventMessage [source]
type RpcEventMessage = { id: number; date: Date; type: string; body: any };
RpcClientEventIncomingMessage [source]
type RpcClientEventIncomingMessage = { event: 'incoming' } & RpcEventMessage;
RpcClientEventOutgoingMessage [source]
type RpcClientEventOutgoingMessage = { event: 'outgoing' } & RpcEventMessage;
RpcClientEvent [source]
type RpcClientEvent = RpcClientEventIncomingMessage | RpcClientEventOutgoingMessage;
RpcHttpResponseInterface [source]
interface RpcHttpResponseInterface {
    status: number;
    headers: { [name: string]: string };
    body?: any;
}
RpcHttpInterface [source]
interface RpcHttpInterface {
    fetch(
        url: string,
        options: {
            headers: { [name: string]: string };
            method: string;
            body?: string;
        },
    ): Promise<RpcHttpResponseInterface>;
}
RpcChannel [source]
interface RpcChannel {
    /**
     * Sends bytes. The buffer belongs to the channel afterwards, it may transfer it to the other side.
     */
    send(data: Uint8Array): void;

    /**
     * Ends the current connection. The other side gets onEnd. A message channel can carry the next connection afterwards.
     */
    end(): void;

    /**
     * Receives bytes until the returned function is called. onEnd is called when the other side ended the
     * connection or the channel closed. The buffer is only valid during the call.
     */
    listen(onData: (data: Uint8Array, bytes?: number) => void, onEnd: (reason: string) => void): () => void;

    /**
     * Channels of a byte stream write the frames directly to this socket instead of send(), which
     * collects the frames of one tick into one message.
     */
    binarySocket?: BinarySocket;

    /** Shown as address of the client. */
    readonly name?: string;
}

A connection between two sides that are not connected over the network: a worker thread, a Web Worker, a forked child process, or any other message port or byte stream. RPC frames are sent over it, one side runs a RpcKernel with serveRpcChannel() and the other a RpcClient with RpcChannelClientAdapter.

Use createMessagePortChannel(), createProcessChannel() or createStreamChannel(), or implement it for other channels.

RpcChannelServer [source]
interface RpcChannelServer {
    /** The connection that currently runs over the channel. */
    readonly connection?: RpcKernelBaseConnection;

    /** Stops listening and closes the current connection. */
    close(): void;
}
RpcMessagePortLike [source]
interface RpcMessagePortLike {
    postMessage(message: any, transfer?: any[]): void;
    on?(event: string, listener: (...args: any[]) => void): unknown;
    off?(event: string, listener: (...args: any[]) => void): unknown;
    addEventListener?(event: string, listener: (event: any) => void): unknown;
    removeEventListener?(event: string, listener: (event: any) => void): unknown;
    start?(): void;
}

The parts of a MessagePort, Worker, or the global scope of a Web Worker (self) the channel uses. In node these are MessagePort, Worker and parentPort of worker_threads.

RpcProcessLike [source]
interface RpcProcessLike {
    send?(message: any, ...rest: any[]): boolean;
    readonly connected?: boolean;
    on(event: string, listener: (...args: any[]) => void): unknown;
    off(event: string, listener: (...args: any[]) => void): unknown;
}

The parts of a ChildProcess or of process in the child the channel uses.

RpcStreamLike [source]
interface RpcStreamLike {
    write(data: Uint8Array): unknown;
    end(): unknown;
    readonly writableLength: number;
    readonly destroyed: boolean;
    on(event: string, listener: (...args: any[]) => void): unknown;
    off(event: string, listener: (...args: any[]) => void): unknown;
}

The parts of a node Duplex stream the channel uses, like a net.Socket.

SharedMemoryChannelOptions [source]
interface SharedMemoryChannelOptions {
    /**
     * How long the receiving side polls for new data, in each turn of the event loop, before it goes to sleep, in
     * microseconds. An answer that arrives meanwhile is read right away instead of after a wake-up of the thread,
     * which takes 20-30µs. The core is busy while polling. 0 disables it. Default 100.
     */
    spin?: number;
}
ActionTypes [source]
type ActionTypes = {
    strictSerialization: boolean;
    parametersValidate: Guard<any>;

    parameters: TypeTuple;
    mode: ActionMode;
    type: Type; //the type T of Collection<T>, EntitySubject<T>, Observable<T>, or return type of the function if mode=arbitrary

    resultSchema: TypeObjectLiteral; //with v as property
    observableNextSchema?: TypeObjectLiteral; //with v as property
    collectionItems?: Type; //T[]
    collectionQueryModel?: Type;

    noTypeWarned: boolean;

    /** Writes one observable value on the fast path. */
    nextValueEncoder?: AutoBufferSerializer;
};
RpcServerActionObservableSubject [source]
interface RpcServerActionObservableSubject {
    subject: Subject<any>;
    trackingType: NumericKeys<ActionStats>;
    completed: boolean;
    completedByClient: boolean;
    subscription: Subscription;
    subscribe: () => Subscription;
}
RpcCacheAction [source]
interface RpcCacheAction {
    controller: RpcControllerAccess;
    fn: Function;
    types: ActionTypes;
    action: RpcAction;
    resolver: Resolver<any>;
    label: string; //controller.action
}
OnConnectionCallback [source]
type OnConnectionCallback = (
    connection: RpcKernelConnection,
    injector: InjectorContext,
    logger: LoggerInterface,
) => void;
RpcControllerAccess [source]
interface RpcControllerAccess {
    controllerName: string;
    controllerClassType: ClassType;
    actionName: string;
    actionGroups: string[];
    actionData: { [name: string]: any };
}
ActionEntry [source]
interface ActionEntry {
    id: number;
    controllerName: string;
    methodName: string;
    classType: ClassType;
    module?: InjectorModule;
    mode: ActionMode;
    parameters: TypeTuple;
    type: Type;

    cache?: RpcCacheAction;
    /** The returned array is reused by the next call. */
    decode?: ParameterDeserializer;
    /** Indexes of the parameters that are views on the frame, see TransientBytes. */
    transient?: number[];
    /** The decoder already guarantees the parameter types, there is nothing a validator could add. */
    validate: boolean;
    encodeResult?: AutoBufferSerializer;
    warnResultType: boolean;
}
TransientBytes [source]
type TransientBytes = Uint8Array & TypeAnnotation<'rpcTransientBytes'>;

Bytes of a parameter that are a view on the received frame instead of a copy. Only valid during the synchronous part of the action: for what is forwarded or read right away, not for what is kept.

ParameterDeserializer [source]
type ParameterDeserializer = (message: Uint8Array, offset: number, frameEnd: number) => any[];
ReturnDeserializer [source]
type ReturnDeserializer = (message: Uint8Array, offset: number, frameEnd: number) => any;
BodySerializer [source]
type BodySerializer = AutoBufferSerializer;
BodyCodec [source]
interface BodyCodec {
    serialize: BodySerializer;
    deserialize: ReturnDeserializer;
}
SchemaMapping [source]
type SchemaMapping = {
    [controllerName: string]: [actionName: string, action: number, mode: ActionMode, parameters: any, type: any][];
};

Sent to the client in the handshake. The types stay serialized until an action is used for the first time.

ParsedSchemaEntry [source]
type ParsedSchemaEntry = { action: number; mode: ActionMode; parameters: any; type: any };
ParsedSchemaMapping [source]
type ParsedSchemaMapping = { [controllerName: string]: { [actionName: string]: ParsedSchemaEntry } };
FilterParameters [source]
type FilterParameters = { [name: string]: any | undefined };
QuerySelector [source]
type QuerySelector<T> = {
    // Comparison
    $eq?: T;
    $gt?: T;
    $gte?: T;
    $in?: T[];
    $lt?: T;
    $lte?: T;
    $ne?: T;
    $nin?: T[];
    // Logical
    $not?: T extends string ? (QuerySelector<T> | RegExp) : QuerySelector<T>;
    $regex?: T extends string ? (RegExp | string) : never;

    //special deepkit/type type
    $parameter?: string;
};
RootQuerySelector [source]
type RootQuerySelector<T> = {
    $and?: Array<FilterQuery<T>>;
    $nor?: Array<FilterQuery<T>>;
    $or?: Array<FilterQuery<T>>;
    // we could not find a proper TypeScript generic to support nested queries e.g. 'user.friends.name'
    // this will mark all unrecognized properties as any (including nested queries)
    [key: string]: any;
};
Condition [source]
type Condition<T> = MongoAltQuery<T> | QuerySelector<MongoAltQuery<T>>;
FilterQuery [source]
type FilterQuery<T> = {
    [P in keyof T & string]?: Condition<T[P]>;
} &
    RootQuerySelector<T>;
SORT_ORDER [source]
type SORT_ORDER = 'asc' | 'desc' | any;
Sort [source]
type Sort<T, ORDER extends SORT_ORDER = SORT_ORDER> = { [P in keyof T & string]?: ORDER };
CollectionEventAdd [source]
interface CollectionEventAdd<T> {
    type: 'add';
    items: T[];
}
CollectionEventState [source]
interface CollectionEventState {
    type: 'state';
    state: CollectionState;
}
CollectionEventRemove [source]
interface CollectionEventRemove {
    type: 'remove';
    ids: (string | number)[];
}
CollectionEventSet [source]
interface CollectionEventSet {
    type: 'set';
    items: any[];
}
CollectionEventUpdate [source]
interface CollectionEventUpdate {
    type: 'update';
    items: any[];
}
CollectionSetSort [source]
interface CollectionSetSort {
    type: 'sort';
    ids: (string | number)[];
}
CollectionEvent [source]
type CollectionEvent<T> = CollectionEventAdd<T> | CollectionEventRemove | CollectionEventSet | CollectionEventState | CollectionEventUpdate | CollectionSetSort;
CollectionSortDirection [source]
type CollectionSortDirection = 'asc' | 'desc';
CollectionSort [source]
interface CollectionSort {
    field: string;
    direction: CollectionSortDirection;
}
CollectionEntitySubjectFetcher [source]
interface CollectionEntitySubjectFetcher {
    fetch<T extends IdInterface>(classType: ClassType<T>, id: string | number): EntitySubject<T>;
}
CollectionQueryModelInterface [source]
interface CollectionQueryModelInterface<T> {
    filter?: FilterQuery<T>;
    skip?: number;
    itemsPerPage: number;
    limit?: number;
    parameters: { [name: string]: any };
    sort?: Sort<T>;
}
IdType [source]
type IdType = string | number;
IdInterface [source]
interface IdInterface {
    id: IdType;
}
IdVersionInterface [source]
interface IdVersionInterface extends IdInterface {
    version: number;
}
NumericKeys [source]
type NumericKeys<T> = {
    [K in keyof T]: T[K] extends number ? K : never;
}[keyof T];
ActionMode [source]
type ActionMode = 'arbitrary' | 'collection' | 'entitySubject' | 'observable';
rpcCollectionRemove [source]
interface rpcCollectionRemove {
    ids: (string | number)[];
}
rpcCollectionSort [source]
interface rpcCollectionSort {
    ids: (string | number)[];
}
rpcEntityRemove [source]
interface rpcEntityRemove {
    entityName: string;
    ids: (string | number)[];
}
EntityPatch [source]
interface EntityPatch {
    $set?: { [path: string]: any };
    $unset?: { [path: string]: number };
    $inc?: { [path: string]: number };
}
rpcEntityPatch [source]
interface rpcEntityPatch {
    entityName: string;
    id: string | number;
    version: number;
    patch: {
        $set?: Record<string, any>;
        $unset?: Record<string, number>;
        $inc?: Record<string, number>;
    };
}
RouteFlag [source]
type RouteFlag =
    | MessageFlag.RouteClient
    | MessageFlag.RouteServer
    | MessageFlag.RouteSourceDest
    | MessageFlag.RoutePeer;
ContextFlag [source]
type ContextFlag =
    | MessageFlag.ContextNone
    | MessageFlag.ContextNew
    | MessageFlag.ContextExisting
    | MessageFlag.ContextEnd;
TypeFlag [source]
type TypeFlag =
    | MessageFlag.TypeAction
    | MessageFlag.TypeAck
    | MessageFlag.TypeChunk
    | MessageFlag.TypeError
    | MessageFlag.TypeSchema
    | MessageFlag.TypeResult
    | MessageFlag.TypeControl
    | MessageFlag.TypeChannel;
EncodedErrorTuple [source]
type EncodedErrorTuple = [
    classType: string,
    properties: { [name: string]: any },
    stack: string,
    message: string,
    /** The tuple of error.cause, only when rpcErrorSettings.exposeCause is set. Older peers ignore it. */
    cause?: any,
];
EncodedError [source]
interface EncodedError {
    classType: string;
    message: string;
    stack: string;
    properties?: { [name: string]: any };
    cause?: EncodedError;
}
TransportConnection [source]
interface TransportConnection {
    /**
     * Sends a frame. Large frames are chunked before they get here.
     */
    writeBinary?(message: Uint8Array): void;

    /**
     * A socket to write to instead of writeBinary. Its bytes are copied by the kernel during write(), so
     * messages can be sent from one reused buffer without copying them first.
     */
    binarySocket?: BinarySocket;

    bufferedAmount?(): number;

    clientAddress?(): string;

    close(): void;
}
TransportClientConnection [source]
interface TransportClientConnection {
    token?: any;

    onConnected(established: TransportConnection): void;

    onClose(reason: string): void;

    onError(error: Error): void;

    readBinary(message: Uint8Array, bytes?: number): void;
}
RpcBinaryWriter [source]
type RpcBinaryWriter = (buffer: Uint8Array) => void;
BinarySocket [source]
interface BinarySocket {
    write(buffer: Uint8Array): unknown;

    /** Writes a range of the buffer without a view on it, where the socket supports that. */
    writeRange?(buffer: Uint8Array, start: number, end: number): unknown;

    /** Bytes the socket could not hand to the kernel yet, and whose memory it still needs. */
    readonly writableLength: number;
}
RpcFrameSender [source]
type RpcFrameSender = (buffer: Uint8Array, size: number, progress?: SingleProgress) => void;

Sends the frame in the range 0 to size of the buffer, which may be the shared message buffer: it is written and given up during the call.

InstanceProducer [source]
type InstanceProducer<T> = T | Promise<T> | (() => T) | (() => Promise<T>);
WithFail [source]
type WithFail<T> = Omit<T, 'phase'> & { phase: 'fail'; error: Error };
RpcConnectionEvent [source]
interface RpcConnectionEvent {
    context: {
        connection: RpcKernelBaseConnection;
        injector: InjectorContext;
    };
}
RpcConnectionCloseEvent [source]
interface RpcConnectionCloseEvent extends RpcConnectionEvent {
    /**
     * There could be multiple reasons why a connection is closed. This could be a normal
     * close, an error, or a timeout.
     * If the connection was closed because of an error, this property contains the error object.
     */
    reason: string | Error;
}
RpcActionTimings [source]
interface RpcActionTimings {
    /**
     * The start of the action (performance.now())
     */
    start: number;

    /**
     * The end of the action (performance.now())
     */
    end: number;

    /**
     * Time it took to check the controller access (since start)
     */
    types?: number;

    /**
     * Time it took to parse the body (since start)
     */
    parseBody?: number;

    /**
     * Time it took to validate the parameters (since start)
     */
    validate?: number;

    /**
     * Time it took to check the controller access (since start)
     */
    controllerAccess?: number;
}

All times are in milliseconds (using performance.now()).

RpcActionEventBase [source]
interface RpcActionEventBase extends RpcConnectionEvent {
    phase: 'start' | 'success';
    controller: RpcControllerAccess;
    timing: RpcActionTimings;
}
RpcActionEvent [source]
type RpcActionEvent = RpcActionEventBase | WithFail<RpcActionEventBase>;
RpcAuthEventStart [source]
interface RpcAuthEventStart extends RpcConnectionEvent {
    token: any;
    phase: 'start';
    /**
     * Set this to the session object if the authentication was successful.
     * If set this will bypass RpcKernelSecurity and directly use this session.
     */
    session?: Session;
}
RpcAuthEventSuccess [source]
interface RpcAuthEventSuccess extends RpcConnectionEvent {
    token: any;
    phase: 'success';
    session: Session;
}
RpcAuthEvent [source]
type RpcAuthEvent = RpcAuthEventStart | RpcAuthEventSuccess | WithFail<RpcAuthEventStart>;
RpcControllerAccessEventStart [source]
interface RpcControllerAccessEventStart extends RpcConnectionEvent {
    phase: 'start';
    session: Session;
    controller: RpcControllerAccess;
    /**
     * Set this to true if you want to grant access to the controller.
     * If set this will bypass RpcKernelSecurity and directly grant access.
     */
    granted?: boolean;
}
RpcControllerAccessEventBase [source]
interface RpcControllerAccessEventBase extends RpcConnectionEvent {
    phase: 'success' | 'denied';
    session: Session;
    controller: RpcControllerAccess;
}
RpcControllerAccessEvent [source]
type RpcControllerAccessEvent = RpcControllerAccessEventStart | RpcControllerAccessEventBase | WithFail<RpcControllerAccessEventBase>;

English中文 (Chinese)한국어 (Korean)日本語 (Japanese)Deutsch (German)