DocumentationCore Protocol

Plugin System

Extend PaindaProtocol with custom plugins. Plugins get full access to lifecycle hooks and can expose public APIs for other plugins.

Creating a Plugin

import type { PPPlugin } from "@painda/core";

const myPlugin: PPPlugin<{ debug: boolean }> = {
  name: "my-plugin",
  version: "1.0.0",
  dependencies: [],    // Other plugins required
  install(ctx, options) {
    // Register middleware
    ctx.use((socket, next) => {
      if (options?.debug) ctx.log("New connection:", socket.id);
      next();
    });

    // Expose API for other plugins
    ctx.expose({
      getStats: () => ({ clients: ctx.getClientCount() }),
    });

    // Return lifecycle hooks
    return {
      onConnect: (socket) => { /* ... */ },
      onDisconnect: (socket) => { /* ... */ },
      onMessage: (socket, msg) => {
        // Return false to block the message
        if (msg.type === "banned") return false;
      },
      onSend: (socket, msg) => {
        // Transform outgoing messages
        return { ...msg, payload: { ...msg.payload, ts: Date.now() } };
      },
      onShutdown: () => { /* cleanup */ },
    };
  },
};

server.register(myPlugin, { debug: true });

Lifecycle Hooks

HookWhen
onConnectAfter middleware, before handlers
onDisconnectClient disconnected
onMessageEvery incoming message (return false to block)
onSendBefore encoding outgoing message
onRoomJoin / onRoomLeaveRoom membership changes
onShutdownServer is shutting down
onErrorServer errors

Next: Typed Rooms