@trutoo/event-bus
Version:
Typesafe cross-platform pubsub event bus ensuring reliable communication between fragments and micro frontends.
143 lines (142 loc) • 6.08 kB
TypeScript
export type Schema = Record<string, unknown>;
export type Payload = any;
export type ChannelEvent<T> = {
channel: string;
payload: T | undefined;
};
export type Callback<T> = (event: ChannelEvent<T>) => void;
export type Subscription = {
unsubscribe(): void;
};
export type LogLevel = 'none' | 'error' | 'warn' | 'info';
export interface EventBusOptions {
/**
* The logging level for the event bus
* - 'none': No logging
* - 'error': Only log errors
* - 'warn': Log warnings and errors
* - 'info': Log everything (default)
*/
logLevel?: LogLevel;
}
export declare class PayloadMismatchError extends Error {
channel: string;
schema: Schema;
payload: Payload;
/**
* Creates a new PayloadMismatchError error
* @param channel - name of event channel
* @param schema - registered schema on event channel
* @param payload - payload detail sent
*/
constructor(channel: string, schema: Schema, payload: Payload);
}
export declare class SchemaMismatchError extends Error {
channel: string;
schema: Schema;
newSchema: Schema;
/**
* Creates a new SchemaMismatchError error
* @param channel - name of event channel
* @param schema - registered schema on event channel
* @param newSchema - new schema attempting to be registered on event channel
*/
constructor(channel: string, schema: Schema, newSchema: Schema);
}
export declare class EventBus {
private _lastId;
private _subscriptions;
private readonly _options;
private readonly _validator;
constructor(options?: EventBusOptions);
/**
* Generates and returns the next available sequential identifier.
* Increments the internal counter after returning the current value.
* @returns The next sequential identifier
*/
private _getNextId;
/**
* Logs messages for debugging and monitoring.
* @param message - The message to log.
* @param level - The log level (info, warn, error).
*/
private _log;
/**
* Safely executes a callback asynchronously with error handling.
* @param callback - The callback to execute.
* @param event - The event to pass to the callback.
*/
private _asyncCallback;
/**
* Gets an existing channel subscription or creates a new one if it doesn't exist.
* @param channel - The channel identifier to get or create a subscription for
* @returns The channel subscription object containing registered callbacks
*/
private _getOrCreateChannel;
/**
* Register a schema for the specified channel and equality checking on subsequent registers.
* Subsequent registers must use an equal schema or an error will be thrown.
* @param channel - name of event channel to register schema to
* @param schema - all communication on channel must follow this schema
* @returns returns true if event channel already existed of false if a new one was created
*
* @throws {SchemaMismatchError}
* This exception is thrown if new schema does not match already registered schema.
*/
register(channel: string, schema: Schema): boolean;
/**
* Unregister the schema for the specified channel if channel exists.
* @param channel - name of event channel to unregister schema from
* @returns returns true if event channel existed and an existing schema was removed
*/
unregister(channel: string): boolean;
/**
* Subscribe to an event channel triggering callback on received event matching type.
* @param channel - name of event channel to receive data from
* @param callback - function executed on when event channel receives new data
* @returns object containing an unsubscribe method and initial subscription promise
*/
subscribe<T>(channel: string, callback: Callback<T>): Promise<Subscription>;
/**
* Subscribe to an event channel triggering callback on received event matching type,
* with an optional replay of last event at initial subscription.
* @param channel - name of event channel to receive data from
* @param replay - flag indicating if initial description should return last event
* @param callback - function executed on when event channel receives new data
* @returns object containing an unsubscribe method and initial subscription promise
*/
subscribe<T>(channel: string, replay: boolean, callback: Callback<T>): Promise<Subscription>;
/**
* Helper method to publish an event to a specific channel.
* @param channel - The channel to publish to.
* @param payload - The payload to send.
*/
private _publishToChannel;
/**
* Publishes a payload to the specified channel and triggers all subscription callbacks.
* If a schema is registered for the channel, the payload will be validated against it.
* @param channel - The name of the event channel to send the payload on.
* @param payload - The payload to be sent.
* @returns Promise that resolves when all callbacks have completed
* @throws {PayloadMismatchError} If the payload does not match the registered schema.
*/
publish<T>(channel: string, payload?: T): Promise<void>;
/**
* Get the latest published payload on the specified event channel.
* @param channel - name of the event channel to fetch the latest payload from
* @returns the latest payload or `undefined`
*/
getLatest<T>(channel: string): T | undefined;
/**
* Get the schema registered on the specified event channel.
* @param channel - name of the event channel to fetch the schema from
* @returns the schema or `undefined`
*/
getSchema(channel: string): Schema | undefined;
/**
* Clears the replay event for the specified channel.
* @param channel - The name of the event channel to clear the replay event from.
* @returns Returns true if the replay event was cleared, false otherwise.
*/
clearReplay(channel: string): boolean;
}