npm package: @microstack-dev/ms-events
Description: Ultra type-safe, zero-dependency event emitter for TS
Author: OpenCode AI
Latest version: 1.0.0

# ms-events

[![npm version](https://badge.fury.io/js/ms-events.svg)](https://badge.fury.io/js/ms-events)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
[![Node.js](https://img.shields.io/badge/Node.js-14+-green.svg)](https://nodejs.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Bundle Size](https://img.shields.io/bundlephobia/min/ms-events)](https://bundlephobia.com/result?p=ms-events)

Ultra type-safe, zero-dependency event emitter for TypeScript. Supports CJS, ESM, browser, Bun, Deno, and Node.js. A production-ready alternative to Node.js EventEmitter with advanced features.

## ✨ Features

- **🔒 Type-Safe**: Full TypeScript inference for event handlers
- **📦 Zero Dependencies**: Pure TypeScript, no runtime dependencies
- **⚡ High Performance**: Optimized for speed with fast paths and pooling
- **🔄 Async Support**: `emitAsync`, `emitAsyncSerial`, `emitAsyncParallel`
- **🌟 Wildcards**: Subscribe to all events with `*`
- **🏷️ Namespaces**: Scoped emitters with `scope()` and prefix matching
- **⏱️ Rate Limiting**: Built-in throttling and debouncing
- **📼 Buffering**: Replay events when listeners are added
- **🛑 AbortSignal**: Auto-cleanup with AbortController
- **🔑 Symbols**: Private symbol-based events
- **🐛 Debugging**: Comprehensive logging and tracing
- **🧵 Microtask/Tick**: `emitNextTick`, `emitMicrotask`

## 📦 Installation

```bash
npm install ms-events
```

```bash
yarn add ms-events
```

```bash
pnpm add ms-events
```

## 🚀 Quick Start

```ts
import { EventEmitter } from 'ms-events';

type Events = {
  ready: [];
  message: [string, number];
  error: [Error];
};

const emitter = new EventEmitter<Events>();

// Type-safe listeners
emitter.on('message', (text, count) => {
  console.log(text, count);
});

emitter.emit('message', 'hello', 42); // ✅ OK
// emitter.emit('message', 'hello', 'world'); // ❌ TypeScript error
```

## 📚 Examples

### Async Events

```ts
emitter.on('ready', async () => {
  await fetchData();
  console.log('Ready!');
});

await emitter.emitAsync('ready');
```

### Wildcards

```ts
emitter.on('*', (event, ...args) => {
  console.log(`Event ${String(event)} fired with:`, args);
});

emitter.emit('message', 'hi', 1);
// Output: Event message fired with: ['hi', 1]
```

### Namespaces

```ts
const userEmitter = emitter.scope('user');

userEmitter.on('login:*', (event, ...args) => {
  console.log(`User event: ${String(event)}`);
});

userEmitter.emit('login:success', 'alice');
```

### Throttling

```ts
emitter.onThrottled('scroll', (position) => {
  console.log('Throttled scroll:', position);
}, { delay: 100 });
```

### AbortSignal Cleanup

```ts
const controller = new AbortController();

emitter.on('update', handler, { signal: controller.signal });
controller.abort(); // Auto-removes listener
```

### Error Handling

```ts
emitter.on('error', (error) => {
  console.error('Emitter error:', error);
});

emitter.on('fail', () => {
  throw new Error('Something went wrong');
});

emitter.emit('fail'); // Caught by error handler
```

## 🔧 API Reference

### Constructor

```ts
const emitter = new EventEmitter<Events>(options?);
```

Options:
- `maxListeners?: number` - Max listeners per event
- `strictMaxListeners?: boolean` - Throw on limit exceeded
- `debug?: DebugOptions` - Enable logging
- `buffer?: BufferOptions` - Enable event buffering

### Core Methods

#### `on(event, handler, options?)`
Add a listener. Returns cleanup function.

```ts
const cleanup = emitter.on('event', handler, { signal: abortSignal });
cleanup(); // Remove listener
```

#### `once(event, handler, options?)`
Add one-time listener.

#### `emit(event, ...args)`
Emit event synchronously.

#### `emitAsync(event, ...args)`
Emit event asynchronously, waiting for all listeners.

#### `emitAsyncSerial(event, ...args)`
Emit serially (one after another).

#### `emitAsyncParallel(event, ...args)`
Emit in parallel (default for `emitAsync`).

#### `off(event, handler)`
Remove specific listener.

### Advanced Methods

#### Listeners
- `prependListener(event, handler)` - Add to front of queue
- `appendListener(event, handler)` - Add to end (same as `on`)
- `prependOnceListener(event, handler)` - Prepend one-time
- `onThrottled(event, handler, options)` - Throttled listener
- `onDebounced(event, handler, options)` - Debounced listener

#### Inspection
- `listeners(event)` - Get listeners (defensive copy)
- `rawListeners(event)` - Get listeners (mutable)
- `listenerCount(event)` - Count listeners
- `hasListeners(event)` - Check if has listeners
- `eventNames()` - Get all event names

#### Control
- `setMaxListeners(n)` - Set global max
- `setMaxListenersPerEvent(event, n)` - Per-event max
- `setStrictMaxListeners(strict)` - Throw on exceed
- `clear(event?)` - Remove all listeners
- `removeAllListeners(event?)` - Alias for `clear`

#### Scoping
- `scope(namespace)` - Create scoped emitter

#### Timing
- `emitNextTick(event, ...args)` - Emit on next tick
- `emitMicrotask(event, ...args)` - Emit on microtask

#### Debugging
- `setDebug(options)` - Enable logging
- `setBuffering(options)` - Enable buffering

## ⚡ Performance

- **Fast Path**: Optimized for single listener
- **Minimal Allocations**: Reuse objects where possible
- **Defensive Copies**: Only when necessary
- **Zero GC Pressure**: For high-frequency events

## 🔍 Comparison

| Feature | Node.js EventEmitter | ms-events |
|---------|---------------------|-----------|
| Type Safety | ❌ | ✅ Full inference |
| Zero Runtime Deps | ❌ | ✅ |
| Async Emit | ❌ | ✅ |
| Wildcards | ❌ | ✅ |
| Namespaces | ❌ | ✅ |
| Throttling | ❌ | ✅ |
| Debouncing | ❌ | ✅ |
| Symbols | ❌ | ✅ |
| AbortSignal | ❌ | ✅ |
| Buffering | ❌ | ✅ |
| Performance | Good | Optimized |

## 🛠️ Development

```bash
# Install deps
npm install

# Build
npm run build

# Test
npm test

# Type check
npm run typecheck

# Lint
npm run lint
```

## 📄 License

MIT © [microstack-dev](https://github.com/microstack-dev)

## 🤝 Contributing

PRs welcome! Please read our [contributing guide](CONTRIBUTING.md).

## 📞 Support

- 📧 [Issues](https://github.com/microstack-dev/ms-events/issues)
- 💬 [Discussions](https://github.com/microstack-dev/ms-events/discussions)