API Reference
Complete API documentation for Nexus Orchestrator.
Class: Nexus<E extends EventMap>
Main event orchestrator class.
Constructor
new Nexus(options?: NexusOptions)Parameters:
options- Configuration object (optional)
Example:
const bus = new Nexus({
replayMemory: 50,
crossTabName: 'my-app',
debug: true,
predictionThreshold: 0.7,
teleport: (event, payload) => ws.send(JSON.stringify({ event, payload })),
chaos: { dropRate: 0.1, maxDelay: 2000 }
});Methods
emit()
Dispatch an event to all subscribed listeners.
emit<K extends keyof E>(
event: K,
payload: E[K],
options?: EmitOptions | boolean
): voidParameters:
event- Event namepayload- Event dataoptions- Execution options (optional)priority:'critical' | 'high' | 'normal' | 'background'(default:'normal')fromRemote:boolean- Internal flag for teleportation
Example:
bus.emit('user:login', { username: 'alice', timestamp: Date.now() });
bus.emit('ui:update', data, { priority: 'critical' });on()
Subscribe to an event.
on<K extends keyof E>(
event: K | string,
fn: Listener<E[K]>,
options?: SubscribeOptions | boolean
): SubscriptionParameters:
event- Event name or wildcard pattern ('user:*')fn- Listener functionoptions- Subscription options (optional)replay:boolean- Replay historical eventsattempts:number- Retry countbackoff:number- Delay between retries (ms)fallback:(error: any) => void- Called after all retries fail
Returns: Subscription object with unsubscribe() method
Example:
const sub = bus.on('user:*', (data) => {
console.log('User event:', data);
}, {
replay: true,
attempts: 3,
backoff: 1000
});
// Later: unsubscribe
sub.unsubscribe();once()
Subscribe to an event for a single execution.
once<K extends keyof E>(
event: K | string,
fn: Listener<E[K]>
): () => voidReturns: Unsubscribe function
Example:
const unsubscribe = bus.once('app:ready', () => {
console.log('App initialized');
});request()
Request/Reply pattern (RPC).
request<R = any, K extends keyof E = any>(
event: K,
payload: E[K],
timeout?: number
): Promise<R>Parameters:
event- Request event namepayload- Request datatimeout- Timeout in milliseconds (default: 5000)
Returns: Promise resolving with reply data
Example:
try {
const user = await bus.request('user:fetch', { id: 123 }, 3000);
console.log(user);
} catch (err) {
console.error('Request timeout:', err);
}reply()
Reply to a request event.
reply(originalPayload: any, responseData: any): voidParameters:
originalPayload- Original request payload (contains_replyTofield)responseData- Reply data
Example:
bus.on('user:fetch', (payload) => {
const user = database.getUser(payload.id);
bus.reply(payload, user);
});cursor()
Create a data cursor for synchronous state access.
cursor<K extends keyof E>(
event: K,
initialValue: E[K]
): DataCursor<E[K]>Parameters:
event- Event nameinitialValue- Default value
Returns: DataCursor object with value getter
Example:
const authCursor = bus.cursor('auth:state', { loggedIn: false });
console.log(authCursor.value); // { loggedIn: false }
bus.emit('auth:state', { loggedIn: true, user: 'Alice' });
console.log(authCursor.value); // { loggedIn: true, user: 'Alice' }pipe()
Create a middleware pipeline.
pipe<T = any>(
event: string,
...args: [...Operator[], Listener<T>]
): SubscriptionParameters:
event- Event name...args- Operators followed by final handler
Returns: Subscription object
Example:
import { filter, map, debounce } from '@caeligo/nexus-orchestrator';
bus.pipe(
'search:input',
debounce(300),
filter(data => data.query.length > 2),
map(data => ({ ...data, normalized: data.query.toLowerCase() })),
(data) => {
performSearch(data.normalized);
}
);feed()
Inject an event from an external source (e.g., WebSocket).
feed(event: string, payload: any): voidParameters:
event- Event namepayload- Event data
Example:
websocket.onmessage = (msg) => {
const { event, payload } = JSON.parse(msg.data);
bus.feed(event, payload);
};scenario()
Fluent API for defining event workflows.
scenario(): ScenarioBuilderReturns: Scenario builder with when() method
Example:
bus.scenario()
.when('user:login')
.thenEmit('analytics:track', data => ({ event: 'login', user: data.username }))
.when('analytics:track')
.thenEmit('log:info', data => ({ message: `Event: ${data.event}` }));generateGraph()
Generate a Mermaid.js diagram of the event architecture.
generateGraph(): stringReturns: Mermaid diagram string
Example:
const diagram = bus.generateGraph();
console.log(diagram);
// Output:
// graph TD
// user_login -->|Triggers| analytics_track
// analytics_track --> ListenerbindDOM()
Bind DOM events to the event bus with auto-cleanup.
bindDOM(
target: HTMLElement | Window,
event: string,
fn: (e: Event) => void,
options?: AddEventListenerOptions
): SubscriptionParameters:
target- DOM element or Windowevent- DOM event namefn- Event handleroptions- addEventListener options (optional)
Returns: Subscription object
Example:
const sub = bus.bindDOM(window, 'resize', (e) => {
bus.emit('window:resize', { width: window.innerWidth, height: window.innerHeight });
});
// Cleanup on component unmount
sub.unsubscribe();Types
NexusOptions
Configuration options for Nexus instance.
interface NexusOptions {
replayMemory?: number;
crossTabName?: string;
debug?: boolean;
teleport?: (event: string, payload: any) => void;
predictionThreshold?: number;
chaos?: ChaosConfig;
}SubscribeOptions
Options for event subscription.
interface SubscribeOptions {
replay?: boolean;
attempts?: number;
backoff?: number;
fallback?: (error: any) => void;
}EmitOptions
Options for event emission.
interface EmitOptions {
priority?: Priority;
fromRemote?: boolean;
}Priority
Execution priority levels.
type Priority = 'critical' | 'high' | 'normal' | 'background';ChaosConfig
Configuration for Chaos Monkey testing.
interface ChaosConfig {
dropRate?: number; // 0.0 to 1.0
maxDelay?: number; // Milliseconds
exclude?: string[]; // Event patterns to exclude
}Listener<T>
Event listener function type.
type Listener<T = any> = (payload: T) => void | Promise<void>;Subscription
Subscription object returned by on().
interface Subscription {
unsubscribe: () => void;
}DataCursor<T>
Reactive cursor for state access.
interface DataCursor<T> {
readonly value: T;
}Operator<T>
Middleware operator type for pipes.
type Operator<T = any> = (data: T, next: (data: T) => void) => void;Operators
Built-in operators for data transformation.
filter()
Conditionally pass data to next operator.
function filter<T>(predicate: (data: T) => boolean): Operator<T>Example:
import { filter } from '@caeligo/nexus-orchestrator';
bus.pipe(
'event',
filter(data => data.value > 10),
handler
);map()
Transform data before passing to next operator.
function map<T, R>(transform: (data: T) => R): Operator<any>Example:
import { map } from '@caeligo/nexus-orchestrator';
bus.pipe(
'event',
map(data => ({ ...data, doubled: data.value * 2 })),
handler
);debounce()
Delay execution until quiet period.
function debounce<T>(wait: number): Operator<T>Example:
import { debounce } from '@caeligo/nexus-orchestrator';
bus.pipe(
'search:input',
debounce(300), // Wait 300ms after last input
handler
);logger()
Log data passing through the pipe.
function logger<T>(tag: string): Operator<T>Example:
import { logger } from '@caeligo/nexus-orchestrator';
bus.pipe(
'event',
logger('debug'),
handler
);
// Console: [Pipe:debug] { data }TypeScript Usage
Type-Safe Events
interface MyEvents {
'user:login': { username: string; timestamp: number };
'user:logout': { userId: string };
'cart:add': { productId: number; quantity: number };
}
const bus = new Nexus<MyEvents>();
// TypeScript ensures type safety
bus.emit('user:login', {
username: 'alice',
timestamp: Date.now()
});
bus.on('user:login', (data) => {
// data is typed as { username: string; timestamp: number }
console.log(data.username);
});Generic Request/Reply
interface User {
id: number;
name: string;
}
const user = await bus.request<User>('user:fetch', { id: 123 });
console.log(user.name); // Type-safe accessEnvironment Variables
Configure Nexus behavior via environment variables:
# Enable Chaos Monkey
CHAOS_ENABLED=true
CHAOS_DROP_RATE=0.1
CHAOS_MAX_DELAY=2000
# Enable Debug Mode
DEBUG=true
# Prediction
PREDICTION_THRESHOLD=0.75Usage in code:
const bus = new Nexus({
debug: process.env.DEBUG === 'true',
predictionThreshold: parseFloat(process.env.PREDICTION_THRESHOLD || '0'),
chaos: process.env.CHAOS_ENABLED === 'true' ? {
dropRate: parseFloat(process.env.CHAOS_DROP_RATE || '0.1'),
maxDelay: parseInt(process.env.CHAOS_MAX_DELAY || '1000')
} : undefined
});