npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

eventbus-js-fast

v2.0.1

Published

A powerful and flexible event bus system with middleware support, validation, scheduling, and scoped namespaces

Readme

EventBus

A powerful and flexible event bus system built with TypeScript, featuring middleware support, event validation, scheduling, and scoped namespaces.

Features

  • 🚀 Event Subscription & Emission - Simple pub/sub pattern
  • 🔧 Middleware Support - Process events before/after emission
  • Event Validation - Validate event data before processing
  • Event Scheduling - Schedule events for future emission
  • 🔄 Recurring Events - Set up interval-based event emission
  • 🏷️ Scoped Namespaces - Organize events with namespaces
  • 📊 Statistics & History - Track event usage and history
  • 🐛 Debug Logging - Comprehensive logging for development
  • 🎯 TypeScript Support - Full type safety and IntelliSense

Installation

npm i eventbus-js-fast

Quick Start

import EventBus from 'eventbus-js-fast';

// Subscribe to events
EventBus.$on('user:login', (user) => {
  console.log('User logged in:', user);
});

// Emit events
EventBus.$emit('user:login', { id: 1, name: 'John' });

// Use middleware
EventBus.$before('user:login', (data) => {
  console.log('Before login:', data);
  return data;
});

// Validate events
EventBus.$validate('user:login', (data) => {
  return data && typeof data.id === 'number';
});

Architecture

The EventBus is built with a clean, professional architecture:

src/
├── types.ts          # Type definitions and interfaces
├── constants.ts      # Configuration constants and enums
├── utils.ts          # Utility functions and helpers
├── EventBus.ts       # Main EventBus class implementation
├── factory.ts        # Factory functions and instances
└── index.ts          # Main entry point and exports

Core Components

  • types.ts - Contains all TypeScript interfaces and type definitions
  • constants.ts - Configuration values, event types, and logging constants
  • utils.ts - Helper functions for common operations
  • EventBus.ts - Main class implementing the event bus functionality
  • factory.ts - Factory functions for creating instances
  • index.ts - Main entry point with all exports

API Reference

Core Methods

$on<T>(event: string, callback: EventCallback<T>)

Subscribe to an event.

EventBus.$on('user:created', (user: User) => {
  console.log('New user:', user);
});

$off<T>(event: string, callback: EventCallback<T>)

Unsubscribe from an event.

EventBus.$off('user:created', callback);

$emit<T>(event: string, data: T): Promise<void>

Emit an event to all registered listeners.

await EventBus.$emit('user:created', { id: 1, name: 'John' });

$once<T>(event: string, callback: EventCallback<T>)

Subscribe to an event once (automatically unsubscribes after first emission).

EventBus.$once('user:deleted', (user) => {
  console.log('User deleted:', user);
});

Advanced Features

Middleware

// Run before event emission
EventBus.$before('user:login', (data) => {
  data.timestamp = Date.now();
  return data;
});

// Run after event emission
EventBus.$after('user:login', (data) => {
  console.log('User logged in at:', data.timestamp);
  return data;
});

Event Validation

EventBus.$validate('user:login', (data) => {
  return data.email && data.password;
});

Scheduled Events

// Schedule event for future emission
const id = EventBus.$schedule('reminder', { message: 'Meeting in 5 minutes' }, Date.now() + 300000);

// Cancel scheduled event
EventBus.$cancelScheduled(id);

Recurring Events

// Emit event every 5 seconds
const id = EventBus.$interval('heartbeat', { status: 'alive' }, 5000);

// Cancel recurring event
EventBus.$cancelScheduled(id);

Scoped Events

const userEvents = EventBus.$scope('user');
const systemEvents = EventBus.$scope('system');

userEvents.$on('profile:update', callback);
systemEvents.$on('maintenance:start', callback);

Utility Methods

$stats(): EventStats

Get statistics about event usage.

const stats = EventBus.$stats();
console.log(`Total events: ${stats.totalEvents}`);
console.log(`Total listeners: ${stats.totalListeners}`);

$history(event?: string, limit?: number): EventHistoryRecord[]

Get event history.

const history = EventBus.$history('user:login', 10);

$debug(enabled: boolean): void

Enable or disable debug logging.

EventBus.$debug(true);

$clear(): void

Clear all events, middleware, and scheduled events.

EventBus.$clear();

Creating Multiple Instances

You can create multiple EventBus instances for different contexts:

import { createEventBus, EventBus } from 'eventbus-js-fast';

// Create a new instance
const userEventBus = createEventBus({ debug: true });

// Or use the class directly
const systemEventBus = new EventBus({ maxHistorySize: 500 });

Configuration

import { createEventBus } from 'eventbus-js-fast';

const eventBus = createEventBus({
  debug: true,           // Enable debug logging
  maxHistorySize: 2000   // Increase history size
});

Error Handling

The EventBus includes built-in error handling:

// Middleware errors are caught and logged
EventBus.$before('user:action', (data) => {
  throw new Error('Something went wrong');
  // Error is caught and logged, event continues
});

// Validation errors prevent event emission
EventBus.$validate('user:action', (data) => {
  if (!data.userId) {
    return false; // Event won't be emitted
  }
  return true;
});

Performance Considerations

  • Events are processed synchronously by default
  • Middleware and validation run in sequence
  • History is automatically trimmed to prevent memory leaks
  • Scheduled events are cleaned up automatically

Testing

npm test

The test suite covers all major functionality including edge cases and integration scenarios.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Submit a pull request

License

MIT License - see LICENSE file for details.

Changelog

v2.0.1

  • Build target downleveled to ES2018 to avoid nullish coalescing in dist
  • Updated README install/imports to eventbus-js-fast

v2.0.0

  • Complete code restructuring for better maintainability
  • Separated concerns into multiple files
  • Added proper TypeScript interfaces
  • Improved error handling and validation
  • Enhanced documentation and examples

v1.0.0

  • Initial release with basic event bus functionality