Core API
defineEvent
Section titled “defineEvent”Creates a type-safe event registry from event definitions.
function defineEvent<T extends EventDefinitionInput[]>( definitions: T): EventRegistry<T>Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
definitions | EventDefinitionInput[] | Array of event definitions |
Event Definition
Section titled “Event Definition”interface EventDefinitionInput { name: string; schema: StandardSchema; options?: EventOptions;}
interface EventOptions { channel?: string; description?: string;}Example
Section titled “Example”import { defineEvent } from "@pubsubjs/core";import { z } from "zod";
const events = defineEvent([ { name: "user.created", schema: z.object({ userId: z.string(), email: z.string().email(), }), options: { channel: "users", description: "Emitted when a new user is created", }, },]);Publisher
Section titled “Publisher”Class for publishing type-safe events.
class Publisher<TEvents extends EventRegistry>Constructor
Section titled “Constructor”new Publisher(options: PublisherOptions<TEvents>)Options
Section titled “Options”| Option | Type | Required | Description |
|---|---|---|---|
events | TEvents | Yes | Event registry |
transport | Transport | Yes | Transport to use |
middleware | PublishMiddleware[] | No | Middleware chain |
channelStrategy | (name: string) => string | No | Channel naming strategy |
skipValidation | boolean | No | Skip payload validation |
autoReconnect | boolean | No | Enable auto-reconnection |
reconnectInterval | number | No | Reconnection interval (ms) |
maxReconnectAttempts | number | No | Max reconnection attempts |
Methods
Section titled “Methods”publish
Section titled “publish”async publish<TEventName extends EventNames<TEvents>>( eventName: TEventName, payload: EventPayload<TEvents, TEventName>, options?: PublishOptions): Promise<void>connect
Section titled “connect”async connect(): Promise<void>disconnect
Section titled “disconnect”async disconnect(): Promise<void>Properties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
state | ConnectionState | Current connection state |
isConnected | boolean | Whether connected |
Subscriber
Section titled “Subscriber”Class for subscribing to events.
class Subscriber< TEvents extends EventRegistry, TContext extends BaseContext = BaseContext, TPublisher extends PublisherInterface | undefined = undefined>Constructor
Section titled “Constructor”new Subscriber(options: SubscriberOptions<TEvents, TContext, TPublisher>)Options
Section titled “Options”| Option | Type | Required | Description |
|---|---|---|---|
events | TEvents | Yes | Event registry |
transport | Transport | Yes | Transport to use |
middleware | SubscribeMiddleware[] | No | Middleware chain |
contextFactory | ContextFactory<TContext> | No | Custom context factory |
publisher | TPublisher | No | Publisher for reply patterns |
onError | SubscriberErrorHandler | No | Error handler |
channelStrategy | (name: string) => string | No | Channel naming strategy |
skipValidation | boolean | No | Skip payload validation |
Methods
Section titled “Methods”on<TEventName extends EventNames<TEvents>>( eventName: TEventName, handler: EventHandler<EventPayload<TEvents, TEventName>, TContext, TPublisher>): thisoff<TEventName extends EventNames<TEvents>>(eventName: TEventName): thisonMany
Section titled “onMany”onMany(handlers: HandlerMap<TEvents, TContext, TPublisher>): thissubscribe
Section titled “subscribe”async subscribe(): Promise<void>unsubscribe
Section titled “unsubscribe”async unsubscribe(): Promise<void>Properties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
state | ConnectionState | Current connection state |
isConnected | boolean | Whether connected |
Middleware Factories
Section titled “Middleware Factories”createLoggingMiddleware
Section titled “createLoggingMiddleware”Publisher middleware that logs events.
function createLoggingMiddleware<TEvents>(): PublishMiddleware<TEvents>createSubscriberLoggingMiddleware
Section titled “createSubscriberLoggingMiddleware”Subscriber middleware that logs events.
function createSubscriberLoggingMiddleware<TEvents, TContext>(): SubscribeMiddleware<TEvents, TContext>createSubscriberTimingMiddleware
Section titled “createSubscriberTimingMiddleware”Reports handler duration.
function createSubscriberTimingMiddleware<TEvents, TContext>( onTiming: (eventName: string, durationMs: number) => void): SubscribeMiddleware<TEvents, TContext>createIdempotencyMiddleware
Section titled “createIdempotencyMiddleware”Prevents duplicate message processing.
function createIdempotencyMiddleware<TEvents, TContext>( options: IdempotencyOptions): SubscribeMiddleware<TEvents, TContext>
interface IdempotencyOptions { hasProcessed: (messageId: string) => boolean | Promise<boolean>; markProcessed: (messageId: string) => void | Promise<void>;}createRateLimitMiddleware
Section titled “createRateLimitMiddleware”Limits event processing rate.
function createRateLimitMiddleware<TEvents, TContext>( options: RateLimitOptions): SubscribeMiddleware<TEvents, TContext>
interface RateLimitOptions { maxEvents: number; windowMs: number; onLimit?: (eventName: string, payload: unknown) => void;}EventNames
Section titled “EventNames”Extracts event names as union type.
type EventNames<T extends EventRegistry> = keyof T & stringEventPayload
Section titled “EventPayload”Extracts payload type for an event.
type EventPayload<T extends EventRegistry, K extends EventNames<T>> = InferOutput<T[K]["schema"]>ConnectionState
Section titled “ConnectionState”type ConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting"PublishMiddleware
Section titled “PublishMiddleware”type PublishMiddleware<TEvents extends EventRegistry> = ( eventName: EventNames<TEvents>, payload: unknown, options: PublishOptions | undefined, next: () => Promise<void>) => Promise<void>SubscribeMiddleware
Section titled “SubscribeMiddleware”type SubscribeMiddleware< TEvents extends EventRegistry, TContext extends BaseContext = BaseContext> = ( eventName: EventNames<TEvents>, payload: unknown, context: TContext, next: () => Promise<void>) => Promise<void>BaseContext
Section titled “BaseContext”interface BaseContext { messageId: string; timestamp: Date;}Errors
Section titled “Errors”ValidationError
Section titled “ValidationError”Thrown when payload validation fails.
class ValidationError extends Error { issues: StandardSchemaIssue[];}UnknownEventError
Section titled “UnknownEventError”Thrown when event is not defined.
class UnknownEventError extends Error { eventName: string;}ConnectionError
Section titled “ConnectionError”Thrown when connection fails.
class ConnectionError extends Error {}