This commit is contained in:
2026-11-02 12:42:04 +00:00
commit e4e28174bf
5498 changed files with 1735888 additions and 0 deletions

19
node_modules/qified/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,19 @@
MIT License & © Jared Wray
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

677
node_modules/qified/README.md generated vendored Normal file
View File

@@ -0,0 +1,677 @@
[![logo.svg](https://qified.org/logo.svg)](https://qified.org)
[![tests](https://github.com/jaredwray/qified/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/qified/actions/workflows/tests.yaml)
[![GitHub license](https://img.shields.io/github/license/jaredwray/qified)](https://github.com/jaredwray/qified/blob/main/LICENSE)
[![codecov](https://codecov.io/gh/jaredwray/qified/graph/badge.svg?token=jcRdy8SkOG)](https://codecov.io/gh/jaredwray/qified)
[![npm](https://img.shields.io/npm/dm/qified)](https://npmjs.com/package/qified)
[![npm](https://img.shields.io/npm/v/qified)](https://npmjs.com/package/qified)
# qified
Task and Message Queues with Multiple Providers
# Features
* Simple Message Queue for Processing Messages
* Simple Message Format `Message`
* Easily Send a Message `publish()`
* Easily Subscribe to a message Queue `subscribe()`
* Simple Task Format `Task`
* Easily Send a Task `enqueue()`
* Easily Subscribe to a Task Queue `dequeue()`
* Ack / Reject / Extend in the handler via `TaskContext`
* Async/Await Built In By Default
* Written in Typescript, Nodejs Last Two Versions, ESM and CJS
* Events and Hooks for all major actions via [Hookified](https://hookified.org)
* Provider Fail Over Support
# Table of Contents
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Constructor](#constructor)
- [Properties](#properties)
- [Methods](#methods)
- [subscribe](#subscribe)
- [publish](#publish)
- [unsubscribeMessage](#unsubscribemessage)
- [enqueue](#enqueue)
- [dequeue](#dequeue)
- [unsubscribeTask](#unsubscribetask)
- [disconnect](#disconnect)
- [Events](#events)
- [Available Events](#available-events)
- [Listening to Events](#listening-to-events)
- [Error Handling with Events](#error-handling-with-events)
- [Hooks](#hooks)
- [Available Hooks](#available-hooks)
- [Using Hooks](#using-hooks)
- [Modifying Data with Before Hooks](#modifying-data-with-before-hooks)
- [Modifying Topics with Before Hooks](#modifying-topics-with-before-hooks)
- [Multiple Hooks](#multiple-hooks)
- [Hooks vs Events](#hooks-vs-events)
- [Providers](#providers)
- [Development and Testing](#development-and-testing)
- [License](#license)
# Installation
```bash
pnpm add qified
```
# Quick Start
```js
import { Qified, MemoryMessageProvider } from 'qified';
// Create a new Qified instance with a memory provider
const qified = new Qified({
messageProviders: new MemoryMessageProvider()
});
// Subscribe to a topic
await qified.subscribe('notifications', {
id: 'notificationHandler',
handler: async (message) => {
console.log('Received:', message.data);
}
});
// Publish a message
await qified.publish('notifications', {
id: 'msg-1',
data: { text: 'Hello, World!' }
});
// Clean up
await qified.disconnect();
```
# Constructor
```js
new Qified(options?: QifiedOptions)
```
**Options:**
- `messageProviders?: MessageProvider | MessageProvider[]` - a provider or Array of message providers to use
- `taskProviders?: TaskProvider[]` - Array of task providers to use
**Example:**
```js
import { Qified, MemoryMessageProvider } from 'qified';
const qified = new Qified({
messageProviders: new MemoryMessageProvider()
});
```
# Properties
### `messageProviders: MessageProvider[]`
Get or set the array of message providers. This property allows you to dynamically manage which message providers are active in your Qified instance.
**Type:** `MessageProvider[]`
**Access:** Read/Write
**Description:**
- **Getter**: Returns the current array of message providers being used
- **Setter**: Replaces all current message providers with a new array
**Use Cases:**
- Inspect which providers are currently configured
- Add or remove providers dynamically at runtime
- Replace all providers with a new set
- Migrate from one provider to another
**Example:**
```typescript
import { Qified, MemoryMessageProvider } from 'qified';
import { NatsMessageProvider } from '@qified/nats';
import { RedisMessageProvider } from '@qified/redis';
const qified = new Qified({
messageProviders: new MemoryMessageProvider()
});
// Get current providers
const providers = qified.messageProviders;
console.log(`Currently using ${providers.length} provider(s)`);
// Add another provider
qified.messageProviders = [
new MemoryMessageProvider(),
new NatsMessageProvider()
];
// Replace all providers
qified.messageProviders = [
new RedisMessageProvider({ uri: 'redis://localhost:6379' })
];
// Access provider properties
qified.messageProviders.forEach(provider => {
console.log('Provider ID:', provider.id);
});
```
**Important Notes:**
- Setting this property does **not** automatically disconnect existing providers
- You should call `disconnect()` on old providers before replacing them to clean up resources
- All message operations (`subscribe`, `publish`, `unsubscribeMessage`) will execute across all message providers in this array
### `taskProviders: TaskProvider[]`
Get or set the array of task providers. Works the same way as `messageProviders` — getter returns the active providers, setter replaces them.
**Type:** `TaskProvider[]`
**Access:** Read/Write
**Example:**
```typescript
import { Qified, MemoryTaskProvider } from 'qified';
import { RedisTaskProvider } from '@qified/redis';
const qified = new Qified({
taskProviders: new MemoryTaskProvider()
});
// Replace with a Redis-backed task provider
qified.taskProviders = [
new RedisTaskProvider({ uri: 'redis://localhost:6379' })
];
```
All task operations (`enqueue`, `dequeue`, `unsubscribeTask`) execute across every task provider in this array.
# Methods
## subscribe
Subscribe to a topic to receive messages. If multiple message providers are configured, this will subscribe on all of them.
**Parameters:**
- `topic: string` - The topic to subscribe to
- `handler: TopicHandler` - Object containing an optional `id` and a `handler` function
**Example:**
```js
await qified.subscribe('user-events', {
id: 'userEventHandler',
handler: async (message) => {
console.log('User event:', message.data);
}
});
```
## publish
Publish a message to a topic. If multiple message providers are configured, this will publish to all of them.
**Parameters:**
- `topic: string` - The topic to publish to
- `message: Message` - The message object to publish
**Example:**
```js
await qified.publish('user-events', {
id: 'evt-123',
data: {
userId: 'user-456',
action: 'login',
timestamp: Date.now()
},
headers: {
'content-type': 'application/json'
}
});
```
## unsubscribeMessage
Unsubscribe a message handler from a topic. If an `id` is provided, only that handler is unsubscribed. Otherwise, all handlers for the topic are unsubscribed.
**Parameters:**
- `topic: string` - The topic to unsubscribe from
- `id?: string` - Optional handler ID. If not provided, all handlers are unsubscribed
**Example:**
```js
// Unsubscribe a specific handler
await qified.unsubscribeMessage('user-events', 'userEventHandler');
// Unsubscribe all handlers for a topic
await qified.unsubscribeMessage('user-events');
```
## enqueue
Enqueue a task to a queue. If multiple task providers are configured, this will enqueue on all of them and return the id assigned by each provider (in provider order).
**Parameters:**
- `queue: string` - The queue to enqueue to
- `task: EnqueueTask` - The task payload. `id` and `timestamp` are assigned by the provider
**Returns:** `Promise<string[]>` - The task ids from each provider
**Example:**
```js
const ids = await qified.enqueue('image-processing', {
data: { imageUrl: 'https://example.com/img.png' },
headers: { 'x-source': 'uploader' },
maxRetries: 3,
timeout: 30_000
});
console.log('Enqueued as', ids);
```
## dequeue
Register a handler to process tasks from a queue. If multiple task providers are configured, this registers the handler on all of them. The handler receives the task and a `TaskContext` with `ack()`, `reject()`, and `extend()` methods.
**Parameters:**
- `queue: string` - The queue to dequeue from
- `handler: TaskHandler` - Object containing an optional `id` and a `handler(task, context)` function
**Example:**
```js
await qified.dequeue('image-processing', {
id: 'resizer',
handler: async (task, context) => {
try {
await processImage(task.data.imageUrl);
await context.ack();
} catch (error) {
// true = requeue for retry; false = send to dead-letter queue
await context.reject(true);
}
}
});
```
## unsubscribeTask
Unsubscribe a task handler from a queue. If an `id` is provided, only that handler is unsubscribed. Otherwise, all handlers for the queue are unsubscribed.
**Parameters:**
- `queue: string` - The queue to unsubscribe from
- `id?: string` - Optional handler ID. If not provided, all handlers are unsubscribed
**Example:**
```js
// Unsubscribe a specific handler
await qified.unsubscribeTask('image-processing', 'resizer');
// Unsubscribe all handlers for a queue
await qified.unsubscribeTask('image-processing');
```
## disconnect
Disconnect from all providers and clean up resources.
**Example:**
```js
await qified.disconnect();
```
# Events
Qified extends [Hookified](https://hookified.org) and emits events for all major operations. You can listen to these events to add custom logging, monitoring, or error handling.
# Available Events
The following events are available via the `QifiedEvents` enum:
- `QifiedEvents.publish` - Emitted after a message is successfully published
- `QifiedEvents.subscribe` - Emitted after successfully subscribing to a topic
- `QifiedEvents.unsubscribeMessage` - Emitted after successfully unsubscribing a message handler from a topic
- `QifiedEvents.enqueue` - Emitted after a task is successfully enqueued
- `QifiedEvents.dequeue` - Emitted after successfully registering a task handler on a queue
- `QifiedEvents.unsubscribeTask` - Emitted after successfully unsubscribing a task handler from a queue
- `QifiedEvents.disconnect` - Emitted after successfully disconnecting from all providers
- `QifiedEvents.error` - Emitted when an error occurs during any operation
- `QifiedEvents.info` - Emitted for informational messages
- `QifiedEvents.warn` - Emitted for warning messages
# Listening to Events
Use the `on()` method to listen to events:
```js
import { Qified, MemoryMessageProvider, QifiedEvents } from 'qified';
const qified = new Qified({
messageProviders: new MemoryMessageProvider()
});
// Listen for publish events
await qified.on(QifiedEvents.publish, async (data) => {
console.log('Message published to topic:', data.topic);
console.log('Message:', data.message);
});
// Listen for subscribe events
await qified.on(QifiedEvents.subscribe, async (data) => {
console.log('Subscribed to topic:', data.topic);
console.log('Handler ID:', data.handler.id);
});
// Listen for unsubscribeMessage events
await qified.on(QifiedEvents.unsubscribeMessage, async (data) => {
console.log('Unsubscribed from topic:', data.topic);
if (data.id) {
console.log('Handler ID:', data.id);
}
});
// Listen for enqueue events
await qified.on(QifiedEvents.enqueue, async (data) => {
console.log('Task enqueued to queue:', data.queue);
console.log('Assigned ids:', data.ids);
});
// Listen for dequeue events
await qified.on(QifiedEvents.dequeue, async (data) => {
console.log('Handler registered on queue:', data.queue);
console.log('Handler ID:', data.handler.id);
});
// Listen for unsubscribeTask events
await qified.on(QifiedEvents.unsubscribeTask, async (data) => {
console.log('Unsubscribed from queue:', data.queue);
if (data.id) {
console.log('Handler ID:', data.id);
}
});
// Listen for disconnect events
await qified.on(QifiedEvents.disconnect, async () => {
console.log('Disconnected from all providers');
});
// Listen for errors
await qified.on(QifiedEvents.error, async (error) => {
console.error('Error occurred:', error);
});
// Now perform operations
await qified.subscribe('events', {
id: 'handler1',
handler: async (message) => {
console.log('Received:', message.data);
}
});
await qified.publish('events', {
id: 'msg-1',
data: { text: 'Hello!' }
});
await qified.unsubscribeMessage('events', 'handler1');
await qified.disconnect();
```
### Error Handling with Events
Events provide a centralized way to handle errors across all operations:
```js
import { Qified, QifiedEvents } from 'qified';
import { NatsMessageProvider } from '@qified/nats';
const qified = new Qified({
messageProviders: new NatsMessageProvider()
});
// Centralized error handler
await qified.on(QifiedEvents.error, async (error) => {
console.error('Qified error:', error.message);
// Send to error tracking service
// Log to file
// Send alert
});
// Errors from publish, subscribe, etc. will be caught and emitted
await qified.publish('topic', { id: '1', data: { test: true } });
```
# Hooks
Qified provides before and after hooks for all major operations, allowing you to intercept and modify data before an operation executes, or perform actions after it completes. Hooks are powered by [Hookified](https://hookified.org).
## Available Hooks
The following hooks are available via the `QifiedHooks` enum:
| Hook | Description | Context Properties |
|------|-------------|-------------------|
| `beforeSubscribe` | Called before subscribing to a topic | `{ topic, handler }` |
| `afterSubscribe` | Called after subscribing to a topic | `{ topic, handler }` |
| `beforePublish` | Called before publishing a message | `{ topic, message }` |
| `afterPublish` | Called after publishing a message | `{ topic, message }` |
| `beforeUnsubscribeMessage` | Called before unsubscribing a message handler | `{ topic, id }` |
| `afterUnsubscribeMessage` | Called after unsubscribing a message handler | `{ topic, id }` |
| `beforeEnqueue` | Called before enqueueing a task | `{ queue, task }` |
| `afterEnqueue` | Called after enqueueing a task | `{ queue, task, ids }` |
| `beforeDequeue` | Called before registering a task handler | `{ queue, handler }` |
| `afterDequeue` | Called after registering a task handler | `{ queue, handler }` |
| `beforeUnsubscribeTask` | Called before unsubscribing a task handler | `{ queue, id }` |
| `afterUnsubscribeTask` | Called after unsubscribing a task handler | `{ queue, id }` |
| `beforeDisconnect` | Called before disconnecting from providers | `{ messageProviderCount, taskProviderCount }` |
| `afterDisconnect` | Called after disconnecting from providers | `{ messageProviderCount, taskProviderCount }` |
## Using Hooks
Use the `onHook()` method to register a hook handler. Hooks use the `IHook` object format from [Hookified](https://hookified.org):
```js
import { Qified, MemoryMessageProvider, QifiedHooks } from 'qified';
const qified = new Qified({
messageProviders: new MemoryMessageProvider()
});
// Register a before hook using IHook object
qified.onHook({
event: QifiedHooks.beforePublish,
handler: async (context) => {
console.log('About to publish to:', context.topic);
}
});
// Register an after hook with an id for later removal
qified.onHook({
id: 'publish-logger',
event: QifiedHooks.afterPublish,
handler: async (context) => {
console.log('Published message:', context.message.id);
}
});
// Register with options to control position
qified.onHook({
event: QifiedHooks.beforePublish,
handler: async (context) => {
console.log('This runs first');
}
}, { position: 'Top' });
```
## Modifying Data with Before Hooks
Before hooks receive a mutable context object. Any changes you make to the context will be applied to the operation:
```js
import { Qified, MemoryMessageProvider, QifiedHooks } from 'qified';
const qified = new Qified({
messageProviders: new MemoryMessageProvider()
});
// Add timestamp and headers to all messages
qified.onHook({
event: QifiedHooks.beforePublish,
handler: async (context) => {
// Add timestamp if not present
context.message.timestamp = context.message.timestamp ?? Date.now();
// Add custom headers
context.message.headers = {
...context.message.headers,
'x-processed-by': 'qified',
'x-environment': process.env.NODE_ENV
};
}
});
// Modify message data
qified.onHook({
event: QifiedHooks.beforePublish,
handler: async (context) => {
// Add metadata to the message data
context.message.data = {
...context.message.data,
_meta: {
version: '1.0',
source: 'api'
}
};
}
});
// Subscribe to receive messages
await qified.subscribe('events', {
id: 'handler1',
handler: async (message) => {
// Message will have timestamp, headers, and modified data
console.log('Timestamp:', message.timestamp);
console.log('Headers:', message.headers);
console.log('Data:', message.data);
}
});
// Publish a message - hooks will modify it before sending
await qified.publish('events', {
id: 'msg-1',
data: { text: 'Hello!' }
});
```
## Modifying Topics with Before Hooks
You can also modify the topic in before hooks:
```js
// Route all messages to a prefixed topic
qified.onHook({
event: QifiedHooks.beforePublish,
handler: async (context) => {
context.topic = `production/${context.topic}`;
}
});
// Subscribe to the prefixed topic
await qified.subscribe('production/events', {
id: 'handler1',
handler: async (message) => {
console.log('Received:', message.data);
}
});
// This publishes to 'production/events' due to the hook
await qified.publish('events', {
id: 'msg-1',
data: { text: 'Hello!' }
});
```
## Multiple Hooks
Multiple hooks for the same event execute in the order they were registered:
```js
// First hook - runs first (default position is 'Bottom')
qified.onHook({
event: QifiedHooks.beforePublish,
handler: async (context) => {
context.message.timestamp = Date.now();
}
});
// Second hook - runs second, can see changes from first hook
qified.onHook({
event: QifiedHooks.beforePublish,
handler: async (context) => {
context.message.headers = { 'x-timestamp': String(context.message.timestamp) };
}
});
// Third hook - runs third
qified.onHook({
event: QifiedHooks.beforePublish,
handler: async (context) => {
console.log('Final message:', context.message);
}
});
// Use position option to insert at the top
qified.onHook({
event: QifiedHooks.beforePublish,
handler: async (context) => {
console.log('This runs before all other hooks');
}
}, { position: 'Top' });
```
## Hooks vs Events
Both hooks and events are available, but they serve different purposes:
| Feature | Hooks | Events |
|---------|-------|--------|
| Timing | Before and after operations | After operations only |
| Data modification | Yes (before hooks) | No |
| Use case | Intercepting/transforming data | Logging, monitoring, side effects |
```js
// Hook - can modify the message before it's published
qified.onHook({
event: QifiedHooks.beforePublish,
handler: async (context) => {
context.message.timestamp = Date.now();
}
});
// Event - notified after publish completes (cannot modify)
qified.on(QifiedEvents.publish, async (data) => {
console.log('Published:', data.message.id);
});
```
# Providers
There are multiple providers available to use:
* Memory - this is built into the current `qified` library as `MemoryMessageProvider` and `MemoryTaskProvider`.
* [@qified/redis](../redis/README.md) - Redis Provider (messages and tasks)
* [@qified/rabbitmq](../rabbitmq/README.md) - RabbitMQ Provider (messages and tasks)
* [@qified/nats](../nats/README.md) - NATS Provider (messages and tasks)
* [@qified/zeromq](../zeromq/README.md) - ZeroMQ Provider (messages only)
# Development and Testing
Qified is written in TypeScript and tests are written in `vitest`. To run the tests, use the following command:
1. `pnpm install` - This will install all the dependencies
2. `pnpm test:services:start` - This will start the services needed for testing (Redis, RabbitMQ, etc)
3. `pnpm test` - This will run the tests
To contribute follow the [Contributing Guidelines](CONTRIBUTING.md) and [Code of Conduct](CODE_OF_CONDUCT.md).
# License
[MIT & © Jared Wray](LICENSE)

662
node_modules/qified/dist/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,662 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
let hookified = require("hookified");
/**
* In-memory message provider for testing and simple use cases.
* Messages are stored and delivered synchronously in memory without persistence.
*/
var MemoryMessageProvider = class {
_subscriptions;
_id;
/**
* Creates an instance of MemoryMessageProvider.
* @param {MemoryMessageProviderOptions} options - Optional configuration for the provider.
*/
constructor(options) {
this._subscriptions = /* @__PURE__ */ new Map();
this._id = options?.id ?? "@qified/memory";
}
/**
* Gets the provider ID for the memory message provider.
* @returns {string} The provider ID.
*/
get id() {
return this._id;
}
/**
* Sets the provider ID for the memory message provider.
* @param {string} id The new provider ID.
*/
set id(id) {
this._id = id;
}
/**
* Gets the subscriptions map for all topics.
* @returns {Map<string, TopicHandler[]>} The subscriptions map.
*/
get subscriptions() {
return this._subscriptions;
}
/**
* Sets the subscriptions map.
* @param {Map<string, TopicHandler[]>} value The new subscriptions map.
*/
set subscriptions(value) {
this._subscriptions = value;
}
/**
* Publishes a message to a specified topic.
* All handlers subscribed to the topic will be called synchronously in order.
* @param {string} topic The topic to publish the message to.
* @param {Message} message The message to publish.
* @returns {Promise<void>} A promise that resolves when all handlers have been called.
*/
async publish(topic, message) {
const messageWithProvider = {
...message,
providerId: this._id
};
const subscriptions = this._subscriptions.get(topic) ?? [];
for (const subscription of subscriptions) await subscription.handler(messageWithProvider);
}
/**
* Subscribes to a specified topic.
* @param {string} topic The topic to subscribe to.
* @param {TopicHandler} handler The handler to process incoming messages.
* @returns {Promise<void>} A promise that resolves when the subscription is complete.
*/
async subscribe(topic, handler) {
if (!this._subscriptions.has(topic)) this._subscriptions.set(topic, []);
this._subscriptions.get(topic)?.push(handler);
}
/**
* Unsubscribes from a specified topic.
* If an ID is provided, only the handler with that ID is removed.
* If no ID is provided, all handlers for the topic are removed.
* @param {string} topic The topic to unsubscribe from.
* @param {string} [id] Optional identifier for the subscription to remove.
* @returns {Promise<void>} A promise that resolves when the unsubscription is complete.
*/
async unsubscribe(topic, id) {
if (id) {
const subscriptions = this._subscriptions.get(topic);
if (subscriptions) this._subscriptions.set(topic, subscriptions.filter((sub) => sub.id !== id));
} else this._subscriptions.delete(topic);
}
/**
* Disconnects and clears all subscriptions.
* @returns {Promise<void>} A promise that resolves when the disconnection is complete.
*/
async disconnect() {
this._subscriptions.clear();
}
};
/**
* In-memory task provider for testing and simple use cases.
* Tasks are stored and processed in memory without persistence.
* Supports task acknowledgment, rejection, retry, and timeout handling.
*/
var MemoryTaskProvider = class {
_id;
_timeout;
_retries;
_taskHandlers;
_queues;
_processing;
_deadLetterQueue;
_taskIdCounter = 0;
_active = true;
/**
* Creates an instance of MemoryTaskProvider.
* @param {MemoryTaskProviderOptions} options - Optional configuration for the provider.
*/
constructor(options) {
this._id = options?.id ?? "@qified/memory";
this._timeout = options?.timeout ?? 3e4;
this._retries = options?.retries ?? 3;
this._taskHandlers = /* @__PURE__ */ new Map();
this._queues = /* @__PURE__ */ new Map();
this._processing = /* @__PURE__ */ new Map();
this._deadLetterQueue = /* @__PURE__ */ new Map();
}
/**
* Gets the provider ID for the memory task provider.
* @returns {string} The provider ID.
*/
get id() {
return this._id;
}
/**
* Sets the provider ID for the memory task provider.
* @param {string} id The new provider ID.
*/
set id(id) {
this._id = id;
}
/**
* Gets the default timeout for task processing.
* @returns {number} The timeout in milliseconds.
*/
get timeout() {
return this._timeout;
}
/**
* Sets the default timeout for task processing.
* @param {number} timeout The timeout in milliseconds.
*/
set timeout(timeout) {
this._timeout = timeout;
}
/**
* Gets the default maximum retry attempts.
* @returns {number} The maximum retry attempts.
*/
get retries() {
return this._retries;
}
/**
* Sets the default maximum retry attempts.
* @param {number} retries The maximum retry attempts.
*/
set retries(retries) {
this._retries = retries;
}
/**
* Gets the task handlers map.
* @returns {Map<string, TaskHandler[]>} The task handlers map.
*/
get taskHandlers() {
return this._taskHandlers;
}
/**
* Sets the task handlers map.
* @param {Map<string, TaskHandler[]>} value The new task handlers map.
*/
set taskHandlers(value) {
this._taskHandlers = value;
}
/**
* Generates a unique task ID.
* @returns {string} A unique task ID.
*/
generateTaskId() {
return `task-${Date.now()}-${++this._taskIdCounter}`;
}
/**
* Enqueues a task to a specific queue.
* Automatically assigns ID and timestamp to the task.
* @param {string} queue - The queue name to enqueue to.
* @param {EnqueueTask} taskData - The task data to enqueue.
* @returns {Promise<string>} The ID of the enqueued task.
*/
async enqueue(queue, taskData) {
if (!this._active) throw new Error("TaskProvider has been disconnected");
const task = {
id: this.generateTaskId(),
timestamp: Date.now(),
...taskData
};
const queuedTask = {
task,
attempt: 0,
deadlineAt: 0,
processing: false
};
if (!this._queues.has(queue)) this._queues.set(queue, []);
this._queues.get(queue)?.push(queuedTask);
await this.processQueue(queue);
return task.id;
}
/**
* Registers a handler to process tasks from a queue.
* Starts processing any pending tasks in the queue.
* @param {string} queue - The queue name to dequeue from.
* @param {TaskHandler} handler - The handler configuration.
* @returns {Promise<void>}
*/
async dequeue(queue, handler) {
if (!this._active) throw new Error("TaskProvider has been disconnected");
if (!this._taskHandlers.has(queue)) this._taskHandlers.set(queue, []);
this._taskHandlers.get(queue)?.push(handler);
await this.processQueue(queue);
}
/**
* Processes tasks in a queue by delivering them to registered handlers.
* @param {string} queue - The queue name to process.
*/
async processQueue(queue) {
/* v8 ignore next -- @preserve */
if (!this._active) return;
const handlers = this._taskHandlers.get(queue);
if (!handlers || handlers.length === 0) return;
const queuedTasks = this._queues.get(queue);
if (!queuedTasks || queuedTasks.length === 0) return;
const processingSet = this._processing.get(queue) ?? /* @__PURE__ */ new Set();
this._processing.set(queue, processingSet);
for (const queuedTask of queuedTasks) {
if (queuedTask.processing || processingSet.has(queuedTask.task.id)) continue;
queuedTask.processing = true;
processingSet.add(queuedTask.task.id);
for (const handler of handlers) this.processTask(queue, queuedTask, handler);
}
}
/**
* Processes a single task with a handler.
* @param {string} queue - The queue name.
* @param {QueuedTask} queuedTask - The queued task to process.
* @param {TaskHandler} handler - The handler to process the task.
*/
async processTask(queue, queuedTask, handler) {
const { task } = queuedTask;
const maxRetries = task.maxRetries ?? this._retries;
const timeout = task.timeout ?? this._timeout;
queuedTask.attempt++;
queuedTask.deadlineAt = Date.now() + timeout;
let acknowledged = false;
let rejected = false;
const context = {
ack: async () => {
if (acknowledged || rejected) return;
acknowledged = true;
await this.removeTask(queue, task.id);
},
reject: async (requeue = true) => {
if (acknowledged || rejected) return;
rejected = true;
if (requeue && queuedTask.attempt < maxRetries) {
queuedTask.processing = false;
this._processing.get(queue)?.delete(task.id);
setTimeout(() => {
this.processQueue(queue);
}, 100);
} else {
await this.moveToDeadLetter(queue, task);
await this.removeTask(queue, task.id);
}
},
extend: async (ttl) => {
if (acknowledged || rejected) return;
queuedTask.deadlineAt = Date.now() + ttl;
if (queuedTask.timeoutHandle) clearTimeout(queuedTask.timeoutHandle);
/* v8 ignore next -- @preserve */
queuedTask.timeoutHandle = setTimeout(() => {
if (!acknowledged && !rejected) context.reject(true);
}, ttl);
},
metadata: {
attempt: queuedTask.attempt,
maxRetries
}
};
queuedTask.timeoutHandle = setTimeout(() => {
if (!acknowledged && !rejected) context.reject(true);
}, timeout);
try {
await handler.handler(task, context);
if (!acknowledged && !rejected) await context.ack();
} catch (_error) {
if (!acknowledged && !rejected) await context.reject(true);
} finally {
if (queuedTask.timeoutHandle) clearTimeout(queuedTask.timeoutHandle);
}
}
/**
* Removes a task from the queue.
* @param {string} queue - The queue name.
* @param {string} taskId - The task ID to remove.
*/
async removeTask(queue, taskId) {
const queuedTasks = this._queues.get(queue);
if (queuedTasks) {
const index = queuedTasks.findIndex((qt) => qt.task.id === taskId);
if (index !== -1) queuedTasks.splice(index, 1);
}
this._processing.get(queue)?.delete(taskId);
}
/**
* Moves a task to the dead-letter queue.
* @param {string} queue - The original queue name.
* @param {Task} task - The task to move.
*/
async moveToDeadLetter(queue, task) {
const dlqKey = `${queue}:dead-letter`;
if (!this._deadLetterQueue.has(dlqKey)) this._deadLetterQueue.set(dlqKey, []);
this._deadLetterQueue.get(dlqKey)?.push(task);
}
/**
* Unsubscribes a handler from a queue.
* @param {string} queue - The queue name to unsubscribe from.
* @param {string} [id] - Optional handler ID. If not provided, removes all handlers.
* @returns {Promise<void>}
*/
async unsubscribe(queue, id) {
if (id) {
const handlers = this._taskHandlers.get(queue);
if (handlers) this._taskHandlers.set(queue, handlers.filter((h) => h.id !== id));
} else this._taskHandlers.delete(queue);
}
/**
* Disconnects and clears all queues and handlers.
* Stops all task processing.
* @returns {Promise<void>}
*/
async disconnect() {
this._active = false;
for (const queuedTasks of this._queues.values()) for (const queuedTask of queuedTasks) if (queuedTask.timeoutHandle) clearTimeout(queuedTask.timeoutHandle);
this._taskHandlers.clear();
this._queues.clear();
this._processing.clear();
this._deadLetterQueue.clear();
}
/**
* Gets all tasks in the dead-letter queue for a specific queue.
* Useful for debugging and monitoring failed tasks.
* @param {string} queue - The queue name.
* @returns {Task[]} Array of tasks in the dead-letter queue.
*/
getDeadLetterTasks(queue) {
const dlqKey = `${queue}:dead-letter`;
return this._deadLetterQueue.get(dlqKey) ?? [];
}
/**
* Gets the current state of a queue.
* Useful for monitoring and debugging.
* @param {string} queue - The queue name.
* @returns {Object} Queue statistics.
*/
getQueueStats(queue) {
const queuedTasks = this._queues.get(queue) ?? [];
const processing = this._processing.get(queue)?.size ?? 0;
const waiting = queuedTasks.filter((qt) => !qt.processing).length;
const dlqKey = `${queue}:dead-letter`;
return {
waiting,
processing,
deadLetter: this._deadLetterQueue.get(dlqKey)?.length ?? 0
};
}
};
//#endregion
//#region src/index.ts
/**
* Standard events emitted by Qified.
*/
let QifiedEvents = /* @__PURE__ */ function(QifiedEvents) {
QifiedEvents["error"] = "error";
QifiedEvents["info"] = "info";
QifiedEvents["warn"] = "warn";
QifiedEvents["publish"] = "publish";
QifiedEvents["subscribe"] = "subscribe";
QifiedEvents["unsubscribeMessage"] = "unsubscribeMessage";
QifiedEvents["enqueue"] = "enqueue";
QifiedEvents["dequeue"] = "dequeue";
QifiedEvents["unsubscribeTask"] = "unsubscribeTask";
QifiedEvents["disconnect"] = "disconnect";
return QifiedEvents;
}({});
/**
* Hook event names for before/after lifecycle hooks.
* Before hooks receive a mutable context object that can be modified.
* After hooks receive the final context after the operation completes.
*/
let QifiedHooks = /* @__PURE__ */ function(QifiedHooks) {
QifiedHooks["beforeSubscribe"] = "before:subscribe";
QifiedHooks["afterSubscribe"] = "after:subscribe";
QifiedHooks["beforePublish"] = "before:publish";
QifiedHooks["afterPublish"] = "after:publish";
QifiedHooks["beforeUnsubscribeMessage"] = "before:unsubscribeMessage";
QifiedHooks["afterUnsubscribeMessage"] = "after:unsubscribeMessage";
QifiedHooks["beforeEnqueue"] = "before:enqueue";
QifiedHooks["afterEnqueue"] = "after:enqueue";
QifiedHooks["beforeDequeue"] = "before:dequeue";
QifiedHooks["afterDequeue"] = "after:dequeue";
QifiedHooks["beforeUnsubscribeTask"] = "before:unsubscribeTask";
QifiedHooks["afterUnsubscribeTask"] = "after:unsubscribeTask";
QifiedHooks["beforeDisconnect"] = "before:disconnect";
QifiedHooks["afterDisconnect"] = "after:disconnect";
return QifiedHooks;
}({});
var Qified = class extends hookified.Hookified {
_messageProviders = [];
_taskProviders = [];
/**
* Creates an instance of Qified.
* @param {QifiedOptions} options - Optional configuration for Qified.
*/
constructor(options) {
super(options);
if (options?.messageProviders) if (Array.isArray(options?.messageProviders)) this._messageProviders = options.messageProviders;
else this._messageProviders = [options?.messageProviders];
if (options?.taskProviders) if (Array.isArray(options?.taskProviders)) this._taskProviders = options.taskProviders;
else this._taskProviders = [options?.taskProviders];
}
/**
* Gets or sets the message providers.
* @returns {MessageProvider[]} The array of message providers.
*/
get messageProviders() {
return this._messageProviders;
}
/**
* Sets the message providers.
* @param {MessageProvider[]} providers - The array of message providers to set.
*/
set messageProviders(providers) {
this._messageProviders = providers;
}
/**
* Gets or sets the task providers.
* @returns {TaskProvider[]} The array of task providers.
*/
get taskProviders() {
return this._taskProviders;
}
/**
* Sets the task providers.
* @param {TaskProvider[]} providers - The array of task providers to set.
*/
set taskProviders(providers) {
this._taskProviders = providers;
}
/**
* Subscribes to a topic. If you have multiple message providers, it will subscribe to the topic on all of them.
* @param {string} topic - The topic to subscribe to.
* @param {TopicHandler} handler - The handler to call when a message is published to the topic.
*/
async subscribe(topic, handler) {
try {
const context = {
topic,
handler
};
await this.hook("before:subscribe", context);
const promises = this._messageProviders.map(async (provider) => provider.subscribe(context.topic, context.handler));
await Promise.all(promises);
await this.hook("after:subscribe", {
topic: context.topic,
handler: context.handler
});
this.emit("subscribe", {
topic: context.topic,
handler: context.handler
});
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
/**
* Publishes a message to a topic. If you have multiple message providers, it will publish the message to all of them.
* @param {string} topic - The topic to publish to.
* @param {Message} message - The message to publish.
*/
async publish(topic, message) {
try {
const context = {
topic,
message
};
await this.hook("before:publish", context);
const promises = this._messageProviders.map(async (provider) => provider.publish(context.topic, context.message));
await Promise.all(promises);
await this.hook("after:publish", {
topic: context.topic,
message: context.message
});
this.emit("publish", {
topic: context.topic,
message: context.message
});
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
/**
* Unsubscribes a message handler from a topic. If you have multiple message providers, it will unsubscribe from the topic on all of them.
* If an ID is provided, it will unsubscribe only that handler. If no ID is provided, it will unsubscribe all handlers for the topic.
* @param topic - The topic to unsubscribe from.
* @param id - The optional ID of the handler to unsubscribe. If not provided, all handlers for the topic will be unsubscribed.
*/
async unsubscribeMessage(topic, id) {
try {
const context = {
topic,
id
};
await this.hook("before:unsubscribeMessage", context);
const promises = this._messageProviders.map(async (provider) => provider.unsubscribe(context.topic, context.id));
await Promise.all(promises);
await this.hook("after:unsubscribeMessage", {
topic: context.topic,
id: context.id
});
this.emit("unsubscribeMessage", {
topic: context.topic,
id: context.id
});
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
/**
* Enqueues a task to a queue. If you have multiple task providers, it will enqueue the task on all of them.
* @param {string} queue - The queue to enqueue to.
* @param {EnqueueTask} task - The task to enqueue.
* @returns {Promise<string[]>} The ids assigned to the task by each provider, in provider order.
*/
async enqueue(queue, task) {
try {
const context = {
queue,
task
};
await this.hook("before:enqueue", context);
const promises = this._taskProviders.map(async (provider) => provider.enqueue(context.queue, context.task));
const ids = await Promise.all(promises);
await this.hook("after:enqueue", {
queue: context.queue,
task: context.task,
ids
});
this.emit("enqueue", {
queue: context.queue,
task: context.task,
ids
});
return ids;
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
/* v8 ignore next -- @preserve */
return [];
}
}
/**
* Registers a handler to dequeue tasks from a queue. If you have multiple task providers, it will register the handler on all of them.
* @param {string} queue - The queue to dequeue from.
* @param {TaskHandler} handler - The handler to call when a task is available.
*/
async dequeue(queue, handler) {
try {
const context = {
queue,
handler
};
await this.hook("before:dequeue", context);
const promises = this._taskProviders.map(async (provider) => provider.dequeue(context.queue, context.handler));
await Promise.all(promises);
await this.hook("after:dequeue", {
queue: context.queue,
handler: context.handler
});
this.emit("dequeue", {
queue: context.queue,
handler: context.handler
});
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
/**
* Unsubscribes a task handler from a queue. If you have multiple task providers, it will unsubscribe on all of them.
* If an ID is provided, it will unsubscribe only that handler. If no ID is provided, it will unsubscribe all handlers for the queue.
* @param queue - The queue to unsubscribe from.
* @param id - The optional ID of the handler to unsubscribe. If not provided, all handlers for the queue will be unsubscribed.
*/
async unsubscribeTask(queue, id) {
try {
const context = {
queue,
id
};
await this.hook("before:unsubscribeTask", context);
const promises = this._taskProviders.map(async (provider) => provider.unsubscribe(context.queue, context.id));
await Promise.all(promises);
await this.hook("after:unsubscribeTask", {
queue: context.queue,
id: context.id
});
this.emit("unsubscribeTask", {
queue: context.queue,
id: context.id
});
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
/**
* Disconnects from all providers.
* This method will call the `disconnect` method on each message provider and task provider,
* then clear both provider arrays.
*/
async disconnect() {
try {
const context = {
messageProviderCount: this._messageProviders.length,
taskProviderCount: this._taskProviders.length
};
await this.hook("before:disconnect", context);
const promises = [...this._messageProviders.map(async (provider) => provider.disconnect()), ...this._taskProviders.map(async (provider) => provider.disconnect())];
await Promise.all(promises);
this._messageProviders = [];
this._taskProviders = [];
await this.hook("after:disconnect", {
messageProviderCount: context.messageProviderCount,
taskProviderCount: context.taskProviderCount
});
this.emit("disconnect");
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
};
//#endregion
exports.MemoryMessageProvider = MemoryMessageProvider;
exports.MemoryTaskProvider = MemoryTaskProvider;
exports.Qified = Qified;
exports.QifiedEvents = QifiedEvents;
exports.QifiedHooks = QifiedHooks;

626
node_modules/qified/dist/index.d.cts generated vendored Normal file
View File

@@ -0,0 +1,626 @@
import { Hookified, HookifiedOptions } from "hookified";
//#region src/types.d.ts
/**
* Message interface for the message provider
* @template T - The type of the message data
*/
type Message<T = any> = {
/**
* Unique identifier for the message
* @type {string}
*/
id: string;
/**
* The id of the provider that delivered this message.
* Set by the provider before delivery — always present on received messages.
* Producers should publish with `Omit<Message, "providerId">`; the provider
* assigns this field.
*/
providerId: string;
/**
* The data of the message
* @type {<T = any>}
*/
data: T;
/**
* Timestamp of when the message was created
* @type {number}
*/
timestamp?: number;
/**
* Headers for additional metadata
* @type {Record<string, string>}
*/
headers?: Record<string, string>;
};
type TopicHandler = {
id?: string;
handler: (message: Message) => Promise<void>;
};
/**
* MessageProvider interface for the message provider
*/
type MessageProvider = {
/**
* The id of the message provider. Use primary when multiple providers
* are used.
*/
id: string;
/**
* Array of handlers for message processing
* @type {Map<string, Array<TopicHandler>>}
*/
subscriptions: Map<string, TopicHandler[]>;
/**
* Plublish a message to a topic / queue. This is used to send messages to subscribers.
* @param topic - The topic or queue to publish the message to
* @param message - The message to be published
* @returns {Promise<void>}
*/
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**
* Subscribe to a topic / queue. This is used to receive messages from the provider.
* @param {TopicHandler} subscription - The topic or queue to subscribe to
* @returns {Promise<void>}
*/
subscribe(topic: string, handler: TopicHandler): Promise<void>;
/**
* Remove subscription to a topic / queue.
* @param topic - The topic or queue to unsubscribe from
* @param id - Optional unique identifier for the subscription to remove. If not provided, it will remove all subscriptions for the topic.
* @returns {Promise<void>}
*/
unsubscribe(topic: string, id?: string): Promise<void>;
/**
* Unsubscribe from a topic / queue. This is used to stop receiving messages from the provider.
* @returns {Promise<void>}
*/
disconnect(): Promise<void>;
};
/**
* Task interface for the task provider
* @template T - The type of the task data
*/
type Task<T = any> = {
/**
* Unique identifier for the task
* @type {string}
*/
id: string;
/**
* The data of the task
* @type {<T = any>}
*/
data: T;
/**
* Timestamp of when the task was created (milliseconds since epoch)
* Set automatically by provider if not provided based on Date.now()
* @type {number}
*/
timestamp?: number;
/**
* Headers for additional metadata
* @type {Record<string, string>}
*/
headers?: Record<string, string>;
/**
* Maximum number of retry attempts
* If undefined, uses provider default
* @type {number}
*/
maxRetries?: number;
/**
* Maximum processing time in milliseconds before task times out
* If not set, uses provider default
* @type {number}
*/
timeout?: number;
};
/**
* Task type for enqueueing tasks
* Omits fields that are automatically generated by the provider
* The provider will assign the id and timestamp when the task is enqueued
*/
type EnqueueTask = Omit<Task, "id" | "timestamp">;
/**
* Context provided to task handlers for acknowledgment and task control
* Allows handlers to acknowledge, reject, or extend processing time for tasks
*/
type TaskContext = {
/**
* Acknowledge successful task completion
* Removes the task from the queue and marks it as completed
* @returns {Promise<void>}
*/
ack: () => Promise<void>;
/**
* Reject the task with explicit requeue control
* @param requeue - If true, requeue for retry. If false, send to dead-letter queue. Defaults to true.
* @returns {Promise<void>}
*/
reject: (requeue?: boolean) => Promise<void>;
/**
* Extend the visibility timeout / processing deadline
* Prevents task from being redelivered to another consumer while still processing
* Useful for long-running tasks that need more time
* @param ttl - Additional time to live in milliseconds
* @returns {Promise<void>}
*/
extend: (ttl: number) => Promise<void>;
/**
* Metadata about the current task execution
* Provides context for retry logic and deadline management
*/
metadata: {
/**
* Current retry attempt (0 = first attempt)
* @type {number}
*/
attempt: number;
/**
* Maximum retries allowed for this task
* @type {number}
*/
maxRetries: number;
};
};
/**
* Handler configuration for processing tasks from a queue
* Defines how tasks should be processed and provides options for error handling
*/
type TaskHandler = {
/**
* Optional unique identifier for this handler
* Used to identify and unsubscribe specific handlers
* @type {string}
*/
id?: string;
/**
* The handler function to process tasks
* Called for each task dequeued from the queue
* @param task - The task to process
* @param context - Context for acknowledging, rejecting, or extending the task
* @returns {Promise<void>}
*/
handler: (task: Task, context: TaskContext) => Promise<void>;
};
/**
* Configuration options for task providers
* Allows customization of default behavior for task processing
*/
type TaskProviderOptions = {
/**
* Default timeout for task processing in milliseconds
* Tasks exceeding this duration may be requeued or marked as failed
* @type {number}
*/
timeout?: number;
/**
* Default maximum number of retry attempts for failed tasks
* After this many failures, tasks may be sent to dead-letter queue
* @type {number}
*/
retries?: number;
/**
* Name of the dead-letter queue for failed tasks
* If not provided, dead-letter functionality is disabled
* @type {string}
*/
deadLetterQueue?: string;
};
/**
* TaskProvider interface for task queue management
* Handles enqueueing, dequeueing, and lifecycle management of tasks
* Implementations should provide reliable task delivery and acknowledgment
*/
type TaskProvider = {
/**
* Unique identifier for this provider instance
* Used to distinguish between multiple providers
* @type {string}
*/
id: string;
/**
* Default timeout for task processing in milliseconds
* Can be overridden per task or per handler
* @type {number}
*/
timeout: number;
/**
* Default maximum number of retry attempts
* Can be overridden per task
* @type {number}
*/
retries: number;
/**
* Name of the dead-letter queue for failed tasks
* If not provided, dead-letter functionality is disabled
* @type {string}
*/
deadLetterQueue?: string;
/**
* Map of queue names to their registered handlers
* Tracks all active handlers for each queue
* @type {Map<string, TaskHandler[]>}
*/
taskHandlers: Map<string, TaskHandler[]>;
/**
* Enqueue a task to a specific queue for processing
* The task will be delivered to registered handlers for that queue
* @param queue - The queue name to enqueue the task to
* @param task - The task to be enqueued
* @returns {Promise<string>} - the id of the task being queued
*/
enqueue(queue: string, task: EnqueueTask): Promise<string>;
/**
* Register a handler to process tasks from a specific queue
* The handler will be called for each task dequeued from the queue
* @param queue - The queue name to dequeue tasks from
* @param handler - The handler configuration for processing tasks
* @returns {Promise<void>}
*/
dequeue(queue: string, handler: TaskHandler): Promise<void>;
/**
* Unsubscribe a handler from a queue
* Stops the handler from receiving new tasks
* @param queue - The queue name to unsubscribe from
* @param id - Optional handler ID. If not provided, removes all handlers for the queue
* @returns {Promise<void>}
*/
unsubscribe(queue: string, id?: string): Promise<void>;
/**
* Disconnect and clean up the provider
* Stops receiving tasks, closes connections, and releases resources
* Should be called before application shutdown
* @returns {Promise<void>}
*/
disconnect(): Promise<void>;
};
//#endregion
//#region src/memory/message.d.ts
/**
* Configuration options for the memory message provider.
*/
type MemoryMessageProviderOptions = {
/**
* The unique identifier for this provider instance.
* @default "@qified/memory"
*/
id?: string;
};
/**
* In-memory message provider for testing and simple use cases.
* Messages are stored and delivered synchronously in memory without persistence.
*/
declare class MemoryMessageProvider implements MessageProvider {
private _subscriptions;
private _id;
/**
* Creates an instance of MemoryMessageProvider.
* @param {MemoryMessageProviderOptions} options - Optional configuration for the provider.
*/
constructor(options?: MemoryMessageProviderOptions);
/**
* Gets the provider ID for the memory message provider.
* @returns {string} The provider ID.
*/
get id(): string;
/**
* Sets the provider ID for the memory message provider.
* @param {string} id The new provider ID.
*/
set id(id: string);
/**
* Gets the subscriptions map for all topics.
* @returns {Map<string, TopicHandler[]>} The subscriptions map.
*/
get subscriptions(): Map<string, TopicHandler[]>;
/**
* Sets the subscriptions map.
* @param {Map<string, TopicHandler[]>} value The new subscriptions map.
*/
set subscriptions(value: Map<string, TopicHandler[]>);
/**
* Publishes a message to a specified topic.
* All handlers subscribed to the topic will be called synchronously in order.
* @param {string} topic The topic to publish the message to.
* @param {Message} message The message to publish.
* @returns {Promise<void>} A promise that resolves when all handlers have been called.
*/
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**
* Subscribes to a specified topic.
* @param {string} topic The topic to subscribe to.
* @param {TopicHandler} handler The handler to process incoming messages.
* @returns {Promise<void>} A promise that resolves when the subscription is complete.
*/
subscribe(topic: string, handler: TopicHandler): Promise<void>;
/**
* Unsubscribes from a specified topic.
* If an ID is provided, only the handler with that ID is removed.
* If no ID is provided, all handlers for the topic are removed.
* @param {string} topic The topic to unsubscribe from.
* @param {string} [id] Optional identifier for the subscription to remove.
* @returns {Promise<void>} A promise that resolves when the unsubscription is complete.
*/
unsubscribe(topic: string, id?: string): Promise<void>;
/**
* Disconnects and clears all subscriptions.
* @returns {Promise<void>} A promise that resolves when the disconnection is complete.
*/
disconnect(): Promise<void>;
}
//#endregion
//#region src/memory/task.d.ts
/**
* Configuration options for the memory task provider.
*/
type MemoryTaskProviderOptions = TaskProviderOptions & {
/**
* The unique identifier for this provider instance.
* @default "@qified/memory-task"
*/
id?: string;
};
/**
* In-memory task provider for testing and simple use cases.
* Tasks are stored and processed in memory without persistence.
* Supports task acknowledgment, rejection, retry, and timeout handling.
*/
declare class MemoryTaskProvider implements TaskProvider {
private _id;
private _timeout;
private _retries;
private _taskHandlers;
private _queues;
private _processing;
private _deadLetterQueue;
private _taskIdCounter;
private _active;
/**
* Creates an instance of MemoryTaskProvider.
* @param {MemoryTaskProviderOptions} options - Optional configuration for the provider.
*/
constructor(options?: MemoryTaskProviderOptions);
/**
* Gets the provider ID for the memory task provider.
* @returns {string} The provider ID.
*/
get id(): string;
/**
* Sets the provider ID for the memory task provider.
* @param {string} id The new provider ID.
*/
set id(id: string);
/**
* Gets the default timeout for task processing.
* @returns {number} The timeout in milliseconds.
*/
get timeout(): number;
/**
* Sets the default timeout for task processing.
* @param {number} timeout The timeout in milliseconds.
*/
set timeout(timeout: number);
/**
* Gets the default maximum retry attempts.
* @returns {number} The maximum retry attempts.
*/
get retries(): number;
/**
* Sets the default maximum retry attempts.
* @param {number} retries The maximum retry attempts.
*/
set retries(retries: number);
/**
* Gets the task handlers map.
* @returns {Map<string, TaskHandler[]>} The task handlers map.
*/
get taskHandlers(): Map<string, TaskHandler[]>;
/**
* Sets the task handlers map.
* @param {Map<string, TaskHandler[]>} value The new task handlers map.
*/
set taskHandlers(value: Map<string, TaskHandler[]>);
/**
* Generates a unique task ID.
* @returns {string} A unique task ID.
*/
private generateTaskId;
/**
* Enqueues a task to a specific queue.
* Automatically assigns ID and timestamp to the task.
* @param {string} queue - The queue name to enqueue to.
* @param {EnqueueTask} taskData - The task data to enqueue.
* @returns {Promise<string>} The ID of the enqueued task.
*/
enqueue(queue: string, taskData: EnqueueTask): Promise<string>;
/**
* Registers a handler to process tasks from a queue.
* Starts processing any pending tasks in the queue.
* @param {string} queue - The queue name to dequeue from.
* @param {TaskHandler} handler - The handler configuration.
* @returns {Promise<void>}
*/
dequeue(queue: string, handler: TaskHandler): Promise<void>;
/**
* Processes tasks in a queue by delivering them to registered handlers.
* @param {string} queue - The queue name to process.
*/
private processQueue;
/**
* Processes a single task with a handler.
* @param {string} queue - The queue name.
* @param {QueuedTask} queuedTask - The queued task to process.
* @param {TaskHandler} handler - The handler to process the task.
*/
private processTask;
/**
* Removes a task from the queue.
* @param {string} queue - The queue name.
* @param {string} taskId - The task ID to remove.
*/
private removeTask;
/**
* Moves a task to the dead-letter queue.
* @param {string} queue - The original queue name.
* @param {Task} task - The task to move.
*/
private moveToDeadLetter;
/**
* Unsubscribes a handler from a queue.
* @param {string} queue - The queue name to unsubscribe from.
* @param {string} [id] - Optional handler ID. If not provided, removes all handlers.
* @returns {Promise<void>}
*/
unsubscribe(queue: string, id?: string): Promise<void>;
/**
* Disconnects and clears all queues and handlers.
* Stops all task processing.
* @returns {Promise<void>}
*/
disconnect(): Promise<void>;
/**
* Gets all tasks in the dead-letter queue for a specific queue.
* Useful for debugging and monitoring failed tasks.
* @param {string} queue - The queue name.
* @returns {Task[]} Array of tasks in the dead-letter queue.
*/
getDeadLetterTasks(queue: string): Task[];
/**
* Gets the current state of a queue.
* Useful for monitoring and debugging.
* @param {string} queue - The queue name.
* @returns {Object} Queue statistics.
*/
getQueueStats(queue: string): {
waiting: number;
processing: number;
deadLetter: number;
};
}
//#endregion
//#region src/index.d.ts
/**
* Standard events emitted by Qified.
*/
declare enum QifiedEvents {
error = "error",
info = "info",
warn = "warn",
publish = "publish",
subscribe = "subscribe",
unsubscribeMessage = "unsubscribeMessage",
enqueue = "enqueue",
dequeue = "dequeue",
unsubscribeTask = "unsubscribeTask",
disconnect = "disconnect"
}
/**
* Hook event names for before/after lifecycle hooks.
* Before hooks receive a mutable context object that can be modified.
* After hooks receive the final context after the operation completes.
*/
declare enum QifiedHooks {
beforeSubscribe = "before:subscribe",
afterSubscribe = "after:subscribe",
beforePublish = "before:publish",
afterPublish = "after:publish",
beforeUnsubscribeMessage = "before:unsubscribeMessage",
afterUnsubscribeMessage = "after:unsubscribeMessage",
beforeEnqueue = "before:enqueue",
afterEnqueue = "after:enqueue",
beforeDequeue = "before:dequeue",
afterDequeue = "after:dequeue",
beforeUnsubscribeTask = "before:unsubscribeTask",
afterUnsubscribeTask = "after:unsubscribeTask",
beforeDisconnect = "before:disconnect",
afterDisconnect = "after:disconnect"
}
type QifiedOptions = {
/**
* The message providers to use.
*/
messageProviders?: MessageProvider | MessageProvider[];
/**
* The task providers to use.
*/
taskProviders?: TaskProvider | TaskProvider[];
} & HookifiedOptions;
declare class Qified extends Hookified {
private _messageProviders;
private _taskProviders;
/**
* Creates an instance of Qified.
* @param {QifiedOptions} options - Optional configuration for Qified.
*/
constructor(options?: QifiedOptions);
/**
* Gets or sets the message providers.
* @returns {MessageProvider[]} The array of message providers.
*/
get messageProviders(): MessageProvider[];
/**
* Sets the message providers.
* @param {MessageProvider[]} providers - The array of message providers to set.
*/
set messageProviders(providers: MessageProvider[]);
/**
* Gets or sets the task providers.
* @returns {TaskProvider[]} The array of task providers.
*/
get taskProviders(): TaskProvider[];
/**
* Sets the task providers.
* @param {TaskProvider[]} providers - The array of task providers to set.
*/
set taskProviders(providers: TaskProvider[]);
/**
* Subscribes to a topic. If you have multiple message providers, it will subscribe to the topic on all of them.
* @param {string} topic - The topic to subscribe to.
* @param {TopicHandler} handler - The handler to call when a message is published to the topic.
*/
subscribe(topic: string, handler: TopicHandler): Promise<void>;
/**
* Publishes a message to a topic. If you have multiple message providers, it will publish the message to all of them.
* @param {string} topic - The topic to publish to.
* @param {Message} message - The message to publish.
*/
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**
* Unsubscribes a message handler from a topic. If you have multiple message providers, it will unsubscribe from the topic on all of them.
* If an ID is provided, it will unsubscribe only that handler. If no ID is provided, it will unsubscribe all handlers for the topic.
* @param topic - The topic to unsubscribe from.
* @param id - The optional ID of the handler to unsubscribe. If not provided, all handlers for the topic will be unsubscribed.
*/
unsubscribeMessage(topic: string, id?: string): Promise<void>;
/**
* Enqueues a task to a queue. If you have multiple task providers, it will enqueue the task on all of them.
* @param {string} queue - The queue to enqueue to.
* @param {EnqueueTask} task - The task to enqueue.
* @returns {Promise<string[]>} The ids assigned to the task by each provider, in provider order.
*/
enqueue(queue: string, task: EnqueueTask): Promise<string[]>;
/**
* Registers a handler to dequeue tasks from a queue. If you have multiple task providers, it will register the handler on all of them.
* @param {string} queue - The queue to dequeue from.
* @param {TaskHandler} handler - The handler to call when a task is available.
*/
dequeue(queue: string, handler: TaskHandler): Promise<void>;
/**
* Unsubscribes a task handler from a queue. If you have multiple task providers, it will unsubscribe on all of them.
* If an ID is provided, it will unsubscribe only that handler. If no ID is provided, it will unsubscribe all handlers for the queue.
* @param queue - The queue to unsubscribe from.
* @param id - The optional ID of the handler to unsubscribe. If not provided, all handlers for the queue will be unsubscribed.
*/
unsubscribeTask(queue: string, id?: string): Promise<void>;
/**
* Disconnects from all providers.
* This method will call the `disconnect` method on each message provider and task provider,
* then clear both provider arrays.
*/
disconnect(): Promise<void>;
}
//#endregion
export { type EnqueueTask, MemoryMessageProvider, MemoryTaskProvider, type Message, type MessageProvider, Qified, QifiedEvents, QifiedHooks, QifiedOptions, type Task, type TaskContext, type TaskHandler, type TaskProvider, type TaskProviderOptions, type TopicHandler };

626
node_modules/qified/dist/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,626 @@
import { Hookified, HookifiedOptions } from "hookified";
//#region src/types.d.ts
/**
* Message interface for the message provider
* @template T - The type of the message data
*/
type Message<T = any> = {
/**
* Unique identifier for the message
* @type {string}
*/
id: string;
/**
* The id of the provider that delivered this message.
* Set by the provider before delivery — always present on received messages.
* Producers should publish with `Omit<Message, "providerId">`; the provider
* assigns this field.
*/
providerId: string;
/**
* The data of the message
* @type {<T = any>}
*/
data: T;
/**
* Timestamp of when the message was created
* @type {number}
*/
timestamp?: number;
/**
* Headers for additional metadata
* @type {Record<string, string>}
*/
headers?: Record<string, string>;
};
type TopicHandler = {
id?: string;
handler: (message: Message) => Promise<void>;
};
/**
* MessageProvider interface for the message provider
*/
type MessageProvider = {
/**
* The id of the message provider. Use primary when multiple providers
* are used.
*/
id: string;
/**
* Array of handlers for message processing
* @type {Map<string, Array<TopicHandler>>}
*/
subscriptions: Map<string, TopicHandler[]>;
/**
* Plublish a message to a topic / queue. This is used to send messages to subscribers.
* @param topic - The topic or queue to publish the message to
* @param message - The message to be published
* @returns {Promise<void>}
*/
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**
* Subscribe to a topic / queue. This is used to receive messages from the provider.
* @param {TopicHandler} subscription - The topic or queue to subscribe to
* @returns {Promise<void>}
*/
subscribe(topic: string, handler: TopicHandler): Promise<void>;
/**
* Remove subscription to a topic / queue.
* @param topic - The topic or queue to unsubscribe from
* @param id - Optional unique identifier for the subscription to remove. If not provided, it will remove all subscriptions for the topic.
* @returns {Promise<void>}
*/
unsubscribe(topic: string, id?: string): Promise<void>;
/**
* Unsubscribe from a topic / queue. This is used to stop receiving messages from the provider.
* @returns {Promise<void>}
*/
disconnect(): Promise<void>;
};
/**
* Task interface for the task provider
* @template T - The type of the task data
*/
type Task<T = any> = {
/**
* Unique identifier for the task
* @type {string}
*/
id: string;
/**
* The data of the task
* @type {<T = any>}
*/
data: T;
/**
* Timestamp of when the task was created (milliseconds since epoch)
* Set automatically by provider if not provided based on Date.now()
* @type {number}
*/
timestamp?: number;
/**
* Headers for additional metadata
* @type {Record<string, string>}
*/
headers?: Record<string, string>;
/**
* Maximum number of retry attempts
* If undefined, uses provider default
* @type {number}
*/
maxRetries?: number;
/**
* Maximum processing time in milliseconds before task times out
* If not set, uses provider default
* @type {number}
*/
timeout?: number;
};
/**
* Task type for enqueueing tasks
* Omits fields that are automatically generated by the provider
* The provider will assign the id and timestamp when the task is enqueued
*/
type EnqueueTask = Omit<Task, "id" | "timestamp">;
/**
* Context provided to task handlers for acknowledgment and task control
* Allows handlers to acknowledge, reject, or extend processing time for tasks
*/
type TaskContext = {
/**
* Acknowledge successful task completion
* Removes the task from the queue and marks it as completed
* @returns {Promise<void>}
*/
ack: () => Promise<void>;
/**
* Reject the task with explicit requeue control
* @param requeue - If true, requeue for retry. If false, send to dead-letter queue. Defaults to true.
* @returns {Promise<void>}
*/
reject: (requeue?: boolean) => Promise<void>;
/**
* Extend the visibility timeout / processing deadline
* Prevents task from being redelivered to another consumer while still processing
* Useful for long-running tasks that need more time
* @param ttl - Additional time to live in milliseconds
* @returns {Promise<void>}
*/
extend: (ttl: number) => Promise<void>;
/**
* Metadata about the current task execution
* Provides context for retry logic and deadline management
*/
metadata: {
/**
* Current retry attempt (0 = first attempt)
* @type {number}
*/
attempt: number;
/**
* Maximum retries allowed for this task
* @type {number}
*/
maxRetries: number;
};
};
/**
* Handler configuration for processing tasks from a queue
* Defines how tasks should be processed and provides options for error handling
*/
type TaskHandler = {
/**
* Optional unique identifier for this handler
* Used to identify and unsubscribe specific handlers
* @type {string}
*/
id?: string;
/**
* The handler function to process tasks
* Called for each task dequeued from the queue
* @param task - The task to process
* @param context - Context for acknowledging, rejecting, or extending the task
* @returns {Promise<void>}
*/
handler: (task: Task, context: TaskContext) => Promise<void>;
};
/**
* Configuration options for task providers
* Allows customization of default behavior for task processing
*/
type TaskProviderOptions = {
/**
* Default timeout for task processing in milliseconds
* Tasks exceeding this duration may be requeued or marked as failed
* @type {number}
*/
timeout?: number;
/**
* Default maximum number of retry attempts for failed tasks
* After this many failures, tasks may be sent to dead-letter queue
* @type {number}
*/
retries?: number;
/**
* Name of the dead-letter queue for failed tasks
* If not provided, dead-letter functionality is disabled
* @type {string}
*/
deadLetterQueue?: string;
};
/**
* TaskProvider interface for task queue management
* Handles enqueueing, dequeueing, and lifecycle management of tasks
* Implementations should provide reliable task delivery and acknowledgment
*/
type TaskProvider = {
/**
* Unique identifier for this provider instance
* Used to distinguish between multiple providers
* @type {string}
*/
id: string;
/**
* Default timeout for task processing in milliseconds
* Can be overridden per task or per handler
* @type {number}
*/
timeout: number;
/**
* Default maximum number of retry attempts
* Can be overridden per task
* @type {number}
*/
retries: number;
/**
* Name of the dead-letter queue for failed tasks
* If not provided, dead-letter functionality is disabled
* @type {string}
*/
deadLetterQueue?: string;
/**
* Map of queue names to their registered handlers
* Tracks all active handlers for each queue
* @type {Map<string, TaskHandler[]>}
*/
taskHandlers: Map<string, TaskHandler[]>;
/**
* Enqueue a task to a specific queue for processing
* The task will be delivered to registered handlers for that queue
* @param queue - The queue name to enqueue the task to
* @param task - The task to be enqueued
* @returns {Promise<string>} - the id of the task being queued
*/
enqueue(queue: string, task: EnqueueTask): Promise<string>;
/**
* Register a handler to process tasks from a specific queue
* The handler will be called for each task dequeued from the queue
* @param queue - The queue name to dequeue tasks from
* @param handler - The handler configuration for processing tasks
* @returns {Promise<void>}
*/
dequeue(queue: string, handler: TaskHandler): Promise<void>;
/**
* Unsubscribe a handler from a queue
* Stops the handler from receiving new tasks
* @param queue - The queue name to unsubscribe from
* @param id - Optional handler ID. If not provided, removes all handlers for the queue
* @returns {Promise<void>}
*/
unsubscribe(queue: string, id?: string): Promise<void>;
/**
* Disconnect and clean up the provider
* Stops receiving tasks, closes connections, and releases resources
* Should be called before application shutdown
* @returns {Promise<void>}
*/
disconnect(): Promise<void>;
};
//#endregion
//#region src/memory/message.d.ts
/**
* Configuration options for the memory message provider.
*/
type MemoryMessageProviderOptions = {
/**
* The unique identifier for this provider instance.
* @default "@qified/memory"
*/
id?: string;
};
/**
* In-memory message provider for testing and simple use cases.
* Messages are stored and delivered synchronously in memory without persistence.
*/
declare class MemoryMessageProvider implements MessageProvider {
private _subscriptions;
private _id;
/**
* Creates an instance of MemoryMessageProvider.
* @param {MemoryMessageProviderOptions} options - Optional configuration for the provider.
*/
constructor(options?: MemoryMessageProviderOptions);
/**
* Gets the provider ID for the memory message provider.
* @returns {string} The provider ID.
*/
get id(): string;
/**
* Sets the provider ID for the memory message provider.
* @param {string} id The new provider ID.
*/
set id(id: string);
/**
* Gets the subscriptions map for all topics.
* @returns {Map<string, TopicHandler[]>} The subscriptions map.
*/
get subscriptions(): Map<string, TopicHandler[]>;
/**
* Sets the subscriptions map.
* @param {Map<string, TopicHandler[]>} value The new subscriptions map.
*/
set subscriptions(value: Map<string, TopicHandler[]>);
/**
* Publishes a message to a specified topic.
* All handlers subscribed to the topic will be called synchronously in order.
* @param {string} topic The topic to publish the message to.
* @param {Message} message The message to publish.
* @returns {Promise<void>} A promise that resolves when all handlers have been called.
*/
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**
* Subscribes to a specified topic.
* @param {string} topic The topic to subscribe to.
* @param {TopicHandler} handler The handler to process incoming messages.
* @returns {Promise<void>} A promise that resolves when the subscription is complete.
*/
subscribe(topic: string, handler: TopicHandler): Promise<void>;
/**
* Unsubscribes from a specified topic.
* If an ID is provided, only the handler with that ID is removed.
* If no ID is provided, all handlers for the topic are removed.
* @param {string} topic The topic to unsubscribe from.
* @param {string} [id] Optional identifier for the subscription to remove.
* @returns {Promise<void>} A promise that resolves when the unsubscription is complete.
*/
unsubscribe(topic: string, id?: string): Promise<void>;
/**
* Disconnects and clears all subscriptions.
* @returns {Promise<void>} A promise that resolves when the disconnection is complete.
*/
disconnect(): Promise<void>;
}
//#endregion
//#region src/memory/task.d.ts
/**
* Configuration options for the memory task provider.
*/
type MemoryTaskProviderOptions = TaskProviderOptions & {
/**
* The unique identifier for this provider instance.
* @default "@qified/memory-task"
*/
id?: string;
};
/**
* In-memory task provider for testing and simple use cases.
* Tasks are stored and processed in memory without persistence.
* Supports task acknowledgment, rejection, retry, and timeout handling.
*/
declare class MemoryTaskProvider implements TaskProvider {
private _id;
private _timeout;
private _retries;
private _taskHandlers;
private _queues;
private _processing;
private _deadLetterQueue;
private _taskIdCounter;
private _active;
/**
* Creates an instance of MemoryTaskProvider.
* @param {MemoryTaskProviderOptions} options - Optional configuration for the provider.
*/
constructor(options?: MemoryTaskProviderOptions);
/**
* Gets the provider ID for the memory task provider.
* @returns {string} The provider ID.
*/
get id(): string;
/**
* Sets the provider ID for the memory task provider.
* @param {string} id The new provider ID.
*/
set id(id: string);
/**
* Gets the default timeout for task processing.
* @returns {number} The timeout in milliseconds.
*/
get timeout(): number;
/**
* Sets the default timeout for task processing.
* @param {number} timeout The timeout in milliseconds.
*/
set timeout(timeout: number);
/**
* Gets the default maximum retry attempts.
* @returns {number} The maximum retry attempts.
*/
get retries(): number;
/**
* Sets the default maximum retry attempts.
* @param {number} retries The maximum retry attempts.
*/
set retries(retries: number);
/**
* Gets the task handlers map.
* @returns {Map<string, TaskHandler[]>} The task handlers map.
*/
get taskHandlers(): Map<string, TaskHandler[]>;
/**
* Sets the task handlers map.
* @param {Map<string, TaskHandler[]>} value The new task handlers map.
*/
set taskHandlers(value: Map<string, TaskHandler[]>);
/**
* Generates a unique task ID.
* @returns {string} A unique task ID.
*/
private generateTaskId;
/**
* Enqueues a task to a specific queue.
* Automatically assigns ID and timestamp to the task.
* @param {string} queue - The queue name to enqueue to.
* @param {EnqueueTask} taskData - The task data to enqueue.
* @returns {Promise<string>} The ID of the enqueued task.
*/
enqueue(queue: string, taskData: EnqueueTask): Promise<string>;
/**
* Registers a handler to process tasks from a queue.
* Starts processing any pending tasks in the queue.
* @param {string} queue - The queue name to dequeue from.
* @param {TaskHandler} handler - The handler configuration.
* @returns {Promise<void>}
*/
dequeue(queue: string, handler: TaskHandler): Promise<void>;
/**
* Processes tasks in a queue by delivering them to registered handlers.
* @param {string} queue - The queue name to process.
*/
private processQueue;
/**
* Processes a single task with a handler.
* @param {string} queue - The queue name.
* @param {QueuedTask} queuedTask - The queued task to process.
* @param {TaskHandler} handler - The handler to process the task.
*/
private processTask;
/**
* Removes a task from the queue.
* @param {string} queue - The queue name.
* @param {string} taskId - The task ID to remove.
*/
private removeTask;
/**
* Moves a task to the dead-letter queue.
* @param {string} queue - The original queue name.
* @param {Task} task - The task to move.
*/
private moveToDeadLetter;
/**
* Unsubscribes a handler from a queue.
* @param {string} queue - The queue name to unsubscribe from.
* @param {string} [id] - Optional handler ID. If not provided, removes all handlers.
* @returns {Promise<void>}
*/
unsubscribe(queue: string, id?: string): Promise<void>;
/**
* Disconnects and clears all queues and handlers.
* Stops all task processing.
* @returns {Promise<void>}
*/
disconnect(): Promise<void>;
/**
* Gets all tasks in the dead-letter queue for a specific queue.
* Useful for debugging and monitoring failed tasks.
* @param {string} queue - The queue name.
* @returns {Task[]} Array of tasks in the dead-letter queue.
*/
getDeadLetterTasks(queue: string): Task[];
/**
* Gets the current state of a queue.
* Useful for monitoring and debugging.
* @param {string} queue - The queue name.
* @returns {Object} Queue statistics.
*/
getQueueStats(queue: string): {
waiting: number;
processing: number;
deadLetter: number;
};
}
//#endregion
//#region src/index.d.ts
/**
* Standard events emitted by Qified.
*/
declare enum QifiedEvents {
error = "error",
info = "info",
warn = "warn",
publish = "publish",
subscribe = "subscribe",
unsubscribeMessage = "unsubscribeMessage",
enqueue = "enqueue",
dequeue = "dequeue",
unsubscribeTask = "unsubscribeTask",
disconnect = "disconnect"
}
/**
* Hook event names for before/after lifecycle hooks.
* Before hooks receive a mutable context object that can be modified.
* After hooks receive the final context after the operation completes.
*/
declare enum QifiedHooks {
beforeSubscribe = "before:subscribe",
afterSubscribe = "after:subscribe",
beforePublish = "before:publish",
afterPublish = "after:publish",
beforeUnsubscribeMessage = "before:unsubscribeMessage",
afterUnsubscribeMessage = "after:unsubscribeMessage",
beforeEnqueue = "before:enqueue",
afterEnqueue = "after:enqueue",
beforeDequeue = "before:dequeue",
afterDequeue = "after:dequeue",
beforeUnsubscribeTask = "before:unsubscribeTask",
afterUnsubscribeTask = "after:unsubscribeTask",
beforeDisconnect = "before:disconnect",
afterDisconnect = "after:disconnect"
}
type QifiedOptions = {
/**
* The message providers to use.
*/
messageProviders?: MessageProvider | MessageProvider[];
/**
* The task providers to use.
*/
taskProviders?: TaskProvider | TaskProvider[];
} & HookifiedOptions;
declare class Qified extends Hookified {
private _messageProviders;
private _taskProviders;
/**
* Creates an instance of Qified.
* @param {QifiedOptions} options - Optional configuration for Qified.
*/
constructor(options?: QifiedOptions);
/**
* Gets or sets the message providers.
* @returns {MessageProvider[]} The array of message providers.
*/
get messageProviders(): MessageProvider[];
/**
* Sets the message providers.
* @param {MessageProvider[]} providers - The array of message providers to set.
*/
set messageProviders(providers: MessageProvider[]);
/**
* Gets or sets the task providers.
* @returns {TaskProvider[]} The array of task providers.
*/
get taskProviders(): TaskProvider[];
/**
* Sets the task providers.
* @param {TaskProvider[]} providers - The array of task providers to set.
*/
set taskProviders(providers: TaskProvider[]);
/**
* Subscribes to a topic. If you have multiple message providers, it will subscribe to the topic on all of them.
* @param {string} topic - The topic to subscribe to.
* @param {TopicHandler} handler - The handler to call when a message is published to the topic.
*/
subscribe(topic: string, handler: TopicHandler): Promise<void>;
/**
* Publishes a message to a topic. If you have multiple message providers, it will publish the message to all of them.
* @param {string} topic - The topic to publish to.
* @param {Message} message - The message to publish.
*/
publish(topic: string, message: Omit<Message, "providerId">): Promise<void>;
/**
* Unsubscribes a message handler from a topic. If you have multiple message providers, it will unsubscribe from the topic on all of them.
* If an ID is provided, it will unsubscribe only that handler. If no ID is provided, it will unsubscribe all handlers for the topic.
* @param topic - The topic to unsubscribe from.
* @param id - The optional ID of the handler to unsubscribe. If not provided, all handlers for the topic will be unsubscribed.
*/
unsubscribeMessage(topic: string, id?: string): Promise<void>;
/**
* Enqueues a task to a queue. If you have multiple task providers, it will enqueue the task on all of them.
* @param {string} queue - The queue to enqueue to.
* @param {EnqueueTask} task - The task to enqueue.
* @returns {Promise<string[]>} The ids assigned to the task by each provider, in provider order.
*/
enqueue(queue: string, task: EnqueueTask): Promise<string[]>;
/**
* Registers a handler to dequeue tasks from a queue. If you have multiple task providers, it will register the handler on all of them.
* @param {string} queue - The queue to dequeue from.
* @param {TaskHandler} handler - The handler to call when a task is available.
*/
dequeue(queue: string, handler: TaskHandler): Promise<void>;
/**
* Unsubscribes a task handler from a queue. If you have multiple task providers, it will unsubscribe on all of them.
* If an ID is provided, it will unsubscribe only that handler. If no ID is provided, it will unsubscribe all handlers for the queue.
* @param queue - The queue to unsubscribe from.
* @param id - The optional ID of the handler to unsubscribe. If not provided, all handlers for the queue will be unsubscribed.
*/
unsubscribeTask(queue: string, id?: string): Promise<void>;
/**
* Disconnects from all providers.
* This method will call the `disconnect` method on each message provider and task provider,
* then clear both provider arrays.
*/
disconnect(): Promise<void>;
}
//#endregion
export { type EnqueueTask, MemoryMessageProvider, MemoryTaskProvider, type Message, type MessageProvider, Qified, QifiedEvents, QifiedHooks, QifiedOptions, type Task, type TaskContext, type TaskHandler, type TaskProvider, type TaskProviderOptions, type TopicHandler };

657
node_modules/qified/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,657 @@
import { Hookified } from "hookified";
/**
* In-memory message provider for testing and simple use cases.
* Messages are stored and delivered synchronously in memory without persistence.
*/
var MemoryMessageProvider = class {
_subscriptions;
_id;
/**
* Creates an instance of MemoryMessageProvider.
* @param {MemoryMessageProviderOptions} options - Optional configuration for the provider.
*/
constructor(options) {
this._subscriptions = /* @__PURE__ */ new Map();
this._id = options?.id ?? "@qified/memory";
}
/**
* Gets the provider ID for the memory message provider.
* @returns {string} The provider ID.
*/
get id() {
return this._id;
}
/**
* Sets the provider ID for the memory message provider.
* @param {string} id The new provider ID.
*/
set id(id) {
this._id = id;
}
/**
* Gets the subscriptions map for all topics.
* @returns {Map<string, TopicHandler[]>} The subscriptions map.
*/
get subscriptions() {
return this._subscriptions;
}
/**
* Sets the subscriptions map.
* @param {Map<string, TopicHandler[]>} value The new subscriptions map.
*/
set subscriptions(value) {
this._subscriptions = value;
}
/**
* Publishes a message to a specified topic.
* All handlers subscribed to the topic will be called synchronously in order.
* @param {string} topic The topic to publish the message to.
* @param {Message} message The message to publish.
* @returns {Promise<void>} A promise that resolves when all handlers have been called.
*/
async publish(topic, message) {
const messageWithProvider = {
...message,
providerId: this._id
};
const subscriptions = this._subscriptions.get(topic) ?? [];
for (const subscription of subscriptions) await subscription.handler(messageWithProvider);
}
/**
* Subscribes to a specified topic.
* @param {string} topic The topic to subscribe to.
* @param {TopicHandler} handler The handler to process incoming messages.
* @returns {Promise<void>} A promise that resolves when the subscription is complete.
*/
async subscribe(topic, handler) {
if (!this._subscriptions.has(topic)) this._subscriptions.set(topic, []);
this._subscriptions.get(topic)?.push(handler);
}
/**
* Unsubscribes from a specified topic.
* If an ID is provided, only the handler with that ID is removed.
* If no ID is provided, all handlers for the topic are removed.
* @param {string} topic The topic to unsubscribe from.
* @param {string} [id] Optional identifier for the subscription to remove.
* @returns {Promise<void>} A promise that resolves when the unsubscription is complete.
*/
async unsubscribe(topic, id) {
if (id) {
const subscriptions = this._subscriptions.get(topic);
if (subscriptions) this._subscriptions.set(topic, subscriptions.filter((sub) => sub.id !== id));
} else this._subscriptions.delete(topic);
}
/**
* Disconnects and clears all subscriptions.
* @returns {Promise<void>} A promise that resolves when the disconnection is complete.
*/
async disconnect() {
this._subscriptions.clear();
}
};
/**
* In-memory task provider for testing and simple use cases.
* Tasks are stored and processed in memory without persistence.
* Supports task acknowledgment, rejection, retry, and timeout handling.
*/
var MemoryTaskProvider = class {
_id;
_timeout;
_retries;
_taskHandlers;
_queues;
_processing;
_deadLetterQueue;
_taskIdCounter = 0;
_active = true;
/**
* Creates an instance of MemoryTaskProvider.
* @param {MemoryTaskProviderOptions} options - Optional configuration for the provider.
*/
constructor(options) {
this._id = options?.id ?? "@qified/memory";
this._timeout = options?.timeout ?? 3e4;
this._retries = options?.retries ?? 3;
this._taskHandlers = /* @__PURE__ */ new Map();
this._queues = /* @__PURE__ */ new Map();
this._processing = /* @__PURE__ */ new Map();
this._deadLetterQueue = /* @__PURE__ */ new Map();
}
/**
* Gets the provider ID for the memory task provider.
* @returns {string} The provider ID.
*/
get id() {
return this._id;
}
/**
* Sets the provider ID for the memory task provider.
* @param {string} id The new provider ID.
*/
set id(id) {
this._id = id;
}
/**
* Gets the default timeout for task processing.
* @returns {number} The timeout in milliseconds.
*/
get timeout() {
return this._timeout;
}
/**
* Sets the default timeout for task processing.
* @param {number} timeout The timeout in milliseconds.
*/
set timeout(timeout) {
this._timeout = timeout;
}
/**
* Gets the default maximum retry attempts.
* @returns {number} The maximum retry attempts.
*/
get retries() {
return this._retries;
}
/**
* Sets the default maximum retry attempts.
* @param {number} retries The maximum retry attempts.
*/
set retries(retries) {
this._retries = retries;
}
/**
* Gets the task handlers map.
* @returns {Map<string, TaskHandler[]>} The task handlers map.
*/
get taskHandlers() {
return this._taskHandlers;
}
/**
* Sets the task handlers map.
* @param {Map<string, TaskHandler[]>} value The new task handlers map.
*/
set taskHandlers(value) {
this._taskHandlers = value;
}
/**
* Generates a unique task ID.
* @returns {string} A unique task ID.
*/
generateTaskId() {
return `task-${Date.now()}-${++this._taskIdCounter}`;
}
/**
* Enqueues a task to a specific queue.
* Automatically assigns ID and timestamp to the task.
* @param {string} queue - The queue name to enqueue to.
* @param {EnqueueTask} taskData - The task data to enqueue.
* @returns {Promise<string>} The ID of the enqueued task.
*/
async enqueue(queue, taskData) {
if (!this._active) throw new Error("TaskProvider has been disconnected");
const task = {
id: this.generateTaskId(),
timestamp: Date.now(),
...taskData
};
const queuedTask = {
task,
attempt: 0,
deadlineAt: 0,
processing: false
};
if (!this._queues.has(queue)) this._queues.set(queue, []);
this._queues.get(queue)?.push(queuedTask);
await this.processQueue(queue);
return task.id;
}
/**
* Registers a handler to process tasks from a queue.
* Starts processing any pending tasks in the queue.
* @param {string} queue - The queue name to dequeue from.
* @param {TaskHandler} handler - The handler configuration.
* @returns {Promise<void>}
*/
async dequeue(queue, handler) {
if (!this._active) throw new Error("TaskProvider has been disconnected");
if (!this._taskHandlers.has(queue)) this._taskHandlers.set(queue, []);
this._taskHandlers.get(queue)?.push(handler);
await this.processQueue(queue);
}
/**
* Processes tasks in a queue by delivering them to registered handlers.
* @param {string} queue - The queue name to process.
*/
async processQueue(queue) {
/* v8 ignore next -- @preserve */
if (!this._active) return;
const handlers = this._taskHandlers.get(queue);
if (!handlers || handlers.length === 0) return;
const queuedTasks = this._queues.get(queue);
if (!queuedTasks || queuedTasks.length === 0) return;
const processingSet = this._processing.get(queue) ?? /* @__PURE__ */ new Set();
this._processing.set(queue, processingSet);
for (const queuedTask of queuedTasks) {
if (queuedTask.processing || processingSet.has(queuedTask.task.id)) continue;
queuedTask.processing = true;
processingSet.add(queuedTask.task.id);
for (const handler of handlers) this.processTask(queue, queuedTask, handler);
}
}
/**
* Processes a single task with a handler.
* @param {string} queue - The queue name.
* @param {QueuedTask} queuedTask - The queued task to process.
* @param {TaskHandler} handler - The handler to process the task.
*/
async processTask(queue, queuedTask, handler) {
const { task } = queuedTask;
const maxRetries = task.maxRetries ?? this._retries;
const timeout = task.timeout ?? this._timeout;
queuedTask.attempt++;
queuedTask.deadlineAt = Date.now() + timeout;
let acknowledged = false;
let rejected = false;
const context = {
ack: async () => {
if (acknowledged || rejected) return;
acknowledged = true;
await this.removeTask(queue, task.id);
},
reject: async (requeue = true) => {
if (acknowledged || rejected) return;
rejected = true;
if (requeue && queuedTask.attempt < maxRetries) {
queuedTask.processing = false;
this._processing.get(queue)?.delete(task.id);
setTimeout(() => {
this.processQueue(queue);
}, 100);
} else {
await this.moveToDeadLetter(queue, task);
await this.removeTask(queue, task.id);
}
},
extend: async (ttl) => {
if (acknowledged || rejected) return;
queuedTask.deadlineAt = Date.now() + ttl;
if (queuedTask.timeoutHandle) clearTimeout(queuedTask.timeoutHandle);
/* v8 ignore next -- @preserve */
queuedTask.timeoutHandle = setTimeout(() => {
if (!acknowledged && !rejected) context.reject(true);
}, ttl);
},
metadata: {
attempt: queuedTask.attempt,
maxRetries
}
};
queuedTask.timeoutHandle = setTimeout(() => {
if (!acknowledged && !rejected) context.reject(true);
}, timeout);
try {
await handler.handler(task, context);
if (!acknowledged && !rejected) await context.ack();
} catch (_error) {
if (!acknowledged && !rejected) await context.reject(true);
} finally {
if (queuedTask.timeoutHandle) clearTimeout(queuedTask.timeoutHandle);
}
}
/**
* Removes a task from the queue.
* @param {string} queue - The queue name.
* @param {string} taskId - The task ID to remove.
*/
async removeTask(queue, taskId) {
const queuedTasks = this._queues.get(queue);
if (queuedTasks) {
const index = queuedTasks.findIndex((qt) => qt.task.id === taskId);
if (index !== -1) queuedTasks.splice(index, 1);
}
this._processing.get(queue)?.delete(taskId);
}
/**
* Moves a task to the dead-letter queue.
* @param {string} queue - The original queue name.
* @param {Task} task - The task to move.
*/
async moveToDeadLetter(queue, task) {
const dlqKey = `${queue}:dead-letter`;
if (!this._deadLetterQueue.has(dlqKey)) this._deadLetterQueue.set(dlqKey, []);
this._deadLetterQueue.get(dlqKey)?.push(task);
}
/**
* Unsubscribes a handler from a queue.
* @param {string} queue - The queue name to unsubscribe from.
* @param {string} [id] - Optional handler ID. If not provided, removes all handlers.
* @returns {Promise<void>}
*/
async unsubscribe(queue, id) {
if (id) {
const handlers = this._taskHandlers.get(queue);
if (handlers) this._taskHandlers.set(queue, handlers.filter((h) => h.id !== id));
} else this._taskHandlers.delete(queue);
}
/**
* Disconnects and clears all queues and handlers.
* Stops all task processing.
* @returns {Promise<void>}
*/
async disconnect() {
this._active = false;
for (const queuedTasks of this._queues.values()) for (const queuedTask of queuedTasks) if (queuedTask.timeoutHandle) clearTimeout(queuedTask.timeoutHandle);
this._taskHandlers.clear();
this._queues.clear();
this._processing.clear();
this._deadLetterQueue.clear();
}
/**
* Gets all tasks in the dead-letter queue for a specific queue.
* Useful for debugging and monitoring failed tasks.
* @param {string} queue - The queue name.
* @returns {Task[]} Array of tasks in the dead-letter queue.
*/
getDeadLetterTasks(queue) {
const dlqKey = `${queue}:dead-letter`;
return this._deadLetterQueue.get(dlqKey) ?? [];
}
/**
* Gets the current state of a queue.
* Useful for monitoring and debugging.
* @param {string} queue - The queue name.
* @returns {Object} Queue statistics.
*/
getQueueStats(queue) {
const queuedTasks = this._queues.get(queue) ?? [];
const processing = this._processing.get(queue)?.size ?? 0;
const waiting = queuedTasks.filter((qt) => !qt.processing).length;
const dlqKey = `${queue}:dead-letter`;
return {
waiting,
processing,
deadLetter: this._deadLetterQueue.get(dlqKey)?.length ?? 0
};
}
};
//#endregion
//#region src/index.ts
/**
* Standard events emitted by Qified.
*/
let QifiedEvents = /* @__PURE__ */ function(QifiedEvents) {
QifiedEvents["error"] = "error";
QifiedEvents["info"] = "info";
QifiedEvents["warn"] = "warn";
QifiedEvents["publish"] = "publish";
QifiedEvents["subscribe"] = "subscribe";
QifiedEvents["unsubscribeMessage"] = "unsubscribeMessage";
QifiedEvents["enqueue"] = "enqueue";
QifiedEvents["dequeue"] = "dequeue";
QifiedEvents["unsubscribeTask"] = "unsubscribeTask";
QifiedEvents["disconnect"] = "disconnect";
return QifiedEvents;
}({});
/**
* Hook event names for before/after lifecycle hooks.
* Before hooks receive a mutable context object that can be modified.
* After hooks receive the final context after the operation completes.
*/
let QifiedHooks = /* @__PURE__ */ function(QifiedHooks) {
QifiedHooks["beforeSubscribe"] = "before:subscribe";
QifiedHooks["afterSubscribe"] = "after:subscribe";
QifiedHooks["beforePublish"] = "before:publish";
QifiedHooks["afterPublish"] = "after:publish";
QifiedHooks["beforeUnsubscribeMessage"] = "before:unsubscribeMessage";
QifiedHooks["afterUnsubscribeMessage"] = "after:unsubscribeMessage";
QifiedHooks["beforeEnqueue"] = "before:enqueue";
QifiedHooks["afterEnqueue"] = "after:enqueue";
QifiedHooks["beforeDequeue"] = "before:dequeue";
QifiedHooks["afterDequeue"] = "after:dequeue";
QifiedHooks["beforeUnsubscribeTask"] = "before:unsubscribeTask";
QifiedHooks["afterUnsubscribeTask"] = "after:unsubscribeTask";
QifiedHooks["beforeDisconnect"] = "before:disconnect";
QifiedHooks["afterDisconnect"] = "after:disconnect";
return QifiedHooks;
}({});
var Qified = class extends Hookified {
_messageProviders = [];
_taskProviders = [];
/**
* Creates an instance of Qified.
* @param {QifiedOptions} options - Optional configuration for Qified.
*/
constructor(options) {
super(options);
if (options?.messageProviders) if (Array.isArray(options?.messageProviders)) this._messageProviders = options.messageProviders;
else this._messageProviders = [options?.messageProviders];
if (options?.taskProviders) if (Array.isArray(options?.taskProviders)) this._taskProviders = options.taskProviders;
else this._taskProviders = [options?.taskProviders];
}
/**
* Gets or sets the message providers.
* @returns {MessageProvider[]} The array of message providers.
*/
get messageProviders() {
return this._messageProviders;
}
/**
* Sets the message providers.
* @param {MessageProvider[]} providers - The array of message providers to set.
*/
set messageProviders(providers) {
this._messageProviders = providers;
}
/**
* Gets or sets the task providers.
* @returns {TaskProvider[]} The array of task providers.
*/
get taskProviders() {
return this._taskProviders;
}
/**
* Sets the task providers.
* @param {TaskProvider[]} providers - The array of task providers to set.
*/
set taskProviders(providers) {
this._taskProviders = providers;
}
/**
* Subscribes to a topic. If you have multiple message providers, it will subscribe to the topic on all of them.
* @param {string} topic - The topic to subscribe to.
* @param {TopicHandler} handler - The handler to call when a message is published to the topic.
*/
async subscribe(topic, handler) {
try {
const context = {
topic,
handler
};
await this.hook("before:subscribe", context);
const promises = this._messageProviders.map(async (provider) => provider.subscribe(context.topic, context.handler));
await Promise.all(promises);
await this.hook("after:subscribe", {
topic: context.topic,
handler: context.handler
});
this.emit("subscribe", {
topic: context.topic,
handler: context.handler
});
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
/**
* Publishes a message to a topic. If you have multiple message providers, it will publish the message to all of them.
* @param {string} topic - The topic to publish to.
* @param {Message} message - The message to publish.
*/
async publish(topic, message) {
try {
const context = {
topic,
message
};
await this.hook("before:publish", context);
const promises = this._messageProviders.map(async (provider) => provider.publish(context.topic, context.message));
await Promise.all(promises);
await this.hook("after:publish", {
topic: context.topic,
message: context.message
});
this.emit("publish", {
topic: context.topic,
message: context.message
});
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
/**
* Unsubscribes a message handler from a topic. If you have multiple message providers, it will unsubscribe from the topic on all of them.
* If an ID is provided, it will unsubscribe only that handler. If no ID is provided, it will unsubscribe all handlers for the topic.
* @param topic - The topic to unsubscribe from.
* @param id - The optional ID of the handler to unsubscribe. If not provided, all handlers for the topic will be unsubscribed.
*/
async unsubscribeMessage(topic, id) {
try {
const context = {
topic,
id
};
await this.hook("before:unsubscribeMessage", context);
const promises = this._messageProviders.map(async (provider) => provider.unsubscribe(context.topic, context.id));
await Promise.all(promises);
await this.hook("after:unsubscribeMessage", {
topic: context.topic,
id: context.id
});
this.emit("unsubscribeMessage", {
topic: context.topic,
id: context.id
});
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
/**
* Enqueues a task to a queue. If you have multiple task providers, it will enqueue the task on all of them.
* @param {string} queue - The queue to enqueue to.
* @param {EnqueueTask} task - The task to enqueue.
* @returns {Promise<string[]>} The ids assigned to the task by each provider, in provider order.
*/
async enqueue(queue, task) {
try {
const context = {
queue,
task
};
await this.hook("before:enqueue", context);
const promises = this._taskProviders.map(async (provider) => provider.enqueue(context.queue, context.task));
const ids = await Promise.all(promises);
await this.hook("after:enqueue", {
queue: context.queue,
task: context.task,
ids
});
this.emit("enqueue", {
queue: context.queue,
task: context.task,
ids
});
return ids;
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
/* v8 ignore next -- @preserve */
return [];
}
}
/**
* Registers a handler to dequeue tasks from a queue. If you have multiple task providers, it will register the handler on all of them.
* @param {string} queue - The queue to dequeue from.
* @param {TaskHandler} handler - The handler to call when a task is available.
*/
async dequeue(queue, handler) {
try {
const context = {
queue,
handler
};
await this.hook("before:dequeue", context);
const promises = this._taskProviders.map(async (provider) => provider.dequeue(context.queue, context.handler));
await Promise.all(promises);
await this.hook("after:dequeue", {
queue: context.queue,
handler: context.handler
});
this.emit("dequeue", {
queue: context.queue,
handler: context.handler
});
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
/**
* Unsubscribes a task handler from a queue. If you have multiple task providers, it will unsubscribe on all of them.
* If an ID is provided, it will unsubscribe only that handler. If no ID is provided, it will unsubscribe all handlers for the queue.
* @param queue - The queue to unsubscribe from.
* @param id - The optional ID of the handler to unsubscribe. If not provided, all handlers for the queue will be unsubscribed.
*/
async unsubscribeTask(queue, id) {
try {
const context = {
queue,
id
};
await this.hook("before:unsubscribeTask", context);
const promises = this._taskProviders.map(async (provider) => provider.unsubscribe(context.queue, context.id));
await Promise.all(promises);
await this.hook("after:unsubscribeTask", {
queue: context.queue,
id: context.id
});
this.emit("unsubscribeTask", {
queue: context.queue,
id: context.id
});
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
/**
* Disconnects from all providers.
* This method will call the `disconnect` method on each message provider and task provider,
* then clear both provider arrays.
*/
async disconnect() {
try {
const context = {
messageProviderCount: this._messageProviders.length,
taskProviderCount: this._taskProviders.length
};
await this.hook("before:disconnect", context);
const promises = [...this._messageProviders.map(async (provider) => provider.disconnect()), ...this._taskProviders.map(async (provider) => provider.disconnect())];
await Promise.all(promises);
this._messageProviders = [];
this._taskProviders = [];
await this.hook("after:disconnect", {
messageProviderCount: context.messageProviderCount,
taskProviderCount: context.taskProviderCount
});
this.emit("disconnect");
} catch (error) {
/* v8 ignore next -- @preserve */
this.emit("error", error);
}
}
};
//#endregion
export { MemoryMessageProvider, MemoryTaskProvider, Qified, QifiedEvents, QifiedHooks };

19
node_modules/qified/node_modules/hookified/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,19 @@
MIT License & © Jared Wray
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

1792
node_modules/qified/node_modules/hookified/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,951 @@
var Hookified = (function(exports) {
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region \0@oxc-project+runtime@0.127.0/helpers/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
return typeof o;
} : function(o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
//#endregion
//#region \0@oxc-project+runtime@0.127.0/helpers/toPrimitive.js
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
//#endregion
//#region \0@oxc-project+runtime@0.127.0/helpers/toPropertyKey.js
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
//#endregion
//#region \0@oxc-project+runtime@0.127.0/helpers/defineProperty.js
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
//#endregion
//#region src/eventified.ts
const ERROR_EVENT = "error";
var Eventified = class {
constructor(options) {
_defineProperty(this, "_eventListeners", void 0);
_defineProperty(this, "_maxListeners", void 0);
_defineProperty(this, "_eventLogger", void 0);
_defineProperty(this, "_throwOnEmitError", false);
_defineProperty(this, "_throwOnEmptyListeners", true);
this._eventListeners = /* @__PURE__ */ new Map();
this._maxListeners = 0;
this._eventLogger = options?.eventLogger;
if (options?.throwOnEmitError !== void 0) this._throwOnEmitError = options.throwOnEmitError;
if (options?.throwOnEmptyListeners !== void 0) this._throwOnEmptyListeners = options.throwOnEmptyListeners;
}
/**
* Gets the event logger
* @returns {Logger}
*/
get eventLogger() {
return this._eventLogger;
}
/**
* Sets the event logger
* @param {Logger} eventLogger
*/
set eventLogger(eventLogger) {
this._eventLogger = eventLogger;
}
/**
* Gets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnEmitError() {
return this._throwOnEmitError;
}
/**
* Sets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnEmitError(value) {
this._throwOnEmitError = value;
}
/**
* Gets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @returns {boolean}
*/
get throwOnEmptyListeners() {
return this._throwOnEmptyListeners;
}
/**
* Sets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @param {boolean} value
*/
set throwOnEmptyListeners(value) {
this._throwOnEmptyListeners = value;
}
/**
* Adds a handler function for a specific event that will run only once
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
once(eventName, listener) {
const onceListener = (...arguments_) => {
this.off(eventName, onceListener);
listener(...arguments_);
};
this.on(eventName, onceListener);
return this;
}
/**
* Gets the number of listeners for a specific event. If no event is provided, it returns the total number of listeners
* @param {string} eventName The event name. Not required
* @returns {number} The number of listeners
*/
listenerCount(eventName) {
if (eventName === void 0) {
let count = 0;
for (const entry of this._eventListeners.values()) count += typeof entry === "function" ? 1 : entry.length;
return count;
}
const entry = this._eventListeners.get(eventName);
if (entry === void 0) return 0;
return typeof entry === "function" ? 1 : entry.length;
}
/**
* Gets an array of event names
* @returns {Array<string | symbol>} An array of event names
*/
eventNames() {
return [...this._eventListeners.keys()];
}
/**
* Gets an array of listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
rawListeners(event) {
if (event === void 0) return this.getAllListeners();
const entry = this._eventListeners.get(event);
if (entry === void 0) return [];
return typeof entry === "function" ? [entry] : entry;
}
/**
* Prepends a listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependListener(eventName, listener) {
const existing = this._eventListeners.get(eventName);
if (existing === void 0) this._eventListeners.set(eventName, listener);
else if (typeof existing === "function") this._eventListeners.set(eventName, [listener, existing]);
else existing.unshift(listener);
return this;
}
/**
* Prepends a one-time listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependOnceListener(eventName, listener) {
const onceListener = (...arguments_) => {
this.off(eventName, onceListener);
listener(...arguments_);
};
this.prependListener(eventName, onceListener);
return this;
}
/**
* Gets the maximum number of listeners that can be added for a single event
* @returns {number} The maximum number of listeners
*/
maxListeners() {
return this._maxListeners;
}
/**
* Adds a listener for a specific event. It is an alias for the on() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
addListener(event, listener) {
this.on(event, listener);
return this;
}
/**
* Adds a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
on(event, listener) {
const existing = this._eventListeners.get(event);
if (existing === void 0) {
this._eventListeners.set(event, listener);
return this;
}
if (typeof existing === "function") {
const arr = [existing, listener];
this._eventListeners.set(event, arr);
if (this._maxListeners > 0 && arr.length > this._maxListeners) console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${arr.length} ${event} listeners added. Use setMaxListeners() to increase limit.`);
} else {
existing.push(listener);
if (this._maxListeners > 0 && existing.length > this._maxListeners) console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${existing.length} ${event} listeners added. Use setMaxListeners() to increase limit.`);
}
return this;
}
/**
* Removes a listener for a specific event. It is an alias for the off() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeListener(event, listener) {
this.off(event, listener);
return this;
}
/**
* Removes a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
off(event, listener) {
const entry = this._eventListeners.get(event);
if (entry === void 0) return this;
if (typeof entry === "function") {
if (entry === listener) this._eventListeners.delete(event);
return this;
}
const index = entry.indexOf(listener);
if (index !== -1) if (entry.length === 2) this._eventListeners.set(event, entry[1 - index]);
else if (entry.length === 1) this._eventListeners.delete(event);
else entry.splice(index, 1);
return this;
}
/**
* Calls all listeners for a specific event
* @param {string | symbol} event
* @param arguments_ The arguments to pass to the listeners
* @returns {boolean} Returns true if the event had listeners, false otherwise
*/
emit(event, ...arguments_) {
let result = false;
const entry = this._eventListeners.get(event);
const argumentLength = arguments_.length;
if (entry !== void 0) {
if (typeof entry === "function") if (argumentLength === 1) entry(arguments_[0]);
else if (argumentLength === 2) entry(arguments_[0], arguments_[1]);
else entry(...arguments_);
else {
const len = entry.length;
for (let i = 0; i < len; i++) if (argumentLength === 1) entry[i](arguments_[0]);
else if (argumentLength === 2) entry[i](arguments_[0], arguments_[1]);
else entry[i](...arguments_);
}
result = true;
}
if (this._eventLogger) this.sendToEventLogger(event, arguments_);
if (!result && event === ERROR_EVENT) {
const error = arguments_[0] instanceof Error ? arguments_[0] : /* @__PURE__ */ new Error(`${arguments_[0]}`);
if (this._throwOnEmitError || this._throwOnEmptyListeners) throw error;
}
return result;
}
/**
* Gets all listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
listeners(event) {
const entry = this._eventListeners.get(event);
if (entry === void 0) return [];
return typeof entry === "function" ? [entry] : entry;
}
/**
* Removes all listeners for a specific event. If no event is provided, it removes all listeners
* @param {string} [event] (Optional) The event name
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeAllListeners(event) {
if (event !== void 0) this._eventListeners.delete(event);
else this._eventListeners.clear();
return this;
}
/**
* Sets the maximum number of listeners that can be added for a single event
* @param {number} n The maximum number of listeners
* @returns {void}
*/
setMaxListeners(n) {
this._maxListeners = n < 0 ? 0 : n;
}
/**
* Gets all listeners
* @returns {EventListener[]} An array of listeners
*/
getAllListeners() {
const result = [];
for (const entry of this._eventListeners.values()) if (typeof entry === "function") result.push(entry);
else for (let i = 0; i < entry.length; i++) result.push(entry[i]);
return result;
}
/**
* Sends a log message using the configured logger based on the event name
* @param {string | symbol} eventName - The event name that determines the log level
* @param {unknown} data - The data to log
*/
sendToEventLogger(eventName, data) {
/* v8 ignore next 3 -- @preserve: guarded by caller */
if (!this._eventLogger) return;
let message;
/* v8 ignore next -- @preserve */
if (typeof data === "string") message = data;
else if (Array.isArray(data) && data.length > 0 && data[0] instanceof Error) message = data[0].message;
else if (data instanceof Error) message = data.message;
else if (Array.isArray(data) && data.length > 0 && typeof data[0]?.message === "string") message = data[0].message;
else message = JSON.stringify(data);
switch (eventName) {
case "error":
this._eventLogger.error?.(message, {
event: eventName,
data
});
break;
case "warn":
this._eventLogger.warn?.(message, {
event: eventName,
data
});
break;
case "trace":
this._eventLogger.trace?.(message, {
event: eventName,
data
});
break;
case "debug":
this._eventLogger.debug?.(message, {
event: eventName,
data
});
break;
case "fatal":
this._eventLogger.fatal?.(message, {
event: eventName,
data
});
break;
default:
this._eventLogger.info?.(message, {
event: eventName,
data
});
break;
}
}
};
//#endregion
//#region src/hooks/hook.ts
/**
* Concrete implementation of the IHook interface.
* Provides a convenient class-based way to create hook entries.
*/
var Hook = class {
/**
* Creates a new Hook instance
* @param {string} event - The event name for the hook
* @param {HookFn} handler - The handler function for the hook
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, handler, id) {
_defineProperty(this, "id", void 0);
_defineProperty(this, "event", void 0);
_defineProperty(this, "handler", void 0);
this.id = id;
this.event = event;
this.handler = handler;
}
};
//#endregion
//#region src/hooks/parallel-hook.ts
/**
* A ParallelHook fans a single invocation out to many registered hook
* functions concurrently via Promise.allSettled, then calls a final
* handler with the aggregated results — including failures — keyed by
* the hook function reference for direct lookup. Each hook receives only
* the original arguments; hooks do not see each other's results.
*
* Implements IHook for compatibility with Hookified.onHook(); the final
* handler is called regardless of whether the parallel hook is invoked
* directly or through Hookified.hook().
*
* Generics tighten the per-hook signature when every hook in the set
* accepts the same `initialArgs` and returns the same result type.
* Both default to `any` for backwards compatibility.
*
* @template TArgs - The shape of `initialArgs` passed to every hook
* @template TResult - The result type each hook returns
*/
var ParallelHook = class {
/**
* Creates a new ParallelHook instance
* @param {string} event - The event name for the hook
* @param {ParallelHookFinalFn<TArgs, TResult>} finalHandler - Called once with `{ initialArgs, results }` after all parallel hooks settle
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, finalHandler, id) {
_defineProperty(this, "id", void 0);
_defineProperty(this, "event", void 0);
_defineProperty(this, "handler", void 0);
_defineProperty(this, "hooks", void 0);
_defineProperty(this, "_finalHandler", void 0);
this.id = id;
this.event = event;
this.hooks = [];
this._finalHandler = finalHandler;
this.handler = async (...arguments_) => {
const initialArgs = arguments_.length === 1 ? arguments_[0] : arguments_;
const snapshot = [...this.hooks];
const settled = await Promise.allSettled(snapshot.map((hook) => Promise.resolve().then(() => hook({ initialArgs }))));
const results = /* @__PURE__ */ new Map();
snapshot.forEach((hook, index) => {
const outcome = settled[index];
results.set(hook, outcome.status === "fulfilled" ? {
status: "fulfilled",
result: outcome.value
} : {
status: "rejected",
reason: outcome.reason
});
});
await this._finalHandler({
initialArgs,
results
});
};
}
/**
* Adds a hook function to the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to add
*/
addHook(hook) {
this.hooks.push(hook);
}
/**
* Removes a specific hook function from the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook) {
const index = this.hooks.indexOf(hook);
if (index !== -1) {
this.hooks.splice(index, 1);
return true;
}
return false;
}
};
//#endregion
//#region src/hooks/waterfall-hook.ts
/**
* A WaterfallHook chains multiple hook functions sequentially,
* where each hook receives a context with the previous result,
* initial arguments, and accumulated results. After all hooks
* have executed, the final handler receives the transformed result.
* Implements IHook for compatibility with Hookified.onHook().
*/
var WaterfallHook = class {
/**
* Creates a new WaterfallHook instance
* @param {string} event - The event name for the hook
* @param {WaterfallHookFn} finalHandler - The final handler function that receives the transformed result
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, finalHandler, id) {
_defineProperty(this, "id", void 0);
_defineProperty(this, "event", void 0);
_defineProperty(this, "handler", void 0);
_defineProperty(this, "hooks", void 0);
_defineProperty(this, "_finalHandler", void 0);
this.id = id;
this.event = event;
this.hooks = [];
this._finalHandler = finalHandler;
this.handler = async (...arguments_) => {
const initialArgs = arguments_.length === 1 ? arguments_[0] : arguments_;
const results = [];
for (const hook of this.hooks) {
const result = await hook({
initialArgs,
results: [...results]
});
results.push({
hook,
result
});
}
await this._finalHandler({
initialArgs,
results: [...results]
});
};
}
/**
* Adds a hook function to the end of the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to add
*/
addHook(hook) {
this.hooks.push(hook);
}
/**
* Removes a specific hook function from the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook) {
const index = this.hooks.indexOf(hook);
if (index !== -1) {
this.hooks.splice(index, 1);
return true;
}
return false;
}
};
//#endregion
//#region src/index.ts
var Hookified = class extends Eventified {
constructor(options) {
super({
eventLogger: options?.eventLogger,
throwOnEmitError: options?.throwOnEmitError,
throwOnEmptyListeners: options?.throwOnEmptyListeners
});
_defineProperty(this, "_hooks", void 0);
_defineProperty(this, "_throwOnHookError", false);
_defineProperty(this, "_enforceBeforeAfter", false);
_defineProperty(this, "_deprecatedHooks", void 0);
_defineProperty(this, "_allowDeprecated", true);
_defineProperty(this, "_useHookClone", true);
this._hooks = /* @__PURE__ */ new Map();
this._deprecatedHooks = options?.deprecatedHooks ? new Map(options.deprecatedHooks) : /* @__PURE__ */ new Map();
if (options?.throwOnHookError !== void 0) this._throwOnHookError = options.throwOnHookError;
if (options?.enforceBeforeAfter !== void 0) this._enforceBeforeAfter = options.enforceBeforeAfter;
if (options?.allowDeprecated !== void 0) this._allowDeprecated = options.allowDeprecated;
if (options?.useHookClone !== void 0) this._useHookClone = options.useHookClone;
}
/**
* Gets all hooks
* @returns {Map<string, IHook[]>}
*/
get hooks() {
return this._hooks;
}
/**
* Gets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnHookError() {
return this._throwOnHookError;
}
/**
* Sets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnHookError(value) {
this._throwOnHookError = value;
}
/**
* Gets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @returns {boolean}
* @default false
*/
get enforceBeforeAfter() {
return this._enforceBeforeAfter;
}
/**
* Sets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @param {boolean} value
*/
set enforceBeforeAfter(value) {
this._enforceBeforeAfter = value;
}
/**
* Gets the map of deprecated hook names to deprecation messages.
* @returns {Map<string, string>}
*/
get deprecatedHooks() {
return this._deprecatedHooks;
}
/**
* Sets the map of deprecated hook names to deprecation messages.
* @param {Map<string, string>} value
*/
set deprecatedHooks(value) {
this._deprecatedHooks = value;
}
/**
* Gets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @returns {boolean}
*/
get allowDeprecated() {
return this._allowDeprecated;
}
/**
* Sets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @param {boolean} value
*/
set allowDeprecated(value) {
this._allowDeprecated = value;
}
/**
* Gets whether hook objects are cloned before storing. Default is true.
* @returns {boolean}
*/
get useHookClone() {
return this._useHookClone;
}
/**
* Sets whether hook objects are cloned before storing. Default is true.
* When false, the original IHook reference is stored directly.
* @param {boolean} value
*/
set useHookClone(value) {
this._useHookClone = value;
}
onHook(hookOrEvent, optionsOrHandler) {
let hook;
let options;
if (typeof hookOrEvent === "string") {
if (typeof optionsOrHandler !== "function") throw new TypeError("When calling onHook(event, handler), the second argument must be a function");
hook = {
event: hookOrEvent,
handler: optionsOrHandler
};
options = void 0;
} else {
hook = hookOrEvent;
options = optionsOrHandler;
}
this.validateHookName(hook.event);
if (!this.checkDeprecatedHook(hook.event)) return;
const entry = options?.useHookClone ?? this._useHookClone ? {
id: hook.id,
event: hook.event,
handler: hook.handler
} : hook;
entry.id = entry.id ?? crypto.randomUUID();
const eventHandlers = this._hooks.get(hook.event);
if (eventHandlers) {
const existingIndex = eventHandlers.findIndex((h) => h.id === entry.id);
if (existingIndex !== -1) eventHandlers[existingIndex] = entry;
else {
const position = options?.position ?? "Bottom";
if (position === "Top") eventHandlers.unshift(entry);
else if (position === "Bottom") eventHandlers.push(entry);
else {
const index = Math.max(0, Math.min(position, eventHandlers.length));
eventHandlers.splice(index, 0, entry);
}
}
} else this._hooks.set(hook.event, [entry]);
return entry;
}
/**
* Alias for onHook. This is provided for compatibility with other libraries that use the `addHook` method.
* @param {string} event - the event name
* @param {HookFn} handler - the handler function
* @returns {void}
*/
addHook(event, handler) {
this.onHook({
event,
handler
});
}
/**
* Adds handler functions for specific events
* @param {Array<IHook>} hooks
* @param {OnHookOptions} [options] - optional per-call options (e.g., useHookClone override, position)
* @returns {void}
*/
onHooks(hooks, options) {
for (const hook of hooks) this.onHook(hook, options);
}
/**
* Adds a handler function for a specific event that runs before all other handlers.
* Equivalent to calling `onHook(hook, { position: "Top" })`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependHook(hook, options) {
return this.onHook(hook, {
...options,
position: "Top"
});
}
/**
* Adds a handler that only executes once for a specific event before all other handlers.
* Equivalent to calling `onHook` with a self-removing wrapper and `{ position: "Top" }`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependOnceHook(hook, options) {
const wrappedHandler = async (...arguments_) => {
this.removeHook({
event: hook.event,
handler: wrappedHandler
});
return hook.handler(...arguments_);
};
return this.onHook({
id: hook.id,
event: hook.event,
handler: wrappedHandler
}, {
...options,
position: "Top"
});
}
/**
* Adds a handler that only executes once for a specific event
* @param {IHook} hook - the hook containing event name and handler
*/
onceHook(hook) {
this.validateHookName(hook.event);
if (!this.checkDeprecatedHook(hook.event)) return;
const wrappedHandler = async (...arguments_) => {
this.removeHook({
event: hook.event,
handler: wrappedHandler
});
return hook.handler(...arguments_);
};
this.onHook({
id: hook.id,
event: hook.event,
handler: wrappedHandler
});
}
/**
* Removes a handler function for a specific event
* @param {IHook} hook - the hook containing event name and handler to remove
* @returns {IHook | undefined} the removed hook, or undefined if not found
*/
removeHook(hook) {
this.validateHookName(hook.event);
const eventHandlers = this._hooks.get(hook.event);
if (eventHandlers) {
const index = eventHandlers.findIndex((h) => h.handler === hook.handler);
if (index !== -1) {
eventHandlers.splice(index, 1);
if (eventHandlers.length === 0) this._hooks.delete(hook.event);
return {
event: hook.event,
handler: hook.handler
};
}
}
}
/**
* Removes multiple hook handlers
* @param {Array<IHook>} hooks
* @returns {IHook[]} the hooks that were successfully removed
*/
removeHooks(hooks) {
const removed = [];
for (const hook of hooks) {
const result = this.removeHook(hook);
if (result) removed.push(result);
}
return removed;
}
/**
* Calls all handlers for a specific event
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
async hook(event, ...arguments_) {
this.validateHookName(event);
if (!this.checkDeprecatedHook(event)) return;
const eventHandlers = this._hooks.get(event);
if (eventHandlers) for (const hook of [...eventHandlers]) try {
await hook.handler(...arguments_);
} catch (error) {
const message = `${event}: ${error.message}`;
this.emit("error", new Error(message));
if (this._throwOnHookError) throw new Error(message);
}
}
/**
* Calls all synchronous handlers for a specific event.
* Async handlers (declared with `async` keyword) are silently skipped.
*
* Note: The `hook` method is preferred as it executes both sync and async functions.
* Use `hookSync` only when you specifically need synchronous execution.
* @param {string} event
* @param {T[]} arguments_
* @returns {void}
*/
hookSync(event, ...arguments_) {
this.validateHookName(event);
if (!this.checkDeprecatedHook(event)) return;
const eventHandlers = this._hooks.get(event);
if (eventHandlers) for (const hook of [...eventHandlers]) {
if (hook.handler.constructor.name === "AsyncFunction") continue;
try {
hook.handler(...arguments_);
} catch (error) {
const message = `${event}: ${error.message}`;
this.emit("error", new Error(message));
if (this._throwOnHookError) throw new Error(message);
}
}
}
/**
* Prepends the word `before` to your hook. Example is event is `test`, the before hook is `before:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
async beforeHook(event, ...arguments_) {
await this.hook(`before:${event}`, ...arguments_);
}
/**
* Prepends the word `after` to your hook. Example is event is `test`, the after hook is `after:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
async afterHook(event, ...arguments_) {
await this.hook(`after:${event}`, ...arguments_);
}
/**
* Calls all handlers for a specific event. This is an alias for `hook` and is provided for
* compatibility with other libraries that use the `callHook` method.
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
async callHook(event, ...arguments_) {
await this.hook(event, ...arguments_);
}
/**
* Gets all hooks for a specific event
* @param {string} event
* @returns {IHook[]}
*/
getHooks(event) {
this.validateHookName(event);
return this._hooks.get(event);
}
/**
* Gets a specific hook by id, searching across all events
* @param {string} id - the hook id
* @returns {IHook | undefined} the hook if found, or undefined
*/
getHook(id) {
for (const eventHandlers of this._hooks.values()) {
const found = eventHandlers.find((h) => h.id === id);
if (found) return found;
}
}
/**
* Removes one or more hooks by id, searching across all events
* @param {string | string[]} id - the hook id or array of hook ids to remove
* @returns {IHook | IHook[] | undefined} the removed hook(s), or undefined/empty array if not found
*/
removeHookById(id) {
if (Array.isArray(id)) {
const removed = [];
for (const singleId of id) {
const result = this.removeHookById(singleId);
if (result && !Array.isArray(result)) removed.push(result);
}
return removed;
}
for (const [event, eventHandlers] of this._hooks.entries()) {
const index = eventHandlers.findIndex((h) => h.id === id);
if (index !== -1) {
const [removed] = eventHandlers.splice(index, 1);
if (eventHandlers.length === 0) this._hooks.delete(event);
return removed;
}
}
}
/**
* Removes all hooks
* @returns {void}
*/
clearHooks() {
this._hooks.clear();
}
/**
* Removes all hooks for a specific event and returns the removed hooks.
* @param {string} event - The event name to remove hooks for.
* @returns {IHook[]} the hooks that were removed
*/
removeEventHooks(event) {
this.validateHookName(event);
const eventHandlers = this._hooks.get(event);
if (eventHandlers) {
const removed = [...eventHandlers];
this._hooks.delete(event);
return removed;
}
return [];
}
/**
* Validates hook event name if enforceBeforeAfter is enabled
* @param {string} event - The event name to validate
* @throws {Error} If enforceBeforeAfter is true and event doesn't start with 'before' or 'after'
*/
validateHookName(event) {
if (this._enforceBeforeAfter) {
const eventValue = event.trim().toLocaleLowerCase();
if (!eventValue.startsWith("before") && !eventValue.startsWith("after")) throw new Error(`Hook event "${event}" must start with "before" or "after" when enforceBeforeAfter is enabled`);
}
}
/**
* Checks if a hook is deprecated and emits a warning if it is
* @param {string} event - The event name to check
* @returns {boolean} - Returns true if the hook should proceed, false if it should be blocked
*/
checkDeprecatedHook(event) {
if (this._deprecatedHooks.has(event)) {
const message = this._deprecatedHooks.get(event);
const warningMessage = `Hook "${event}" is deprecated${message ? `: ${message}` : ""}`;
this.emit("warn", {
hook: event,
message: warningMessage
});
return this._allowDeprecated;
}
return true;
}
};
//#endregion
exports.Eventified = Eventified;
exports.Hook = Hook;
exports.Hookified = Hookified;
exports.ParallelHook = ParallelHook;
exports.WaterfallHook = WaterfallHook;
return exports;
})({});
//# sourceMappingURL=index.global.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,943 @@
//#region \0@oxc-project+runtime@0.127.0/helpers/typeof.js
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
return typeof o;
} : function(o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
//#endregion
//#region \0@oxc-project+runtime@0.127.0/helpers/toPrimitive.js
function toPrimitive(t, r) {
if ("object" != _typeof(t) || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r || "default");
if ("object" != _typeof(i)) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
//#endregion
//#region \0@oxc-project+runtime@0.127.0/helpers/toPropertyKey.js
function toPropertyKey(t) {
var i = toPrimitive(t, "string");
return "symbol" == _typeof(i) ? i : i + "";
}
//#endregion
//#region \0@oxc-project+runtime@0.127.0/helpers/defineProperty.js
function _defineProperty(e, r, t) {
return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[r] = t, e;
}
//#endregion
//#region src/eventified.ts
const ERROR_EVENT = "error";
var Eventified = class {
constructor(options) {
_defineProperty(this, "_eventListeners", void 0);
_defineProperty(this, "_maxListeners", void 0);
_defineProperty(this, "_eventLogger", void 0);
_defineProperty(this, "_throwOnEmitError", false);
_defineProperty(this, "_throwOnEmptyListeners", true);
this._eventListeners = /* @__PURE__ */ new Map();
this._maxListeners = 0;
this._eventLogger = options?.eventLogger;
if (options?.throwOnEmitError !== void 0) this._throwOnEmitError = options.throwOnEmitError;
if (options?.throwOnEmptyListeners !== void 0) this._throwOnEmptyListeners = options.throwOnEmptyListeners;
}
/**
* Gets the event logger
* @returns {Logger}
*/
get eventLogger() {
return this._eventLogger;
}
/**
* Sets the event logger
* @param {Logger} eventLogger
*/
set eventLogger(eventLogger) {
this._eventLogger = eventLogger;
}
/**
* Gets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnEmitError() {
return this._throwOnEmitError;
}
/**
* Sets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnEmitError(value) {
this._throwOnEmitError = value;
}
/**
* Gets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @returns {boolean}
*/
get throwOnEmptyListeners() {
return this._throwOnEmptyListeners;
}
/**
* Sets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @param {boolean} value
*/
set throwOnEmptyListeners(value) {
this._throwOnEmptyListeners = value;
}
/**
* Adds a handler function for a specific event that will run only once
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
once(eventName, listener) {
const onceListener = (...arguments_) => {
this.off(eventName, onceListener);
listener(...arguments_);
};
this.on(eventName, onceListener);
return this;
}
/**
* Gets the number of listeners for a specific event. If no event is provided, it returns the total number of listeners
* @param {string} eventName The event name. Not required
* @returns {number} The number of listeners
*/
listenerCount(eventName) {
if (eventName === void 0) {
let count = 0;
for (const entry of this._eventListeners.values()) count += typeof entry === "function" ? 1 : entry.length;
return count;
}
const entry = this._eventListeners.get(eventName);
if (entry === void 0) return 0;
return typeof entry === "function" ? 1 : entry.length;
}
/**
* Gets an array of event names
* @returns {Array<string | symbol>} An array of event names
*/
eventNames() {
return [...this._eventListeners.keys()];
}
/**
* Gets an array of listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
rawListeners(event) {
if (event === void 0) return this.getAllListeners();
const entry = this._eventListeners.get(event);
if (entry === void 0) return [];
return typeof entry === "function" ? [entry] : entry;
}
/**
* Prepends a listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependListener(eventName, listener) {
const existing = this._eventListeners.get(eventName);
if (existing === void 0) this._eventListeners.set(eventName, listener);
else if (typeof existing === "function") this._eventListeners.set(eventName, [listener, existing]);
else existing.unshift(listener);
return this;
}
/**
* Prepends a one-time listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependOnceListener(eventName, listener) {
const onceListener = (...arguments_) => {
this.off(eventName, onceListener);
listener(...arguments_);
};
this.prependListener(eventName, onceListener);
return this;
}
/**
* Gets the maximum number of listeners that can be added for a single event
* @returns {number} The maximum number of listeners
*/
maxListeners() {
return this._maxListeners;
}
/**
* Adds a listener for a specific event. It is an alias for the on() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
addListener(event, listener) {
this.on(event, listener);
return this;
}
/**
* Adds a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
on(event, listener) {
const existing = this._eventListeners.get(event);
if (existing === void 0) {
this._eventListeners.set(event, listener);
return this;
}
if (typeof existing === "function") {
const arr = [existing, listener];
this._eventListeners.set(event, arr);
if (this._maxListeners > 0 && arr.length > this._maxListeners) console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${arr.length} ${event} listeners added. Use setMaxListeners() to increase limit.`);
} else {
existing.push(listener);
if (this._maxListeners > 0 && existing.length > this._maxListeners) console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${existing.length} ${event} listeners added. Use setMaxListeners() to increase limit.`);
}
return this;
}
/**
* Removes a listener for a specific event. It is an alias for the off() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeListener(event, listener) {
this.off(event, listener);
return this;
}
/**
* Removes a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
off(event, listener) {
const entry = this._eventListeners.get(event);
if (entry === void 0) return this;
if (typeof entry === "function") {
if (entry === listener) this._eventListeners.delete(event);
return this;
}
const index = entry.indexOf(listener);
if (index !== -1) if (entry.length === 2) this._eventListeners.set(event, entry[1 - index]);
else if (entry.length === 1) this._eventListeners.delete(event);
else entry.splice(index, 1);
return this;
}
/**
* Calls all listeners for a specific event
* @param {string | symbol} event
* @param arguments_ The arguments to pass to the listeners
* @returns {boolean} Returns true if the event had listeners, false otherwise
*/
emit(event, ...arguments_) {
let result = false;
const entry = this._eventListeners.get(event);
const argumentLength = arguments_.length;
if (entry !== void 0) {
if (typeof entry === "function") if (argumentLength === 1) entry(arguments_[0]);
else if (argumentLength === 2) entry(arguments_[0], arguments_[1]);
else entry(...arguments_);
else {
const len = entry.length;
for (let i = 0; i < len; i++) if (argumentLength === 1) entry[i](arguments_[0]);
else if (argumentLength === 2) entry[i](arguments_[0], arguments_[1]);
else entry[i](...arguments_);
}
result = true;
}
if (this._eventLogger) this.sendToEventLogger(event, arguments_);
if (!result && event === ERROR_EVENT) {
const error = arguments_[0] instanceof Error ? arguments_[0] : /* @__PURE__ */ new Error(`${arguments_[0]}`);
if (this._throwOnEmitError || this._throwOnEmptyListeners) throw error;
}
return result;
}
/**
* Gets all listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
listeners(event) {
const entry = this._eventListeners.get(event);
if (entry === void 0) return [];
return typeof entry === "function" ? [entry] : entry;
}
/**
* Removes all listeners for a specific event. If no event is provided, it removes all listeners
* @param {string} [event] (Optional) The event name
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeAllListeners(event) {
if (event !== void 0) this._eventListeners.delete(event);
else this._eventListeners.clear();
return this;
}
/**
* Sets the maximum number of listeners that can be added for a single event
* @param {number} n The maximum number of listeners
* @returns {void}
*/
setMaxListeners(n) {
this._maxListeners = n < 0 ? 0 : n;
}
/**
* Gets all listeners
* @returns {EventListener[]} An array of listeners
*/
getAllListeners() {
const result = [];
for (const entry of this._eventListeners.values()) if (typeof entry === "function") result.push(entry);
else for (let i = 0; i < entry.length; i++) result.push(entry[i]);
return result;
}
/**
* Sends a log message using the configured logger based on the event name
* @param {string | symbol} eventName - The event name that determines the log level
* @param {unknown} data - The data to log
*/
sendToEventLogger(eventName, data) {
/* v8 ignore next 3 -- @preserve: guarded by caller */
if (!this._eventLogger) return;
let message;
/* v8 ignore next -- @preserve */
if (typeof data === "string") message = data;
else if (Array.isArray(data) && data.length > 0 && data[0] instanceof Error) message = data[0].message;
else if (data instanceof Error) message = data.message;
else if (Array.isArray(data) && data.length > 0 && typeof data[0]?.message === "string") message = data[0].message;
else message = JSON.stringify(data);
switch (eventName) {
case "error":
this._eventLogger.error?.(message, {
event: eventName,
data
});
break;
case "warn":
this._eventLogger.warn?.(message, {
event: eventName,
data
});
break;
case "trace":
this._eventLogger.trace?.(message, {
event: eventName,
data
});
break;
case "debug":
this._eventLogger.debug?.(message, {
event: eventName,
data
});
break;
case "fatal":
this._eventLogger.fatal?.(message, {
event: eventName,
data
});
break;
default:
this._eventLogger.info?.(message, {
event: eventName,
data
});
break;
}
}
};
//#endregion
//#region src/hooks/hook.ts
/**
* Concrete implementation of the IHook interface.
* Provides a convenient class-based way to create hook entries.
*/
var Hook = class {
/**
* Creates a new Hook instance
* @param {string} event - The event name for the hook
* @param {HookFn} handler - The handler function for the hook
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, handler, id) {
_defineProperty(this, "id", void 0);
_defineProperty(this, "event", void 0);
_defineProperty(this, "handler", void 0);
this.id = id;
this.event = event;
this.handler = handler;
}
};
//#endregion
//#region src/hooks/parallel-hook.ts
/**
* A ParallelHook fans a single invocation out to many registered hook
* functions concurrently via Promise.allSettled, then calls a final
* handler with the aggregated results — including failures — keyed by
* the hook function reference for direct lookup. Each hook receives only
* the original arguments; hooks do not see each other's results.
*
* Implements IHook for compatibility with Hookified.onHook(); the final
* handler is called regardless of whether the parallel hook is invoked
* directly or through Hookified.hook().
*
* Generics tighten the per-hook signature when every hook in the set
* accepts the same `initialArgs` and returns the same result type.
* Both default to `any` for backwards compatibility.
*
* @template TArgs - The shape of `initialArgs` passed to every hook
* @template TResult - The result type each hook returns
*/
var ParallelHook = class {
/**
* Creates a new ParallelHook instance
* @param {string} event - The event name for the hook
* @param {ParallelHookFinalFn<TArgs, TResult>} finalHandler - Called once with `{ initialArgs, results }` after all parallel hooks settle
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, finalHandler, id) {
_defineProperty(this, "id", void 0);
_defineProperty(this, "event", void 0);
_defineProperty(this, "handler", void 0);
_defineProperty(this, "hooks", void 0);
_defineProperty(this, "_finalHandler", void 0);
this.id = id;
this.event = event;
this.hooks = [];
this._finalHandler = finalHandler;
this.handler = async (...arguments_) => {
const initialArgs = arguments_.length === 1 ? arguments_[0] : arguments_;
const snapshot = [...this.hooks];
const settled = await Promise.allSettled(snapshot.map((hook) => Promise.resolve().then(() => hook({ initialArgs }))));
const results = /* @__PURE__ */ new Map();
snapshot.forEach((hook, index) => {
const outcome = settled[index];
results.set(hook, outcome.status === "fulfilled" ? {
status: "fulfilled",
result: outcome.value
} : {
status: "rejected",
reason: outcome.reason
});
});
await this._finalHandler({
initialArgs,
results
});
};
}
/**
* Adds a hook function to the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to add
*/
addHook(hook) {
this.hooks.push(hook);
}
/**
* Removes a specific hook function from the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook) {
const index = this.hooks.indexOf(hook);
if (index !== -1) {
this.hooks.splice(index, 1);
return true;
}
return false;
}
};
//#endregion
//#region src/hooks/waterfall-hook.ts
/**
* A WaterfallHook chains multiple hook functions sequentially,
* where each hook receives a context with the previous result,
* initial arguments, and accumulated results. After all hooks
* have executed, the final handler receives the transformed result.
* Implements IHook for compatibility with Hookified.onHook().
*/
var WaterfallHook = class {
/**
* Creates a new WaterfallHook instance
* @param {string} event - The event name for the hook
* @param {WaterfallHookFn} finalHandler - The final handler function that receives the transformed result
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, finalHandler, id) {
_defineProperty(this, "id", void 0);
_defineProperty(this, "event", void 0);
_defineProperty(this, "handler", void 0);
_defineProperty(this, "hooks", void 0);
_defineProperty(this, "_finalHandler", void 0);
this.id = id;
this.event = event;
this.hooks = [];
this._finalHandler = finalHandler;
this.handler = async (...arguments_) => {
const initialArgs = arguments_.length === 1 ? arguments_[0] : arguments_;
const results = [];
for (const hook of this.hooks) {
const result = await hook({
initialArgs,
results: [...results]
});
results.push({
hook,
result
});
}
await this._finalHandler({
initialArgs,
results: [...results]
});
};
}
/**
* Adds a hook function to the end of the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to add
*/
addHook(hook) {
this.hooks.push(hook);
}
/**
* Removes a specific hook function from the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook) {
const index = this.hooks.indexOf(hook);
if (index !== -1) {
this.hooks.splice(index, 1);
return true;
}
return false;
}
};
//#endregion
//#region src/index.ts
var Hookified = class extends Eventified {
constructor(options) {
super({
eventLogger: options?.eventLogger,
throwOnEmitError: options?.throwOnEmitError,
throwOnEmptyListeners: options?.throwOnEmptyListeners
});
_defineProperty(this, "_hooks", void 0);
_defineProperty(this, "_throwOnHookError", false);
_defineProperty(this, "_enforceBeforeAfter", false);
_defineProperty(this, "_deprecatedHooks", void 0);
_defineProperty(this, "_allowDeprecated", true);
_defineProperty(this, "_useHookClone", true);
this._hooks = /* @__PURE__ */ new Map();
this._deprecatedHooks = options?.deprecatedHooks ? new Map(options.deprecatedHooks) : /* @__PURE__ */ new Map();
if (options?.throwOnHookError !== void 0) this._throwOnHookError = options.throwOnHookError;
if (options?.enforceBeforeAfter !== void 0) this._enforceBeforeAfter = options.enforceBeforeAfter;
if (options?.allowDeprecated !== void 0) this._allowDeprecated = options.allowDeprecated;
if (options?.useHookClone !== void 0) this._useHookClone = options.useHookClone;
}
/**
* Gets all hooks
* @returns {Map<string, IHook[]>}
*/
get hooks() {
return this._hooks;
}
/**
* Gets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnHookError() {
return this._throwOnHookError;
}
/**
* Sets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnHookError(value) {
this._throwOnHookError = value;
}
/**
* Gets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @returns {boolean}
* @default false
*/
get enforceBeforeAfter() {
return this._enforceBeforeAfter;
}
/**
* Sets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @param {boolean} value
*/
set enforceBeforeAfter(value) {
this._enforceBeforeAfter = value;
}
/**
* Gets the map of deprecated hook names to deprecation messages.
* @returns {Map<string, string>}
*/
get deprecatedHooks() {
return this._deprecatedHooks;
}
/**
* Sets the map of deprecated hook names to deprecation messages.
* @param {Map<string, string>} value
*/
set deprecatedHooks(value) {
this._deprecatedHooks = value;
}
/**
* Gets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @returns {boolean}
*/
get allowDeprecated() {
return this._allowDeprecated;
}
/**
* Sets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @param {boolean} value
*/
set allowDeprecated(value) {
this._allowDeprecated = value;
}
/**
* Gets whether hook objects are cloned before storing. Default is true.
* @returns {boolean}
*/
get useHookClone() {
return this._useHookClone;
}
/**
* Sets whether hook objects are cloned before storing. Default is true.
* When false, the original IHook reference is stored directly.
* @param {boolean} value
*/
set useHookClone(value) {
this._useHookClone = value;
}
onHook(hookOrEvent, optionsOrHandler) {
let hook;
let options;
if (typeof hookOrEvent === "string") {
if (typeof optionsOrHandler !== "function") throw new TypeError("When calling onHook(event, handler), the second argument must be a function");
hook = {
event: hookOrEvent,
handler: optionsOrHandler
};
options = void 0;
} else {
hook = hookOrEvent;
options = optionsOrHandler;
}
this.validateHookName(hook.event);
if (!this.checkDeprecatedHook(hook.event)) return;
const entry = options?.useHookClone ?? this._useHookClone ? {
id: hook.id,
event: hook.event,
handler: hook.handler
} : hook;
entry.id = entry.id ?? crypto.randomUUID();
const eventHandlers = this._hooks.get(hook.event);
if (eventHandlers) {
const existingIndex = eventHandlers.findIndex((h) => h.id === entry.id);
if (existingIndex !== -1) eventHandlers[existingIndex] = entry;
else {
const position = options?.position ?? "Bottom";
if (position === "Top") eventHandlers.unshift(entry);
else if (position === "Bottom") eventHandlers.push(entry);
else {
const index = Math.max(0, Math.min(position, eventHandlers.length));
eventHandlers.splice(index, 0, entry);
}
}
} else this._hooks.set(hook.event, [entry]);
return entry;
}
/**
* Alias for onHook. This is provided for compatibility with other libraries that use the `addHook` method.
* @param {string} event - the event name
* @param {HookFn} handler - the handler function
* @returns {void}
*/
addHook(event, handler) {
this.onHook({
event,
handler
});
}
/**
* Adds handler functions for specific events
* @param {Array<IHook>} hooks
* @param {OnHookOptions} [options] - optional per-call options (e.g., useHookClone override, position)
* @returns {void}
*/
onHooks(hooks, options) {
for (const hook of hooks) this.onHook(hook, options);
}
/**
* Adds a handler function for a specific event that runs before all other handlers.
* Equivalent to calling `onHook(hook, { position: "Top" })`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependHook(hook, options) {
return this.onHook(hook, {
...options,
position: "Top"
});
}
/**
* Adds a handler that only executes once for a specific event before all other handlers.
* Equivalent to calling `onHook` with a self-removing wrapper and `{ position: "Top" }`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependOnceHook(hook, options) {
const wrappedHandler = async (...arguments_) => {
this.removeHook({
event: hook.event,
handler: wrappedHandler
});
return hook.handler(...arguments_);
};
return this.onHook({
id: hook.id,
event: hook.event,
handler: wrappedHandler
}, {
...options,
position: "Top"
});
}
/**
* Adds a handler that only executes once for a specific event
* @param {IHook} hook - the hook containing event name and handler
*/
onceHook(hook) {
this.validateHookName(hook.event);
if (!this.checkDeprecatedHook(hook.event)) return;
const wrappedHandler = async (...arguments_) => {
this.removeHook({
event: hook.event,
handler: wrappedHandler
});
return hook.handler(...arguments_);
};
this.onHook({
id: hook.id,
event: hook.event,
handler: wrappedHandler
});
}
/**
* Removes a handler function for a specific event
* @param {IHook} hook - the hook containing event name and handler to remove
* @returns {IHook | undefined} the removed hook, or undefined if not found
*/
removeHook(hook) {
this.validateHookName(hook.event);
const eventHandlers = this._hooks.get(hook.event);
if (eventHandlers) {
const index = eventHandlers.findIndex((h) => h.handler === hook.handler);
if (index !== -1) {
eventHandlers.splice(index, 1);
if (eventHandlers.length === 0) this._hooks.delete(hook.event);
return {
event: hook.event,
handler: hook.handler
};
}
}
}
/**
* Removes multiple hook handlers
* @param {Array<IHook>} hooks
* @returns {IHook[]} the hooks that were successfully removed
*/
removeHooks(hooks) {
const removed = [];
for (const hook of hooks) {
const result = this.removeHook(hook);
if (result) removed.push(result);
}
return removed;
}
/**
* Calls all handlers for a specific event
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
async hook(event, ...arguments_) {
this.validateHookName(event);
if (!this.checkDeprecatedHook(event)) return;
const eventHandlers = this._hooks.get(event);
if (eventHandlers) for (const hook of [...eventHandlers]) try {
await hook.handler(...arguments_);
} catch (error) {
const message = `${event}: ${error.message}`;
this.emit("error", new Error(message));
if (this._throwOnHookError) throw new Error(message);
}
}
/**
* Calls all synchronous handlers for a specific event.
* Async handlers (declared with `async` keyword) are silently skipped.
*
* Note: The `hook` method is preferred as it executes both sync and async functions.
* Use `hookSync` only when you specifically need synchronous execution.
* @param {string} event
* @param {T[]} arguments_
* @returns {void}
*/
hookSync(event, ...arguments_) {
this.validateHookName(event);
if (!this.checkDeprecatedHook(event)) return;
const eventHandlers = this._hooks.get(event);
if (eventHandlers) for (const hook of [...eventHandlers]) {
if (hook.handler.constructor.name === "AsyncFunction") continue;
try {
hook.handler(...arguments_);
} catch (error) {
const message = `${event}: ${error.message}`;
this.emit("error", new Error(message));
if (this._throwOnHookError) throw new Error(message);
}
}
}
/**
* Prepends the word `before` to your hook. Example is event is `test`, the before hook is `before:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
async beforeHook(event, ...arguments_) {
await this.hook(`before:${event}`, ...arguments_);
}
/**
* Prepends the word `after` to your hook. Example is event is `test`, the after hook is `after:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
async afterHook(event, ...arguments_) {
await this.hook(`after:${event}`, ...arguments_);
}
/**
* Calls all handlers for a specific event. This is an alias for `hook` and is provided for
* compatibility with other libraries that use the `callHook` method.
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
async callHook(event, ...arguments_) {
await this.hook(event, ...arguments_);
}
/**
* Gets all hooks for a specific event
* @param {string} event
* @returns {IHook[]}
*/
getHooks(event) {
this.validateHookName(event);
return this._hooks.get(event);
}
/**
* Gets a specific hook by id, searching across all events
* @param {string} id - the hook id
* @returns {IHook | undefined} the hook if found, or undefined
*/
getHook(id) {
for (const eventHandlers of this._hooks.values()) {
const found = eventHandlers.find((h) => h.id === id);
if (found) return found;
}
}
/**
* Removes one or more hooks by id, searching across all events
* @param {string | string[]} id - the hook id or array of hook ids to remove
* @returns {IHook | IHook[] | undefined} the removed hook(s), or undefined/empty array if not found
*/
removeHookById(id) {
if (Array.isArray(id)) {
const removed = [];
for (const singleId of id) {
const result = this.removeHookById(singleId);
if (result && !Array.isArray(result)) removed.push(result);
}
return removed;
}
for (const [event, eventHandlers] of this._hooks.entries()) {
const index = eventHandlers.findIndex((h) => h.id === id);
if (index !== -1) {
const [removed] = eventHandlers.splice(index, 1);
if (eventHandlers.length === 0) this._hooks.delete(event);
return removed;
}
}
}
/**
* Removes all hooks
* @returns {void}
*/
clearHooks() {
this._hooks.clear();
}
/**
* Removes all hooks for a specific event and returns the removed hooks.
* @param {string} event - The event name to remove hooks for.
* @returns {IHook[]} the hooks that were removed
*/
removeEventHooks(event) {
this.validateHookName(event);
const eventHandlers = this._hooks.get(event);
if (eventHandlers) {
const removed = [...eventHandlers];
this._hooks.delete(event);
return removed;
}
return [];
}
/**
* Validates hook event name if enforceBeforeAfter is enabled
* @param {string} event - The event name to validate
* @throws {Error} If enforceBeforeAfter is true and event doesn't start with 'before' or 'after'
*/
validateHookName(event) {
if (this._enforceBeforeAfter) {
const eventValue = event.trim().toLocaleLowerCase();
if (!eventValue.startsWith("before") && !eventValue.startsWith("after")) throw new Error(`Hook event "${event}" must start with "before" or "after" when enforceBeforeAfter is enabled`);
}
}
/**
* Checks if a hook is deprecated and emits a warning if it is
* @param {string} event - The event name to check
* @returns {boolean} - Returns true if the hook should proceed, false if it should be blocked
*/
checkDeprecatedHook(event) {
if (this._deprecatedHooks.has(event)) {
const message = this._deprecatedHooks.get(event);
const warningMessage = `Hook "${event}" is deprecated${message ? `: ${message}` : ""}`;
this.emit("warn", {
hook: event,
message: warningMessage
});
return this._allowDeprecated;
}
return true;
}
};
//#endregion
export { Eventified, Hook, Hookified, ParallelHook, WaterfallHook };
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,908 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/eventified.ts
const ERROR_EVENT = "error";
var Eventified = class {
_eventListeners;
_maxListeners;
_eventLogger;
_throwOnEmitError = false;
_throwOnEmptyListeners = true;
constructor(options) {
this._eventListeners = /* @__PURE__ */ new Map();
this._maxListeners = 0;
this._eventLogger = options?.eventLogger;
if (options?.throwOnEmitError !== void 0) this._throwOnEmitError = options.throwOnEmitError;
if (options?.throwOnEmptyListeners !== void 0) this._throwOnEmptyListeners = options.throwOnEmptyListeners;
}
/**
* Gets the event logger
* @returns {Logger}
*/
get eventLogger() {
return this._eventLogger;
}
/**
* Sets the event logger
* @param {Logger} eventLogger
*/
set eventLogger(eventLogger) {
this._eventLogger = eventLogger;
}
/**
* Gets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnEmitError() {
return this._throwOnEmitError;
}
/**
* Sets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnEmitError(value) {
this._throwOnEmitError = value;
}
/**
* Gets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @returns {boolean}
*/
get throwOnEmptyListeners() {
return this._throwOnEmptyListeners;
}
/**
* Sets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @param {boolean} value
*/
set throwOnEmptyListeners(value) {
this._throwOnEmptyListeners = value;
}
/**
* Adds a handler function for a specific event that will run only once
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
once(eventName, listener) {
const onceListener = (...arguments_) => {
this.off(eventName, onceListener);
listener(...arguments_);
};
this.on(eventName, onceListener);
return this;
}
/**
* Gets the number of listeners for a specific event. If no event is provided, it returns the total number of listeners
* @param {string} eventName The event name. Not required
* @returns {number} The number of listeners
*/
listenerCount(eventName) {
if (eventName === void 0) {
let count = 0;
for (const entry of this._eventListeners.values()) count += typeof entry === "function" ? 1 : entry.length;
return count;
}
const entry = this._eventListeners.get(eventName);
if (entry === void 0) return 0;
return typeof entry === "function" ? 1 : entry.length;
}
/**
* Gets an array of event names
* @returns {Array<string | symbol>} An array of event names
*/
eventNames() {
return [...this._eventListeners.keys()];
}
/**
* Gets an array of listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
rawListeners(event) {
if (event === void 0) return this.getAllListeners();
const entry = this._eventListeners.get(event);
if (entry === void 0) return [];
return typeof entry === "function" ? [entry] : entry;
}
/**
* Prepends a listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependListener(eventName, listener) {
const existing = this._eventListeners.get(eventName);
if (existing === void 0) this._eventListeners.set(eventName, listener);
else if (typeof existing === "function") this._eventListeners.set(eventName, [listener, existing]);
else existing.unshift(listener);
return this;
}
/**
* Prepends a one-time listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependOnceListener(eventName, listener) {
const onceListener = (...arguments_) => {
this.off(eventName, onceListener);
listener(...arguments_);
};
this.prependListener(eventName, onceListener);
return this;
}
/**
* Gets the maximum number of listeners that can be added for a single event
* @returns {number} The maximum number of listeners
*/
maxListeners() {
return this._maxListeners;
}
/**
* Adds a listener for a specific event. It is an alias for the on() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
addListener(event, listener) {
this.on(event, listener);
return this;
}
/**
* Adds a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
on(event, listener) {
const existing = this._eventListeners.get(event);
if (existing === void 0) {
this._eventListeners.set(event, listener);
return this;
}
if (typeof existing === "function") {
const arr = [existing, listener];
this._eventListeners.set(event, arr);
if (this._maxListeners > 0 && arr.length > this._maxListeners) console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${arr.length} ${event} listeners added. Use setMaxListeners() to increase limit.`);
} else {
existing.push(listener);
if (this._maxListeners > 0 && existing.length > this._maxListeners) console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${existing.length} ${event} listeners added. Use setMaxListeners() to increase limit.`);
}
return this;
}
/**
* Removes a listener for a specific event. It is an alias for the off() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeListener(event, listener) {
this.off(event, listener);
return this;
}
/**
* Removes a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
off(event, listener) {
const entry = this._eventListeners.get(event);
if (entry === void 0) return this;
if (typeof entry === "function") {
if (entry === listener) this._eventListeners.delete(event);
return this;
}
const index = entry.indexOf(listener);
if (index !== -1) if (entry.length === 2) this._eventListeners.set(event, entry[1 - index]);
else if (entry.length === 1) this._eventListeners.delete(event);
else entry.splice(index, 1);
return this;
}
/**
* Calls all listeners for a specific event
* @param {string | symbol} event
* @param arguments_ The arguments to pass to the listeners
* @returns {boolean} Returns true if the event had listeners, false otherwise
*/
emit(event, ...arguments_) {
let result = false;
const entry = this._eventListeners.get(event);
const argumentLength = arguments_.length;
if (entry !== void 0) {
if (typeof entry === "function") if (argumentLength === 1) entry(arguments_[0]);
else if (argumentLength === 2) entry(arguments_[0], arguments_[1]);
else entry(...arguments_);
else {
const len = entry.length;
for (let i = 0; i < len; i++) if (argumentLength === 1) entry[i](arguments_[0]);
else if (argumentLength === 2) entry[i](arguments_[0], arguments_[1]);
else entry[i](...arguments_);
}
result = true;
}
if (this._eventLogger) this.sendToEventLogger(event, arguments_);
if (!result && event === ERROR_EVENT) {
const error = arguments_[0] instanceof Error ? arguments_[0] : /* @__PURE__ */ new Error(`${arguments_[0]}`);
if (this._throwOnEmitError || this._throwOnEmptyListeners) throw error;
}
return result;
}
/**
* Gets all listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
listeners(event) {
const entry = this._eventListeners.get(event);
if (entry === void 0) return [];
return typeof entry === "function" ? [entry] : entry;
}
/**
* Removes all listeners for a specific event. If no event is provided, it removes all listeners
* @param {string} [event] (Optional) The event name
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeAllListeners(event) {
if (event !== void 0) this._eventListeners.delete(event);
else this._eventListeners.clear();
return this;
}
/**
* Sets the maximum number of listeners that can be added for a single event
* @param {number} n The maximum number of listeners
* @returns {void}
*/
setMaxListeners(n) {
this._maxListeners = n < 0 ? 0 : n;
}
/**
* Gets all listeners
* @returns {EventListener[]} An array of listeners
*/
getAllListeners() {
const result = [];
for (const entry of this._eventListeners.values()) if (typeof entry === "function") result.push(entry);
else for (let i = 0; i < entry.length; i++) result.push(entry[i]);
return result;
}
/**
* Sends a log message using the configured logger based on the event name
* @param {string | symbol} eventName - The event name that determines the log level
* @param {unknown} data - The data to log
*/
sendToEventLogger(eventName, data) {
/* v8 ignore next 3 -- @preserve: guarded by caller */
if (!this._eventLogger) return;
let message;
/* v8 ignore next -- @preserve */
if (typeof data === "string") message = data;
else if (Array.isArray(data) && data.length > 0 && data[0] instanceof Error) message = data[0].message;
else if (data instanceof Error) message = data.message;
else if (Array.isArray(data) && data.length > 0 && typeof data[0]?.message === "string") message = data[0].message;
else message = JSON.stringify(data);
switch (eventName) {
case "error":
this._eventLogger.error?.(message, {
event: eventName,
data
});
break;
case "warn":
this._eventLogger.warn?.(message, {
event: eventName,
data
});
break;
case "trace":
this._eventLogger.trace?.(message, {
event: eventName,
data
});
break;
case "debug":
this._eventLogger.debug?.(message, {
event: eventName,
data
});
break;
case "fatal":
this._eventLogger.fatal?.(message, {
event: eventName,
data
});
break;
default:
this._eventLogger.info?.(message, {
event: eventName,
data
});
break;
}
}
};
//#endregion
//#region src/hooks/hook.ts
/**
* Concrete implementation of the IHook interface.
* Provides a convenient class-based way to create hook entries.
*/
var Hook = class {
id;
event;
handler;
/**
* Creates a new Hook instance
* @param {string} event - The event name for the hook
* @param {HookFn} handler - The handler function for the hook
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, handler, id) {
this.id = id;
this.event = event;
this.handler = handler;
}
};
//#endregion
//#region src/hooks/parallel-hook.ts
/**
* A ParallelHook fans a single invocation out to many registered hook
* functions concurrently via Promise.allSettled, then calls a final
* handler with the aggregated results — including failures — keyed by
* the hook function reference for direct lookup. Each hook receives only
* the original arguments; hooks do not see each other's results.
*
* Implements IHook for compatibility with Hookified.onHook(); the final
* handler is called regardless of whether the parallel hook is invoked
* directly or through Hookified.hook().
*
* Generics tighten the per-hook signature when every hook in the set
* accepts the same `initialArgs` and returns the same result type.
* Both default to `any` for backwards compatibility.
*
* @template TArgs - The shape of `initialArgs` passed to every hook
* @template TResult - The result type each hook returns
*/
var ParallelHook = class {
id;
event;
handler;
hooks;
_finalHandler;
/**
* Creates a new ParallelHook instance
* @param {string} event - The event name for the hook
* @param {ParallelHookFinalFn<TArgs, TResult>} finalHandler - Called once with `{ initialArgs, results }` after all parallel hooks settle
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, finalHandler, id) {
this.id = id;
this.event = event;
this.hooks = [];
this._finalHandler = finalHandler;
this.handler = async (...arguments_) => {
const initialArgs = arguments_.length === 1 ? arguments_[0] : arguments_;
const snapshot = [...this.hooks];
const settled = await Promise.allSettled(snapshot.map((hook) => Promise.resolve().then(() => hook({ initialArgs }))));
const results = /* @__PURE__ */ new Map();
snapshot.forEach((hook, index) => {
const outcome = settled[index];
results.set(hook, outcome.status === "fulfilled" ? {
status: "fulfilled",
result: outcome.value
} : {
status: "rejected",
reason: outcome.reason
});
});
await this._finalHandler({
initialArgs,
results
});
};
}
/**
* Adds a hook function to the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to add
*/
addHook(hook) {
this.hooks.push(hook);
}
/**
* Removes a specific hook function from the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook) {
const index = this.hooks.indexOf(hook);
if (index !== -1) {
this.hooks.splice(index, 1);
return true;
}
return false;
}
};
//#endregion
//#region src/hooks/waterfall-hook.ts
/**
* A WaterfallHook chains multiple hook functions sequentially,
* where each hook receives a context with the previous result,
* initial arguments, and accumulated results. After all hooks
* have executed, the final handler receives the transformed result.
* Implements IHook for compatibility with Hookified.onHook().
*/
var WaterfallHook = class {
id;
event;
handler;
hooks;
_finalHandler;
/**
* Creates a new WaterfallHook instance
* @param {string} event - The event name for the hook
* @param {WaterfallHookFn} finalHandler - The final handler function that receives the transformed result
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, finalHandler, id) {
this.id = id;
this.event = event;
this.hooks = [];
this._finalHandler = finalHandler;
this.handler = async (...arguments_) => {
const initialArgs = arguments_.length === 1 ? arguments_[0] : arguments_;
const results = [];
for (const hook of this.hooks) {
const result = await hook({
initialArgs,
results: [...results]
});
results.push({
hook,
result
});
}
await this._finalHandler({
initialArgs,
results: [...results]
});
};
}
/**
* Adds a hook function to the end of the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to add
*/
addHook(hook) {
this.hooks.push(hook);
}
/**
* Removes a specific hook function from the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook) {
const index = this.hooks.indexOf(hook);
if (index !== -1) {
this.hooks.splice(index, 1);
return true;
}
return false;
}
};
//#endregion
//#region src/index.ts
var Hookified = class extends Eventified {
_hooks;
_throwOnHookError = false;
_enforceBeforeAfter = false;
_deprecatedHooks;
_allowDeprecated = true;
_useHookClone = true;
constructor(options) {
super({
eventLogger: options?.eventLogger,
throwOnEmitError: options?.throwOnEmitError,
throwOnEmptyListeners: options?.throwOnEmptyListeners
});
this._hooks = /* @__PURE__ */ new Map();
this._deprecatedHooks = options?.deprecatedHooks ? new Map(options.deprecatedHooks) : /* @__PURE__ */ new Map();
if (options?.throwOnHookError !== void 0) this._throwOnHookError = options.throwOnHookError;
if (options?.enforceBeforeAfter !== void 0) this._enforceBeforeAfter = options.enforceBeforeAfter;
if (options?.allowDeprecated !== void 0) this._allowDeprecated = options.allowDeprecated;
if (options?.useHookClone !== void 0) this._useHookClone = options.useHookClone;
}
/**
* Gets all hooks
* @returns {Map<string, IHook[]>}
*/
get hooks() {
return this._hooks;
}
/**
* Gets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnHookError() {
return this._throwOnHookError;
}
/**
* Sets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnHookError(value) {
this._throwOnHookError = value;
}
/**
* Gets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @returns {boolean}
* @default false
*/
get enforceBeforeAfter() {
return this._enforceBeforeAfter;
}
/**
* Sets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @param {boolean} value
*/
set enforceBeforeAfter(value) {
this._enforceBeforeAfter = value;
}
/**
* Gets the map of deprecated hook names to deprecation messages.
* @returns {Map<string, string>}
*/
get deprecatedHooks() {
return this._deprecatedHooks;
}
/**
* Sets the map of deprecated hook names to deprecation messages.
* @param {Map<string, string>} value
*/
set deprecatedHooks(value) {
this._deprecatedHooks = value;
}
/**
* Gets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @returns {boolean}
*/
get allowDeprecated() {
return this._allowDeprecated;
}
/**
* Sets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @param {boolean} value
*/
set allowDeprecated(value) {
this._allowDeprecated = value;
}
/**
* Gets whether hook objects are cloned before storing. Default is true.
* @returns {boolean}
*/
get useHookClone() {
return this._useHookClone;
}
/**
* Sets whether hook objects are cloned before storing. Default is true.
* When false, the original IHook reference is stored directly.
* @param {boolean} value
*/
set useHookClone(value) {
this._useHookClone = value;
}
onHook(hookOrEvent, optionsOrHandler) {
let hook;
let options;
if (typeof hookOrEvent === "string") {
if (typeof optionsOrHandler !== "function") throw new TypeError("When calling onHook(event, handler), the second argument must be a function");
hook = {
event: hookOrEvent,
handler: optionsOrHandler
};
options = void 0;
} else {
hook = hookOrEvent;
options = optionsOrHandler;
}
this.validateHookName(hook.event);
if (!this.checkDeprecatedHook(hook.event)) return;
const entry = options?.useHookClone ?? this._useHookClone ? {
id: hook.id,
event: hook.event,
handler: hook.handler
} : hook;
entry.id = entry.id ?? crypto.randomUUID();
const eventHandlers = this._hooks.get(hook.event);
if (eventHandlers) {
const existingIndex = eventHandlers.findIndex((h) => h.id === entry.id);
if (existingIndex !== -1) eventHandlers[existingIndex] = entry;
else {
const position = options?.position ?? "Bottom";
if (position === "Top") eventHandlers.unshift(entry);
else if (position === "Bottom") eventHandlers.push(entry);
else {
const index = Math.max(0, Math.min(position, eventHandlers.length));
eventHandlers.splice(index, 0, entry);
}
}
} else this._hooks.set(hook.event, [entry]);
return entry;
}
/**
* Alias for onHook. This is provided for compatibility with other libraries that use the `addHook` method.
* @param {string} event - the event name
* @param {HookFn} handler - the handler function
* @returns {void}
*/
addHook(event, handler) {
this.onHook({
event,
handler
});
}
/**
* Adds handler functions for specific events
* @param {Array<IHook>} hooks
* @param {OnHookOptions} [options] - optional per-call options (e.g., useHookClone override, position)
* @returns {void}
*/
onHooks(hooks, options) {
for (const hook of hooks) this.onHook(hook, options);
}
/**
* Adds a handler function for a specific event that runs before all other handlers.
* Equivalent to calling `onHook(hook, { position: "Top" })`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependHook(hook, options) {
return this.onHook(hook, {
...options,
position: "Top"
});
}
/**
* Adds a handler that only executes once for a specific event before all other handlers.
* Equivalent to calling `onHook` with a self-removing wrapper and `{ position: "Top" }`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependOnceHook(hook, options) {
const wrappedHandler = async (...arguments_) => {
this.removeHook({
event: hook.event,
handler: wrappedHandler
});
return hook.handler(...arguments_);
};
return this.onHook({
id: hook.id,
event: hook.event,
handler: wrappedHandler
}, {
...options,
position: "Top"
});
}
/**
* Adds a handler that only executes once for a specific event
* @param {IHook} hook - the hook containing event name and handler
*/
onceHook(hook) {
this.validateHookName(hook.event);
if (!this.checkDeprecatedHook(hook.event)) return;
const wrappedHandler = async (...arguments_) => {
this.removeHook({
event: hook.event,
handler: wrappedHandler
});
return hook.handler(...arguments_);
};
this.onHook({
id: hook.id,
event: hook.event,
handler: wrappedHandler
});
}
/**
* Removes a handler function for a specific event
* @param {IHook} hook - the hook containing event name and handler to remove
* @returns {IHook | undefined} the removed hook, or undefined if not found
*/
removeHook(hook) {
this.validateHookName(hook.event);
const eventHandlers = this._hooks.get(hook.event);
if (eventHandlers) {
const index = eventHandlers.findIndex((h) => h.handler === hook.handler);
if (index !== -1) {
eventHandlers.splice(index, 1);
if (eventHandlers.length === 0) this._hooks.delete(hook.event);
return {
event: hook.event,
handler: hook.handler
};
}
}
}
/**
* Removes multiple hook handlers
* @param {Array<IHook>} hooks
* @returns {IHook[]} the hooks that were successfully removed
*/
removeHooks(hooks) {
const removed = [];
for (const hook of hooks) {
const result = this.removeHook(hook);
if (result) removed.push(result);
}
return removed;
}
/**
* Calls all handlers for a specific event
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
async hook(event, ...arguments_) {
this.validateHookName(event);
if (!this.checkDeprecatedHook(event)) return;
const eventHandlers = this._hooks.get(event);
if (eventHandlers) for (const hook of [...eventHandlers]) try {
await hook.handler(...arguments_);
} catch (error) {
const message = `${event}: ${error.message}`;
this.emit("error", new Error(message));
if (this._throwOnHookError) throw new Error(message);
}
}
/**
* Calls all synchronous handlers for a specific event.
* Async handlers (declared with `async` keyword) are silently skipped.
*
* Note: The `hook` method is preferred as it executes both sync and async functions.
* Use `hookSync` only when you specifically need synchronous execution.
* @param {string} event
* @param {T[]} arguments_
* @returns {void}
*/
hookSync(event, ...arguments_) {
this.validateHookName(event);
if (!this.checkDeprecatedHook(event)) return;
const eventHandlers = this._hooks.get(event);
if (eventHandlers) for (const hook of [...eventHandlers]) {
if (hook.handler.constructor.name === "AsyncFunction") continue;
try {
hook.handler(...arguments_);
} catch (error) {
const message = `${event}: ${error.message}`;
this.emit("error", new Error(message));
if (this._throwOnHookError) throw new Error(message);
}
}
}
/**
* Prepends the word `before` to your hook. Example is event is `test`, the before hook is `before:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
async beforeHook(event, ...arguments_) {
await this.hook(`before:${event}`, ...arguments_);
}
/**
* Prepends the word `after` to your hook. Example is event is `test`, the after hook is `after:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
async afterHook(event, ...arguments_) {
await this.hook(`after:${event}`, ...arguments_);
}
/**
* Calls all handlers for a specific event. This is an alias for `hook` and is provided for
* compatibility with other libraries that use the `callHook` method.
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
async callHook(event, ...arguments_) {
await this.hook(event, ...arguments_);
}
/**
* Gets all hooks for a specific event
* @param {string} event
* @returns {IHook[]}
*/
getHooks(event) {
this.validateHookName(event);
return this._hooks.get(event);
}
/**
* Gets a specific hook by id, searching across all events
* @param {string} id - the hook id
* @returns {IHook | undefined} the hook if found, or undefined
*/
getHook(id) {
for (const eventHandlers of this._hooks.values()) {
const found = eventHandlers.find((h) => h.id === id);
if (found) return found;
}
}
/**
* Removes one or more hooks by id, searching across all events
* @param {string | string[]} id - the hook id or array of hook ids to remove
* @returns {IHook | IHook[] | undefined} the removed hook(s), or undefined/empty array if not found
*/
removeHookById(id) {
if (Array.isArray(id)) {
const removed = [];
for (const singleId of id) {
const result = this.removeHookById(singleId);
if (result && !Array.isArray(result)) removed.push(result);
}
return removed;
}
for (const [event, eventHandlers] of this._hooks.entries()) {
const index = eventHandlers.findIndex((h) => h.id === id);
if (index !== -1) {
const [removed] = eventHandlers.splice(index, 1);
if (eventHandlers.length === 0) this._hooks.delete(event);
return removed;
}
}
}
/**
* Removes all hooks
* @returns {void}
*/
clearHooks() {
this._hooks.clear();
}
/**
* Removes all hooks for a specific event and returns the removed hooks.
* @param {string} event - The event name to remove hooks for.
* @returns {IHook[]} the hooks that were removed
*/
removeEventHooks(event) {
this.validateHookName(event);
const eventHandlers = this._hooks.get(event);
if (eventHandlers) {
const removed = [...eventHandlers];
this._hooks.delete(event);
return removed;
}
return [];
}
/**
* Validates hook event name if enforceBeforeAfter is enabled
* @param {string} event - The event name to validate
* @throws {Error} If enforceBeforeAfter is true and event doesn't start with 'before' or 'after'
*/
validateHookName(event) {
if (this._enforceBeforeAfter) {
const eventValue = event.trim().toLocaleLowerCase();
if (!eventValue.startsWith("before") && !eventValue.startsWith("after")) throw new Error(`Hook event "${event}" must start with "before" or "after" when enforceBeforeAfter is enabled`);
}
}
/**
* Checks if a hook is deprecated and emits a warning if it is
* @param {string} event - The event name to check
* @returns {boolean} - Returns true if the hook should proceed, false if it should be blocked
*/
checkDeprecatedHook(event) {
if (this._deprecatedHooks.has(event)) {
const message = this._deprecatedHooks.get(event);
const warningMessage = `Hook "${event}" is deprecated${message ? `: ${message}` : ""}`;
this.emit("warn", {
hook: event,
message: warningMessage
});
return this._allowDeprecated;
}
return true;
}
};
//#endregion
exports.Eventified = Eventified;
exports.Hook = Hook;
exports.Hookified = Hookified;
exports.ParallelHook = ParallelHook;
exports.WaterfallHook = WaterfallHook;

View File

@@ -0,0 +1,771 @@
//#region src/types.d.ts
type Logger = {
trace: (message: string, ...arguments_: unknown[]) => void;
debug: (message: string, ...arguments_: unknown[]) => void;
info: (message: string, ...arguments_: unknown[]) => void;
warn: (message: string, ...arguments_: unknown[]) => void;
error: (message: string, ...arguments_: unknown[]) => void;
fatal: (message: string, ...arguments_: unknown[]) => void;
};
type EventEmitterOptions = {
/**
* Logger instance for logging events.
*/
eventLogger?: Logger;
/**
* Whether to throw an error when emit 'error' and there are no listeners. Default is false and only emits an error event.
*/
throwOnEmitError?: boolean;
/**
* Whether to throw on 'error' when there are no listeners. This is the standard functionality in EventEmitter
* @default true
*/
throwOnEmptyListeners?: boolean;
};
type IEventEmitter = {
/**
* Registers a listener for the specified event.
*
* @param eventName - The name (or symbol) of the event to listen for.
* @param listener - A callback function that will be invoked when the event is emitted.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.on('data', (message) => {
* console.log(message);
* });
*/
on(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Alias for `on`. Registers a listener for the specified event.
*
* @param eventName - The name (or symbol) of the event to listen for.
* @param listener - A callback function that will be invoked when the event is emitted.
* @returns The current instance of EventEmitter for method chaining.
*/
addListener(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Registers a one-time listener for the specified event. The listener is removed after it is called once.
*
* @param eventName - The name (or symbol) of the event to listen for.
* @param listener - A callback function that will be invoked once when the event is emitted.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.once('close', () => {
* console.log('The connection was closed.');
* });
*/
once(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Removes a previously registered listener for the specified event.
*
* @param eventName - The name (or symbol) of the event to stop listening for.
* @param listener - The specific callback function to remove.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.off('data', myListener);
*/
off(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Alias for `off`. Removes a previously registered listener for the specified event.
*
* @param eventName - The name (or symbol) of the event to stop listening for.
* @param listener - The specific callback function to remove.
* @returns The current instance of EventEmitter for method chaining.
*/
removeListener(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Emits the specified event, invoking all registered listeners with the provided arguments.
*
* @param eventName - The name (or symbol) of the event to emit.
* @param args - Arguments passed to each listener.
* @returns `true` if the event had listeners, `false` otherwise.
*
* @example
* emitter.emit('data', 'Hello World');
*/
emit(eventName: string | symbol, ...arguments_: any[]): boolean;
/**
* Returns the number of listeners registered for the specified event.
*
* @param eventName - The name (or symbol) of the event.
* @returns The number of registered listeners.
*
* @example
* const count = emitter.listenerCount('data');
* console.log(count); // e.g., 2
*/
listenerCount(eventName: string | symbol): number;
/**
* Removes all listeners for the specified event. If no event is specified, it removes all listeners for all events.
*
* @param eventName - (Optional) The name (or symbol) of the event.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.removeAllListeners('data');
*/
removeAllListeners(eventName?: string | symbol): IEventEmitter;
/**
* Returns an array of event names for which listeners have been registered.
*
* @returns An array of event names (or symbols).
*
* @example
* const events = emitter.eventNames();
* console.log(events); // e.g., ['data', 'close']
*/
eventNames(): Array<string | symbol>;
/**
* Returns an array of listeners registered for the specified event.
*
* @param eventName - The name (or symbol) of the event.
* @returns An array of listener functions.
*
* @example
* const listeners = emitter.listeners('data');
* console.log(listeners.length); // e.g., 2
*/
listeners(eventName: string | symbol): Array<(...arguments_: any[]) => void>;
/**
* Returns an array of raw listeners for the specified event. This includes listeners wrapped by internal mechanisms (e.g., once-only listeners).
*
* @param eventName - The name (or symbol) of the event.
* @returns An array of raw listener functions.
*
* @example
* const rawListeners = emitter.rawListeners('data');
*/
rawListeners(eventName: string | symbol): Array<(...arguments_: any[]) => void>;
/**
* Adds a listener to the beginning of the listeners array for the specified event.
*
* @param eventName - The name (or symbol) of the event to listen for.
* @param listener - A callback function that will be invoked when the event is emitted.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.prependListener('data', (message) => {
* console.log('This will run first.');
* });
*/
prependListener(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Adds a one-time listener to the beginning of the listeners array for the specified event.
*
* @param eventName - The name (or symbol) of the event to listen for.
* @param listener - A callback function that will be invoked once when the event is emitted.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.prependOnceListener('data', (message) => {
* console.log('This will run first and only once.');
* });
*/
prependOnceListener(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
};
type EventListener = (...arguments_: any[]) => void;
type HookFn = (...arguments_: any[]) => Promise<void> | void;
interface IHook {
/**
* Unique identifier for the hook. Auto-generated via crypto.randomUUID() if not provided.
*/
id?: string;
/**
* The event name for the hook
*/
event: string;
/**
* The handler function for the hook
*/
handler: HookFn;
}
type WaterfallHookResult = {
/**
* The hook function that produced this result
*/
hook: WaterfallHookFn;
/**
* The value returned by the hook
*/
result: any;
};
type WaterfallHookContext = {
/**
* The original arguments passed to the waterfall execution, before any hooks processed them.
*/
initialArgs: any;
/**
* Array of results from previous hooks in execution order, each containing the hook and its result.
* Empty for the first hook.
*/
results: WaterfallHookResult[];
};
type WaterfallHookFn = (context: WaterfallHookContext) => Promise<any> | any;
interface IWaterfallHook extends IHook {
/**
* Array of hook functions that are called sequentially.
* Each hook receives a WaterfallHookContext with initialArgs and results.
*/
hooks: WaterfallHookFn[];
/**
* Adds a hook function to the end of the waterfall chain
*/
addHook(hook: WaterfallHookFn): void;
/**
* Removes a specific hook function from the waterfall chain
*/
removeHook(hook: WaterfallHookFn): boolean;
}
type ParallelHookContext<TArgs = any> = {
/**
* The original arguments passed to the parallel execution.
* Every hook receives this same value; hooks do not see each other's results.
*/
initialArgs: TArgs;
};
type ParallelHookFn<TArgs = any, TResult = any> = (context: ParallelHookContext<TArgs>) => Promise<TResult> | TResult;
type ParallelHookResult<TResult = any> = {
status: "fulfilled";
/**
* The value returned by the hook
*/
result: TResult;
} | {
status: "rejected";
/**
* The error or value the hook rejected with. Errors in JS can be of
* any type, so this stays `unknown` regardless of the result generic.
*/
reason: unknown;
};
type ParallelHookFinalContext<TArgs = any, TResult = any> = {
/**
* The original arguments passed to the parallel execution.
*/
initialArgs: TArgs;
/**
* Aggregated outcomes from every parallel hook, keyed by the hook function
* reference for direct lookup. Iteration order matches registration order.
*/
results: Map<ParallelHookFn<TArgs, TResult>, ParallelHookResult<TResult>>;
};
type ParallelHookFinalFn<TArgs = any, TResult = any> = (context: ParallelHookFinalContext<TArgs, TResult>) => Promise<void> | void;
interface IParallelHook<TArgs = any, TResult = any> extends IHook {
/**
* Array of hook functions that are called concurrently via Promise.allSettled.
* Each hook receives a ParallelHookContext with only initialArgs.
*/
hooks: ParallelHookFn<TArgs, TResult>[];
/**
* Adds a hook function to the parallel set
*/
addHook(hook: ParallelHookFn<TArgs, TResult>): void;
/**
* Removes a specific hook function from the parallel set
*/
removeHook(hook: ParallelHookFn<TArgs, TResult>): boolean;
}
type OnHookOptions = {
/**
* Per-call override for useHookClone.
* When true, hook objects are cloned before storing.
* When false, the original IHook reference is stored directly.
* When undefined, falls back to the instance-level useHookClone setting.
* @type {boolean}
*/
useHookClone?: boolean;
/**
* Controls where the hook is inserted in the handlers array.
* - "Top": Insert at the beginning (index 0), before all existing handlers.
* - "Bottom": Append to the end, after all existing handlers. This is the default.
* - number: Insert at a specific index. Values are clamped to the array bounds.
*/
position?: "Top" | "Bottom" | number;
};
type PrependHookOptions = Omit<OnHookOptions, "position">;
type HookifiedOptions = {
/**
* Whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
*/
throwOnHookError?: boolean;
/**
* Whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @type {boolean}
* @default false
*/
enforceBeforeAfter?: boolean;
/**
* Map of deprecated hook names to deprecation messages. When a deprecated hook is used, a warning will be emitted.
* @type {Map<string, string>}
* @default new Map()
*/
deprecatedHooks?: Map<string, string>;
/**
* Whether to allow deprecated hooks to be registered and executed. Default is true.
* @type {boolean}
* @default true
*/
allowDeprecated?: boolean;
/**
* Whether to clone hook objects before storing. Default is true.
* When false, the original IHook reference is stored directly.
* @type {boolean}
* @default true
*/
useHookClone?: boolean;
} & EventEmitterOptions;
//#endregion
//#region src/eventified.d.ts
declare class Eventified implements IEventEmitter {
private readonly _eventListeners;
private _maxListeners;
private _eventLogger?;
private _throwOnEmitError;
private _throwOnEmptyListeners;
constructor(options?: EventEmitterOptions);
/**
* Gets the event logger
* @returns {Logger}
*/
get eventLogger(): Logger | undefined;
/**
* Sets the event logger
* @param {Logger} eventLogger
*/
set eventLogger(eventLogger: Logger | undefined);
/**
* Gets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnEmitError(): boolean;
/**
* Sets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnEmitError(value: boolean);
/**
* Gets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @returns {boolean}
*/
get throwOnEmptyListeners(): boolean;
/**
* Sets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @param {boolean} value
*/
set throwOnEmptyListeners(value: boolean);
/**
* Adds a handler function for a specific event that will run only once
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
once(eventName: string | symbol, listener: EventListener): IEventEmitter;
/**
* Gets the number of listeners for a specific event. If no event is provided, it returns the total number of listeners
* @param {string} eventName The event name. Not required
* @returns {number} The number of listeners
*/
listenerCount(eventName?: string | symbol): number;
/**
* Gets an array of event names
* @returns {Array<string | symbol>} An array of event names
*/
eventNames(): Array<string | symbol>;
/**
* Gets an array of listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
rawListeners(event?: string | symbol): EventListener[];
/**
* Prepends a listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependListener(eventName: string | symbol, listener: EventListener): IEventEmitter;
/**
* Prepends a one-time listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependOnceListener(eventName: string | symbol, listener: EventListener): IEventEmitter;
/**
* Gets the maximum number of listeners that can be added for a single event
* @returns {number} The maximum number of listeners
*/
maxListeners(): number;
/**
* Adds a listener for a specific event. It is an alias for the on() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
addListener(event: string | symbol, listener: EventListener): IEventEmitter;
/**
* Adds a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
on(event: string | symbol, listener: EventListener): IEventEmitter;
/**
* Removes a listener for a specific event. It is an alias for the off() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeListener(event: string, listener: EventListener): IEventEmitter;
/**
* Removes a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
off(event: string | symbol, listener: EventListener): IEventEmitter;
/**
* Calls all listeners for a specific event
* @param {string | symbol} event
* @param arguments_ The arguments to pass to the listeners
* @returns {boolean} Returns true if the event had listeners, false otherwise
*/
emit(event: string | symbol, ...arguments_: any[]): boolean;
/**
* Gets all listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
listeners(event: string | symbol): EventListener[];
/**
* Removes all listeners for a specific event. If no event is provided, it removes all listeners
* @param {string} [event] (Optional) The event name
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeAllListeners(event?: string | symbol): IEventEmitter;
/**
* Sets the maximum number of listeners that can be added for a single event
* @param {number} n The maximum number of listeners
* @returns {void}
*/
setMaxListeners(n: number): void;
/**
* Gets all listeners
* @returns {EventListener[]} An array of listeners
*/
getAllListeners(): EventListener[];
/**
* Sends a log message using the configured logger based on the event name
* @param {string | symbol} eventName - The event name that determines the log level
* @param {unknown} data - The data to log
*/
private sendToEventLogger;
}
//#endregion
//#region src/hooks/hook.d.ts
/**
* Concrete implementation of the IHook interface.
* Provides a convenient class-based way to create hook entries.
*/
declare class Hook implements IHook {
id?: string;
event: string;
handler: HookFn;
/**
* Creates a new Hook instance
* @param {string} event - The event name for the hook
* @param {HookFn} handler - The handler function for the hook
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event: string, handler: HookFn, id?: string);
}
//#endregion
//#region src/hooks/parallel-hook.d.ts
/**
* A ParallelHook fans a single invocation out to many registered hook
* functions concurrently via Promise.allSettled, then calls a final
* handler with the aggregated results — including failures — keyed by
* the hook function reference for direct lookup. Each hook receives only
* the original arguments; hooks do not see each other's results.
*
* Implements IHook for compatibility with Hookified.onHook(); the final
* handler is called regardless of whether the parallel hook is invoked
* directly or through Hookified.hook().
*
* Generics tighten the per-hook signature when every hook in the set
* accepts the same `initialArgs` and returns the same result type.
* Both default to `any` for backwards compatibility.
*
* @template TArgs - The shape of `initialArgs` passed to every hook
* @template TResult - The result type each hook returns
*/
declare class ParallelHook<TArgs = any, TResult = any> implements IParallelHook<TArgs, TResult> {
id?: string;
event: string;
handler: HookFn;
hooks: ParallelHookFn<TArgs, TResult>[];
private readonly _finalHandler;
/**
* Creates a new ParallelHook instance
* @param {string} event - The event name for the hook
* @param {ParallelHookFinalFn<TArgs, TResult>} finalHandler - Called once with `{ initialArgs, results }` after all parallel hooks settle
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event: string, finalHandler: ParallelHookFinalFn<TArgs, TResult>, id?: string);
/**
* Adds a hook function to the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to add
*/
addHook(hook: ParallelHookFn<TArgs, TResult>): void;
/**
* Removes a specific hook function from the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook: ParallelHookFn<TArgs, TResult>): boolean;
}
//#endregion
//#region src/hooks/waterfall-hook.d.ts
/**
* A WaterfallHook chains multiple hook functions sequentially,
* where each hook receives a context with the previous result,
* initial arguments, and accumulated results. After all hooks
* have executed, the final handler receives the transformed result.
* Implements IHook for compatibility with Hookified.onHook().
*/
declare class WaterfallHook implements IWaterfallHook {
id?: string;
event: string;
handler: HookFn;
hooks: WaterfallHookFn[];
private readonly _finalHandler;
/**
* Creates a new WaterfallHook instance
* @param {string} event - The event name for the hook
* @param {WaterfallHookFn} finalHandler - The final handler function that receives the transformed result
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event: string, finalHandler: WaterfallHookFn, id?: string);
/**
* Adds a hook function to the end of the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to add
*/
addHook(hook: WaterfallHookFn): void;
/**
* Removes a specific hook function from the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook: WaterfallHookFn): boolean;
}
//#endregion
//#region src/index.d.ts
declare class Hookified extends Eventified {
private readonly _hooks;
private _throwOnHookError;
private _enforceBeforeAfter;
private _deprecatedHooks;
private _allowDeprecated;
private _useHookClone;
constructor(options?: HookifiedOptions);
/**
* Gets all hooks
* @returns {Map<string, IHook[]>}
*/
get hooks(): Map<string, IHook[]>;
/**
* Gets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnHookError(): boolean;
/**
* Sets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnHookError(value: boolean);
/**
* Gets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @returns {boolean}
* @default false
*/
get enforceBeforeAfter(): boolean;
/**
* Sets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @param {boolean} value
*/
set enforceBeforeAfter(value: boolean);
/**
* Gets the map of deprecated hook names to deprecation messages.
* @returns {Map<string, string>}
*/
get deprecatedHooks(): Map<string, string>;
/**
* Sets the map of deprecated hook names to deprecation messages.
* @param {Map<string, string>} value
*/
set deprecatedHooks(value: Map<string, string>);
/**
* Gets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @returns {boolean}
*/
get allowDeprecated(): boolean;
/**
* Sets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @param {boolean} value
*/
set allowDeprecated(value: boolean);
/**
* Gets whether hook objects are cloned before storing. Default is true.
* @returns {boolean}
*/
get useHookClone(): boolean;
/**
* Sets whether hook objects are cloned before storing. Default is true.
* When false, the original IHook reference is stored directly.
* @param {boolean} value
*/
set useHookClone(value: boolean);
/**
* Adds a handler function for a specific event.
* Supports both object and legacy signatures:
* onHook({ event, handler }, options?)
* onHook(event, handler)
* To register multiple hooks at once, use {@link onHooks}.
* @param {IHook | string} hookOrEvent - the hook object or event name
* @param {OnHookOptions | HookFn} [optionsOrHandler] - options (when using object form) or handler function (when using string form)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
onHook(hook: IHook, options?: OnHookOptions): IHook | undefined;
onHook(event: string, handler: HookFn): IHook | undefined;
/**
* Alias for onHook. This is provided for compatibility with other libraries that use the `addHook` method.
* @param {string} event - the event name
* @param {HookFn} handler - the handler function
* @returns {void}
*/
addHook(event: string, handler: HookFn): void;
/**
* Adds handler functions for specific events
* @param {Array<IHook>} hooks
* @param {OnHookOptions} [options] - optional per-call options (e.g., useHookClone override, position)
* @returns {void}
*/
onHooks(hooks: IHook[], options?: OnHookOptions): void;
/**
* Adds a handler function for a specific event that runs before all other handlers.
* Equivalent to calling `onHook(hook, { position: "Top" })`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependHook(hook: IHook, options?: PrependHookOptions): IHook | undefined;
/**
* Adds a handler that only executes once for a specific event before all other handlers.
* Equivalent to calling `onHook` with a self-removing wrapper and `{ position: "Top" }`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependOnceHook(hook: IHook, options?: PrependHookOptions): IHook | undefined;
/**
* Adds a handler that only executes once for a specific event
* @param {IHook} hook - the hook containing event name and handler
*/
onceHook(hook: IHook): void;
/**
* Removes a handler function for a specific event
* @param {IHook} hook - the hook containing event name and handler to remove
* @returns {IHook | undefined} the removed hook, or undefined if not found
*/
removeHook(hook: IHook): IHook | undefined;
/**
* Removes multiple hook handlers
* @param {Array<IHook>} hooks
* @returns {IHook[]} the hooks that were successfully removed
*/
removeHooks(hooks: IHook[]): IHook[];
/**
* Calls all handlers for a specific event
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
hook<T>(event: string, ...arguments_: T[]): Promise<void>;
/**
* Calls all synchronous handlers for a specific event.
* Async handlers (declared with `async` keyword) are silently skipped.
*
* Note: The `hook` method is preferred as it executes both sync and async functions.
* Use `hookSync` only when you specifically need synchronous execution.
* @param {string} event
* @param {T[]} arguments_
* @returns {void}
*/
hookSync<T>(event: string, ...arguments_: T[]): void;
/**
* Prepends the word `before` to your hook. Example is event is `test`, the before hook is `before:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
beforeHook<T>(event: string, ...arguments_: T[]): Promise<void>;
/**
* Prepends the word `after` to your hook. Example is event is `test`, the after hook is `after:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
afterHook<T>(event: string, ...arguments_: T[]): Promise<void>;
/**
* Calls all handlers for a specific event. This is an alias for `hook` and is provided for
* compatibility with other libraries that use the `callHook` method.
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
callHook<T>(event: string, ...arguments_: T[]): Promise<void>;
/**
* Gets all hooks for a specific event
* @param {string} event
* @returns {IHook[]}
*/
getHooks(event: string): IHook[] | undefined;
/**
* Gets a specific hook by id, searching across all events
* @param {string} id - the hook id
* @returns {IHook | undefined} the hook if found, or undefined
*/
getHook(id: string): IHook | undefined;
/**
* Removes one or more hooks by id, searching across all events
* @param {string | string[]} id - the hook id or array of hook ids to remove
* @returns {IHook | IHook[] | undefined} the removed hook(s), or undefined/empty array if not found
*/
removeHookById(id: string | string[]): IHook | IHook[] | undefined;
/**
* Removes all hooks
* @returns {void}
*/
clearHooks(): void;
/**
* Removes all hooks for a specific event and returns the removed hooks.
* @param {string} event - The event name to remove hooks for.
* @returns {IHook[]} the hooks that were removed
*/
removeEventHooks(event: string): IHook[];
/**
* Validates hook event name if enforceBeforeAfter is enabled
* @param {string} event - The event name to validate
* @throws {Error} If enforceBeforeAfter is true and event doesn't start with 'before' or 'after'
*/
private validateHookName;
/**
* Checks if a hook is deprecated and emits a warning if it is
* @param {string} event - The event name to check
* @returns {boolean} - Returns true if the hook should proceed, false if it should be blocked
*/
private checkDeprecatedHook;
}
//#endregion
export { type EventEmitterOptions, type EventListener, Eventified, Hook, type HookFn, Hookified, type HookifiedOptions, type IEventEmitter, type IHook, type IParallelHook, type IWaterfallHook, type Logger, type OnHookOptions, ParallelHook, type ParallelHookContext, type ParallelHookFinalContext, type ParallelHookFinalFn, type ParallelHookFn, type ParallelHookResult, type PrependHookOptions, WaterfallHook, type WaterfallHookContext, type WaterfallHookFn, type WaterfallHookResult };

View File

@@ -0,0 +1,771 @@
//#region src/types.d.ts
type Logger = {
trace: (message: string, ...arguments_: unknown[]) => void;
debug: (message: string, ...arguments_: unknown[]) => void;
info: (message: string, ...arguments_: unknown[]) => void;
warn: (message: string, ...arguments_: unknown[]) => void;
error: (message: string, ...arguments_: unknown[]) => void;
fatal: (message: string, ...arguments_: unknown[]) => void;
};
type EventEmitterOptions = {
/**
* Logger instance for logging events.
*/
eventLogger?: Logger;
/**
* Whether to throw an error when emit 'error' and there are no listeners. Default is false and only emits an error event.
*/
throwOnEmitError?: boolean;
/**
* Whether to throw on 'error' when there are no listeners. This is the standard functionality in EventEmitter
* @default true
*/
throwOnEmptyListeners?: boolean;
};
type IEventEmitter = {
/**
* Registers a listener for the specified event.
*
* @param eventName - The name (or symbol) of the event to listen for.
* @param listener - A callback function that will be invoked when the event is emitted.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.on('data', (message) => {
* console.log(message);
* });
*/
on(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Alias for `on`. Registers a listener for the specified event.
*
* @param eventName - The name (or symbol) of the event to listen for.
* @param listener - A callback function that will be invoked when the event is emitted.
* @returns The current instance of EventEmitter for method chaining.
*/
addListener(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Registers a one-time listener for the specified event. The listener is removed after it is called once.
*
* @param eventName - The name (or symbol) of the event to listen for.
* @param listener - A callback function that will be invoked once when the event is emitted.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.once('close', () => {
* console.log('The connection was closed.');
* });
*/
once(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Removes a previously registered listener for the specified event.
*
* @param eventName - The name (or symbol) of the event to stop listening for.
* @param listener - The specific callback function to remove.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.off('data', myListener);
*/
off(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Alias for `off`. Removes a previously registered listener for the specified event.
*
* @param eventName - The name (or symbol) of the event to stop listening for.
* @param listener - The specific callback function to remove.
* @returns The current instance of EventEmitter for method chaining.
*/
removeListener(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Emits the specified event, invoking all registered listeners with the provided arguments.
*
* @param eventName - The name (or symbol) of the event to emit.
* @param args - Arguments passed to each listener.
* @returns `true` if the event had listeners, `false` otherwise.
*
* @example
* emitter.emit('data', 'Hello World');
*/
emit(eventName: string | symbol, ...arguments_: any[]): boolean;
/**
* Returns the number of listeners registered for the specified event.
*
* @param eventName - The name (or symbol) of the event.
* @returns The number of registered listeners.
*
* @example
* const count = emitter.listenerCount('data');
* console.log(count); // e.g., 2
*/
listenerCount(eventName: string | symbol): number;
/**
* Removes all listeners for the specified event. If no event is specified, it removes all listeners for all events.
*
* @param eventName - (Optional) The name (or symbol) of the event.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.removeAllListeners('data');
*/
removeAllListeners(eventName?: string | symbol): IEventEmitter;
/**
* Returns an array of event names for which listeners have been registered.
*
* @returns An array of event names (or symbols).
*
* @example
* const events = emitter.eventNames();
* console.log(events); // e.g., ['data', 'close']
*/
eventNames(): Array<string | symbol>;
/**
* Returns an array of listeners registered for the specified event.
*
* @param eventName - The name (or symbol) of the event.
* @returns An array of listener functions.
*
* @example
* const listeners = emitter.listeners('data');
* console.log(listeners.length); // e.g., 2
*/
listeners(eventName: string | symbol): Array<(...arguments_: any[]) => void>;
/**
* Returns an array of raw listeners for the specified event. This includes listeners wrapped by internal mechanisms (e.g., once-only listeners).
*
* @param eventName - The name (or symbol) of the event.
* @returns An array of raw listener functions.
*
* @example
* const rawListeners = emitter.rawListeners('data');
*/
rawListeners(eventName: string | symbol): Array<(...arguments_: any[]) => void>;
/**
* Adds a listener to the beginning of the listeners array for the specified event.
*
* @param eventName - The name (or symbol) of the event to listen for.
* @param listener - A callback function that will be invoked when the event is emitted.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.prependListener('data', (message) => {
* console.log('This will run first.');
* });
*/
prependListener(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
/**
* Adds a one-time listener to the beginning of the listeners array for the specified event.
*
* @param eventName - The name (or symbol) of the event to listen for.
* @param listener - A callback function that will be invoked once when the event is emitted.
* @returns The current instance of EventEmitter for method chaining.
*
* @example
* emitter.prependOnceListener('data', (message) => {
* console.log('This will run first and only once.');
* });
*/
prependOnceListener(eventName: string | symbol, listener: (...arguments_: any[]) => void): IEventEmitter;
};
type EventListener = (...arguments_: any[]) => void;
type HookFn = (...arguments_: any[]) => Promise<void> | void;
interface IHook {
/**
* Unique identifier for the hook. Auto-generated via crypto.randomUUID() if not provided.
*/
id?: string;
/**
* The event name for the hook
*/
event: string;
/**
* The handler function for the hook
*/
handler: HookFn;
}
type WaterfallHookResult = {
/**
* The hook function that produced this result
*/
hook: WaterfallHookFn;
/**
* The value returned by the hook
*/
result: any;
};
type WaterfallHookContext = {
/**
* The original arguments passed to the waterfall execution, before any hooks processed them.
*/
initialArgs: any;
/**
* Array of results from previous hooks in execution order, each containing the hook and its result.
* Empty for the first hook.
*/
results: WaterfallHookResult[];
};
type WaterfallHookFn = (context: WaterfallHookContext) => Promise<any> | any;
interface IWaterfallHook extends IHook {
/**
* Array of hook functions that are called sequentially.
* Each hook receives a WaterfallHookContext with initialArgs and results.
*/
hooks: WaterfallHookFn[];
/**
* Adds a hook function to the end of the waterfall chain
*/
addHook(hook: WaterfallHookFn): void;
/**
* Removes a specific hook function from the waterfall chain
*/
removeHook(hook: WaterfallHookFn): boolean;
}
type ParallelHookContext<TArgs = any> = {
/**
* The original arguments passed to the parallel execution.
* Every hook receives this same value; hooks do not see each other's results.
*/
initialArgs: TArgs;
};
type ParallelHookFn<TArgs = any, TResult = any> = (context: ParallelHookContext<TArgs>) => Promise<TResult> | TResult;
type ParallelHookResult<TResult = any> = {
status: "fulfilled";
/**
* The value returned by the hook
*/
result: TResult;
} | {
status: "rejected";
/**
* The error or value the hook rejected with. Errors in JS can be of
* any type, so this stays `unknown` regardless of the result generic.
*/
reason: unknown;
};
type ParallelHookFinalContext<TArgs = any, TResult = any> = {
/**
* The original arguments passed to the parallel execution.
*/
initialArgs: TArgs;
/**
* Aggregated outcomes from every parallel hook, keyed by the hook function
* reference for direct lookup. Iteration order matches registration order.
*/
results: Map<ParallelHookFn<TArgs, TResult>, ParallelHookResult<TResult>>;
};
type ParallelHookFinalFn<TArgs = any, TResult = any> = (context: ParallelHookFinalContext<TArgs, TResult>) => Promise<void> | void;
interface IParallelHook<TArgs = any, TResult = any> extends IHook {
/**
* Array of hook functions that are called concurrently via Promise.allSettled.
* Each hook receives a ParallelHookContext with only initialArgs.
*/
hooks: ParallelHookFn<TArgs, TResult>[];
/**
* Adds a hook function to the parallel set
*/
addHook(hook: ParallelHookFn<TArgs, TResult>): void;
/**
* Removes a specific hook function from the parallel set
*/
removeHook(hook: ParallelHookFn<TArgs, TResult>): boolean;
}
type OnHookOptions = {
/**
* Per-call override for useHookClone.
* When true, hook objects are cloned before storing.
* When false, the original IHook reference is stored directly.
* When undefined, falls back to the instance-level useHookClone setting.
* @type {boolean}
*/
useHookClone?: boolean;
/**
* Controls where the hook is inserted in the handlers array.
* - "Top": Insert at the beginning (index 0), before all existing handlers.
* - "Bottom": Append to the end, after all existing handlers. This is the default.
* - number: Insert at a specific index. Values are clamped to the array bounds.
*/
position?: "Top" | "Bottom" | number;
};
type PrependHookOptions = Omit<OnHookOptions, "position">;
type HookifiedOptions = {
/**
* Whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
*/
throwOnHookError?: boolean;
/**
* Whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @type {boolean}
* @default false
*/
enforceBeforeAfter?: boolean;
/**
* Map of deprecated hook names to deprecation messages. When a deprecated hook is used, a warning will be emitted.
* @type {Map<string, string>}
* @default new Map()
*/
deprecatedHooks?: Map<string, string>;
/**
* Whether to allow deprecated hooks to be registered and executed. Default is true.
* @type {boolean}
* @default true
*/
allowDeprecated?: boolean;
/**
* Whether to clone hook objects before storing. Default is true.
* When false, the original IHook reference is stored directly.
* @type {boolean}
* @default true
*/
useHookClone?: boolean;
} & EventEmitterOptions;
//#endregion
//#region src/eventified.d.ts
declare class Eventified implements IEventEmitter {
private readonly _eventListeners;
private _maxListeners;
private _eventLogger?;
private _throwOnEmitError;
private _throwOnEmptyListeners;
constructor(options?: EventEmitterOptions);
/**
* Gets the event logger
* @returns {Logger}
*/
get eventLogger(): Logger | undefined;
/**
* Sets the event logger
* @param {Logger} eventLogger
*/
set eventLogger(eventLogger: Logger | undefined);
/**
* Gets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnEmitError(): boolean;
/**
* Sets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnEmitError(value: boolean);
/**
* Gets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @returns {boolean}
*/
get throwOnEmptyListeners(): boolean;
/**
* Sets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @param {boolean} value
*/
set throwOnEmptyListeners(value: boolean);
/**
* Adds a handler function for a specific event that will run only once
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
once(eventName: string | symbol, listener: EventListener): IEventEmitter;
/**
* Gets the number of listeners for a specific event. If no event is provided, it returns the total number of listeners
* @param {string} eventName The event name. Not required
* @returns {number} The number of listeners
*/
listenerCount(eventName?: string | symbol): number;
/**
* Gets an array of event names
* @returns {Array<string | symbol>} An array of event names
*/
eventNames(): Array<string | symbol>;
/**
* Gets an array of listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
rawListeners(event?: string | symbol): EventListener[];
/**
* Prepends a listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependListener(eventName: string | symbol, listener: EventListener): IEventEmitter;
/**
* Prepends a one-time listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependOnceListener(eventName: string | symbol, listener: EventListener): IEventEmitter;
/**
* Gets the maximum number of listeners that can be added for a single event
* @returns {number} The maximum number of listeners
*/
maxListeners(): number;
/**
* Adds a listener for a specific event. It is an alias for the on() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
addListener(event: string | symbol, listener: EventListener): IEventEmitter;
/**
* Adds a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
on(event: string | symbol, listener: EventListener): IEventEmitter;
/**
* Removes a listener for a specific event. It is an alias for the off() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeListener(event: string, listener: EventListener): IEventEmitter;
/**
* Removes a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
off(event: string | symbol, listener: EventListener): IEventEmitter;
/**
* Calls all listeners for a specific event
* @param {string | symbol} event
* @param arguments_ The arguments to pass to the listeners
* @returns {boolean} Returns true if the event had listeners, false otherwise
*/
emit(event: string | symbol, ...arguments_: any[]): boolean;
/**
* Gets all listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
listeners(event: string | symbol): EventListener[];
/**
* Removes all listeners for a specific event. If no event is provided, it removes all listeners
* @param {string} [event] (Optional) The event name
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeAllListeners(event?: string | symbol): IEventEmitter;
/**
* Sets the maximum number of listeners that can be added for a single event
* @param {number} n The maximum number of listeners
* @returns {void}
*/
setMaxListeners(n: number): void;
/**
* Gets all listeners
* @returns {EventListener[]} An array of listeners
*/
getAllListeners(): EventListener[];
/**
* Sends a log message using the configured logger based on the event name
* @param {string | symbol} eventName - The event name that determines the log level
* @param {unknown} data - The data to log
*/
private sendToEventLogger;
}
//#endregion
//#region src/hooks/hook.d.ts
/**
* Concrete implementation of the IHook interface.
* Provides a convenient class-based way to create hook entries.
*/
declare class Hook implements IHook {
id?: string;
event: string;
handler: HookFn;
/**
* Creates a new Hook instance
* @param {string} event - The event name for the hook
* @param {HookFn} handler - The handler function for the hook
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event: string, handler: HookFn, id?: string);
}
//#endregion
//#region src/hooks/parallel-hook.d.ts
/**
* A ParallelHook fans a single invocation out to many registered hook
* functions concurrently via Promise.allSettled, then calls a final
* handler with the aggregated results — including failures — keyed by
* the hook function reference for direct lookup. Each hook receives only
* the original arguments; hooks do not see each other's results.
*
* Implements IHook for compatibility with Hookified.onHook(); the final
* handler is called regardless of whether the parallel hook is invoked
* directly or through Hookified.hook().
*
* Generics tighten the per-hook signature when every hook in the set
* accepts the same `initialArgs` and returns the same result type.
* Both default to `any` for backwards compatibility.
*
* @template TArgs - The shape of `initialArgs` passed to every hook
* @template TResult - The result type each hook returns
*/
declare class ParallelHook<TArgs = any, TResult = any> implements IParallelHook<TArgs, TResult> {
id?: string;
event: string;
handler: HookFn;
hooks: ParallelHookFn<TArgs, TResult>[];
private readonly _finalHandler;
/**
* Creates a new ParallelHook instance
* @param {string} event - The event name for the hook
* @param {ParallelHookFinalFn<TArgs, TResult>} finalHandler - Called once with `{ initialArgs, results }` after all parallel hooks settle
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event: string, finalHandler: ParallelHookFinalFn<TArgs, TResult>, id?: string);
/**
* Adds a hook function to the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to add
*/
addHook(hook: ParallelHookFn<TArgs, TResult>): void;
/**
* Removes a specific hook function from the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook: ParallelHookFn<TArgs, TResult>): boolean;
}
//#endregion
//#region src/hooks/waterfall-hook.d.ts
/**
* A WaterfallHook chains multiple hook functions sequentially,
* where each hook receives a context with the previous result,
* initial arguments, and accumulated results. After all hooks
* have executed, the final handler receives the transformed result.
* Implements IHook for compatibility with Hookified.onHook().
*/
declare class WaterfallHook implements IWaterfallHook {
id?: string;
event: string;
handler: HookFn;
hooks: WaterfallHookFn[];
private readonly _finalHandler;
/**
* Creates a new WaterfallHook instance
* @param {string} event - The event name for the hook
* @param {WaterfallHookFn} finalHandler - The final handler function that receives the transformed result
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event: string, finalHandler: WaterfallHookFn, id?: string);
/**
* Adds a hook function to the end of the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to add
*/
addHook(hook: WaterfallHookFn): void;
/**
* Removes a specific hook function from the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook: WaterfallHookFn): boolean;
}
//#endregion
//#region src/index.d.ts
declare class Hookified extends Eventified {
private readonly _hooks;
private _throwOnHookError;
private _enforceBeforeAfter;
private _deprecatedHooks;
private _allowDeprecated;
private _useHookClone;
constructor(options?: HookifiedOptions);
/**
* Gets all hooks
* @returns {Map<string, IHook[]>}
*/
get hooks(): Map<string, IHook[]>;
/**
* Gets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnHookError(): boolean;
/**
* Sets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnHookError(value: boolean);
/**
* Gets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @returns {boolean}
* @default false
*/
get enforceBeforeAfter(): boolean;
/**
* Sets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @param {boolean} value
*/
set enforceBeforeAfter(value: boolean);
/**
* Gets the map of deprecated hook names to deprecation messages.
* @returns {Map<string, string>}
*/
get deprecatedHooks(): Map<string, string>;
/**
* Sets the map of deprecated hook names to deprecation messages.
* @param {Map<string, string>} value
*/
set deprecatedHooks(value: Map<string, string>);
/**
* Gets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @returns {boolean}
*/
get allowDeprecated(): boolean;
/**
* Sets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @param {boolean} value
*/
set allowDeprecated(value: boolean);
/**
* Gets whether hook objects are cloned before storing. Default is true.
* @returns {boolean}
*/
get useHookClone(): boolean;
/**
* Sets whether hook objects are cloned before storing. Default is true.
* When false, the original IHook reference is stored directly.
* @param {boolean} value
*/
set useHookClone(value: boolean);
/**
* Adds a handler function for a specific event.
* Supports both object and legacy signatures:
* onHook({ event, handler }, options?)
* onHook(event, handler)
* To register multiple hooks at once, use {@link onHooks}.
* @param {IHook | string} hookOrEvent - the hook object or event name
* @param {OnHookOptions | HookFn} [optionsOrHandler] - options (when using object form) or handler function (when using string form)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
onHook(hook: IHook, options?: OnHookOptions): IHook | undefined;
onHook(event: string, handler: HookFn): IHook | undefined;
/**
* Alias for onHook. This is provided for compatibility with other libraries that use the `addHook` method.
* @param {string} event - the event name
* @param {HookFn} handler - the handler function
* @returns {void}
*/
addHook(event: string, handler: HookFn): void;
/**
* Adds handler functions for specific events
* @param {Array<IHook>} hooks
* @param {OnHookOptions} [options] - optional per-call options (e.g., useHookClone override, position)
* @returns {void}
*/
onHooks(hooks: IHook[], options?: OnHookOptions): void;
/**
* Adds a handler function for a specific event that runs before all other handlers.
* Equivalent to calling `onHook(hook, { position: "Top" })`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependHook(hook: IHook, options?: PrependHookOptions): IHook | undefined;
/**
* Adds a handler that only executes once for a specific event before all other handlers.
* Equivalent to calling `onHook` with a self-removing wrapper and `{ position: "Top" }`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependOnceHook(hook: IHook, options?: PrependHookOptions): IHook | undefined;
/**
* Adds a handler that only executes once for a specific event
* @param {IHook} hook - the hook containing event name and handler
*/
onceHook(hook: IHook): void;
/**
* Removes a handler function for a specific event
* @param {IHook} hook - the hook containing event name and handler to remove
* @returns {IHook | undefined} the removed hook, or undefined if not found
*/
removeHook(hook: IHook): IHook | undefined;
/**
* Removes multiple hook handlers
* @param {Array<IHook>} hooks
* @returns {IHook[]} the hooks that were successfully removed
*/
removeHooks(hooks: IHook[]): IHook[];
/**
* Calls all handlers for a specific event
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
hook<T>(event: string, ...arguments_: T[]): Promise<void>;
/**
* Calls all synchronous handlers for a specific event.
* Async handlers (declared with `async` keyword) are silently skipped.
*
* Note: The `hook` method is preferred as it executes both sync and async functions.
* Use `hookSync` only when you specifically need synchronous execution.
* @param {string} event
* @param {T[]} arguments_
* @returns {void}
*/
hookSync<T>(event: string, ...arguments_: T[]): void;
/**
* Prepends the word `before` to your hook. Example is event is `test`, the before hook is `before:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
beforeHook<T>(event: string, ...arguments_: T[]): Promise<void>;
/**
* Prepends the word `after` to your hook. Example is event is `test`, the after hook is `after:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
afterHook<T>(event: string, ...arguments_: T[]): Promise<void>;
/**
* Calls all handlers for a specific event. This is an alias for `hook` and is provided for
* compatibility with other libraries that use the `callHook` method.
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
callHook<T>(event: string, ...arguments_: T[]): Promise<void>;
/**
* Gets all hooks for a specific event
* @param {string} event
* @returns {IHook[]}
*/
getHooks(event: string): IHook[] | undefined;
/**
* Gets a specific hook by id, searching across all events
* @param {string} id - the hook id
* @returns {IHook | undefined} the hook if found, or undefined
*/
getHook(id: string): IHook | undefined;
/**
* Removes one or more hooks by id, searching across all events
* @param {string | string[]} id - the hook id or array of hook ids to remove
* @returns {IHook | IHook[] | undefined} the removed hook(s), or undefined/empty array if not found
*/
removeHookById(id: string | string[]): IHook | IHook[] | undefined;
/**
* Removes all hooks
* @returns {void}
*/
clearHooks(): void;
/**
* Removes all hooks for a specific event and returns the removed hooks.
* @param {string} event - The event name to remove hooks for.
* @returns {IHook[]} the hooks that were removed
*/
removeEventHooks(event: string): IHook[];
/**
* Validates hook event name if enforceBeforeAfter is enabled
* @param {string} event - The event name to validate
* @throws {Error} If enforceBeforeAfter is true and event doesn't start with 'before' or 'after'
*/
private validateHookName;
/**
* Checks if a hook is deprecated and emits a warning if it is
* @param {string} event - The event name to check
* @returns {boolean} - Returns true if the hook should proceed, false if it should be blocked
*/
private checkDeprecatedHook;
}
//#endregion
export { type EventEmitterOptions, type EventListener, Eventified, Hook, type HookFn, Hookified, type HookifiedOptions, type IEventEmitter, type IHook, type IParallelHook, type IWaterfallHook, type Logger, type OnHookOptions, ParallelHook, type ParallelHookContext, type ParallelHookFinalContext, type ParallelHookFinalFn, type ParallelHookFn, type ParallelHookResult, type PrependHookOptions, WaterfallHook, type WaterfallHookContext, type WaterfallHookFn, type WaterfallHookResult };

View File

@@ -0,0 +1,903 @@
//#region src/eventified.ts
const ERROR_EVENT = "error";
var Eventified = class {
_eventListeners;
_maxListeners;
_eventLogger;
_throwOnEmitError = false;
_throwOnEmptyListeners = true;
constructor(options) {
this._eventListeners = /* @__PURE__ */ new Map();
this._maxListeners = 0;
this._eventLogger = options?.eventLogger;
if (options?.throwOnEmitError !== void 0) this._throwOnEmitError = options.throwOnEmitError;
if (options?.throwOnEmptyListeners !== void 0) this._throwOnEmptyListeners = options.throwOnEmptyListeners;
}
/**
* Gets the event logger
* @returns {Logger}
*/
get eventLogger() {
return this._eventLogger;
}
/**
* Sets the event logger
* @param {Logger} eventLogger
*/
set eventLogger(eventLogger) {
this._eventLogger = eventLogger;
}
/**
* Gets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnEmitError() {
return this._throwOnEmitError;
}
/**
* Sets whether an error should be thrown when an emit throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnEmitError(value) {
this._throwOnEmitError = value;
}
/**
* Gets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @returns {boolean}
*/
get throwOnEmptyListeners() {
return this._throwOnEmptyListeners;
}
/**
* Sets whether an error should be thrown when emitting 'error' event with no listeners. Default is false.
* @param {boolean} value
*/
set throwOnEmptyListeners(value) {
this._throwOnEmptyListeners = value;
}
/**
* Adds a handler function for a specific event that will run only once
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
once(eventName, listener) {
const onceListener = (...arguments_) => {
this.off(eventName, onceListener);
listener(...arguments_);
};
this.on(eventName, onceListener);
return this;
}
/**
* Gets the number of listeners for a specific event. If no event is provided, it returns the total number of listeners
* @param {string} eventName The event name. Not required
* @returns {number} The number of listeners
*/
listenerCount(eventName) {
if (eventName === void 0) {
let count = 0;
for (const entry of this._eventListeners.values()) count += typeof entry === "function" ? 1 : entry.length;
return count;
}
const entry = this._eventListeners.get(eventName);
if (entry === void 0) return 0;
return typeof entry === "function" ? 1 : entry.length;
}
/**
* Gets an array of event names
* @returns {Array<string | symbol>} An array of event names
*/
eventNames() {
return [...this._eventListeners.keys()];
}
/**
* Gets an array of listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
rawListeners(event) {
if (event === void 0) return this.getAllListeners();
const entry = this._eventListeners.get(event);
if (entry === void 0) return [];
return typeof entry === "function" ? [entry] : entry;
}
/**
* Prepends a listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependListener(eventName, listener) {
const existing = this._eventListeners.get(eventName);
if (existing === void 0) this._eventListeners.set(eventName, listener);
else if (typeof existing === "function") this._eventListeners.set(eventName, [listener, existing]);
else existing.unshift(listener);
return this;
}
/**
* Prepends a one-time listener to the beginning of the listeners array for the specified event
* @param {string | symbol} eventName
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
prependOnceListener(eventName, listener) {
const onceListener = (...arguments_) => {
this.off(eventName, onceListener);
listener(...arguments_);
};
this.prependListener(eventName, onceListener);
return this;
}
/**
* Gets the maximum number of listeners that can be added for a single event
* @returns {number} The maximum number of listeners
*/
maxListeners() {
return this._maxListeners;
}
/**
* Adds a listener for a specific event. It is an alias for the on() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
addListener(event, listener) {
this.on(event, listener);
return this;
}
/**
* Adds a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
on(event, listener) {
const existing = this._eventListeners.get(event);
if (existing === void 0) {
this._eventListeners.set(event, listener);
return this;
}
if (typeof existing === "function") {
const arr = [existing, listener];
this._eventListeners.set(event, arr);
if (this._maxListeners > 0 && arr.length > this._maxListeners) console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${arr.length} ${event} listeners added. Use setMaxListeners() to increase limit.`);
} else {
existing.push(listener);
if (this._maxListeners > 0 && existing.length > this._maxListeners) console.warn(`MaxListenersExceededWarning: Possible event memory leak detected. ${existing.length} ${event} listeners added. Use setMaxListeners() to increase limit.`);
}
return this;
}
/**
* Removes a listener for a specific event. It is an alias for the off() method
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeListener(event, listener) {
this.off(event, listener);
return this;
}
/**
* Removes a listener for a specific event
* @param {string | symbol} event
* @param {EventListener} listener
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
off(event, listener) {
const entry = this._eventListeners.get(event);
if (entry === void 0) return this;
if (typeof entry === "function") {
if (entry === listener) this._eventListeners.delete(event);
return this;
}
const index = entry.indexOf(listener);
if (index !== -1) if (entry.length === 2) this._eventListeners.set(event, entry[1 - index]);
else if (entry.length === 1) this._eventListeners.delete(event);
else entry.splice(index, 1);
return this;
}
/**
* Calls all listeners for a specific event
* @param {string | symbol} event
* @param arguments_ The arguments to pass to the listeners
* @returns {boolean} Returns true if the event had listeners, false otherwise
*/
emit(event, ...arguments_) {
let result = false;
const entry = this._eventListeners.get(event);
const argumentLength = arguments_.length;
if (entry !== void 0) {
if (typeof entry === "function") if (argumentLength === 1) entry(arguments_[0]);
else if (argumentLength === 2) entry(arguments_[0], arguments_[1]);
else entry(...arguments_);
else {
const len = entry.length;
for (let i = 0; i < len; i++) if (argumentLength === 1) entry[i](arguments_[0]);
else if (argumentLength === 2) entry[i](arguments_[0], arguments_[1]);
else entry[i](...arguments_);
}
result = true;
}
if (this._eventLogger) this.sendToEventLogger(event, arguments_);
if (!result && event === ERROR_EVENT) {
const error = arguments_[0] instanceof Error ? arguments_[0] : /* @__PURE__ */ new Error(`${arguments_[0]}`);
if (this._throwOnEmitError || this._throwOnEmptyListeners) throw error;
}
return result;
}
/**
* Gets all listeners for a specific event. If no event is provided, it returns all listeners
* @param {string} [event] (Optional) The event name
* @returns {EventListener[]} An array of listeners
*/
listeners(event) {
const entry = this._eventListeners.get(event);
if (entry === void 0) return [];
return typeof entry === "function" ? [entry] : entry;
}
/**
* Removes all listeners for a specific event. If no event is provided, it removes all listeners
* @param {string} [event] (Optional) The event name
* @returns {IEventEmitter} returns the instance of the class for chaining
*/
removeAllListeners(event) {
if (event !== void 0) this._eventListeners.delete(event);
else this._eventListeners.clear();
return this;
}
/**
* Sets the maximum number of listeners that can be added for a single event
* @param {number} n The maximum number of listeners
* @returns {void}
*/
setMaxListeners(n) {
this._maxListeners = n < 0 ? 0 : n;
}
/**
* Gets all listeners
* @returns {EventListener[]} An array of listeners
*/
getAllListeners() {
const result = [];
for (const entry of this._eventListeners.values()) if (typeof entry === "function") result.push(entry);
else for (let i = 0; i < entry.length; i++) result.push(entry[i]);
return result;
}
/**
* Sends a log message using the configured logger based on the event name
* @param {string | symbol} eventName - The event name that determines the log level
* @param {unknown} data - The data to log
*/
sendToEventLogger(eventName, data) {
/* v8 ignore next 3 -- @preserve: guarded by caller */
if (!this._eventLogger) return;
let message;
/* v8 ignore next -- @preserve */
if (typeof data === "string") message = data;
else if (Array.isArray(data) && data.length > 0 && data[0] instanceof Error) message = data[0].message;
else if (data instanceof Error) message = data.message;
else if (Array.isArray(data) && data.length > 0 && typeof data[0]?.message === "string") message = data[0].message;
else message = JSON.stringify(data);
switch (eventName) {
case "error":
this._eventLogger.error?.(message, {
event: eventName,
data
});
break;
case "warn":
this._eventLogger.warn?.(message, {
event: eventName,
data
});
break;
case "trace":
this._eventLogger.trace?.(message, {
event: eventName,
data
});
break;
case "debug":
this._eventLogger.debug?.(message, {
event: eventName,
data
});
break;
case "fatal":
this._eventLogger.fatal?.(message, {
event: eventName,
data
});
break;
default:
this._eventLogger.info?.(message, {
event: eventName,
data
});
break;
}
}
};
//#endregion
//#region src/hooks/hook.ts
/**
* Concrete implementation of the IHook interface.
* Provides a convenient class-based way to create hook entries.
*/
var Hook = class {
id;
event;
handler;
/**
* Creates a new Hook instance
* @param {string} event - The event name for the hook
* @param {HookFn} handler - The handler function for the hook
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, handler, id) {
this.id = id;
this.event = event;
this.handler = handler;
}
};
//#endregion
//#region src/hooks/parallel-hook.ts
/**
* A ParallelHook fans a single invocation out to many registered hook
* functions concurrently via Promise.allSettled, then calls a final
* handler with the aggregated results — including failures — keyed by
* the hook function reference for direct lookup. Each hook receives only
* the original arguments; hooks do not see each other's results.
*
* Implements IHook for compatibility with Hookified.onHook(); the final
* handler is called regardless of whether the parallel hook is invoked
* directly or through Hookified.hook().
*
* Generics tighten the per-hook signature when every hook in the set
* accepts the same `initialArgs` and returns the same result type.
* Both default to `any` for backwards compatibility.
*
* @template TArgs - The shape of `initialArgs` passed to every hook
* @template TResult - The result type each hook returns
*/
var ParallelHook = class {
id;
event;
handler;
hooks;
_finalHandler;
/**
* Creates a new ParallelHook instance
* @param {string} event - The event name for the hook
* @param {ParallelHookFinalFn<TArgs, TResult>} finalHandler - Called once with `{ initialArgs, results }` after all parallel hooks settle
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, finalHandler, id) {
this.id = id;
this.event = event;
this.hooks = [];
this._finalHandler = finalHandler;
this.handler = async (...arguments_) => {
const initialArgs = arguments_.length === 1 ? arguments_[0] : arguments_;
const snapshot = [...this.hooks];
const settled = await Promise.allSettled(snapshot.map((hook) => Promise.resolve().then(() => hook({ initialArgs }))));
const results = /* @__PURE__ */ new Map();
snapshot.forEach((hook, index) => {
const outcome = settled[index];
results.set(hook, outcome.status === "fulfilled" ? {
status: "fulfilled",
result: outcome.value
} : {
status: "rejected",
reason: outcome.reason
});
});
await this._finalHandler({
initialArgs,
results
});
};
}
/**
* Adds a hook function to the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to add
*/
addHook(hook) {
this.hooks.push(hook);
}
/**
* Removes a specific hook function from the parallel set
* @param {ParallelHookFn<TArgs, TResult>} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook) {
const index = this.hooks.indexOf(hook);
if (index !== -1) {
this.hooks.splice(index, 1);
return true;
}
return false;
}
};
//#endregion
//#region src/hooks/waterfall-hook.ts
/**
* A WaterfallHook chains multiple hook functions sequentially,
* where each hook receives a context with the previous result,
* initial arguments, and accumulated results. After all hooks
* have executed, the final handler receives the transformed result.
* Implements IHook for compatibility with Hookified.onHook().
*/
var WaterfallHook = class {
id;
event;
handler;
hooks;
_finalHandler;
/**
* Creates a new WaterfallHook instance
* @param {string} event - The event name for the hook
* @param {WaterfallHookFn} finalHandler - The final handler function that receives the transformed result
* @param {string} [id] - Optional unique identifier for the hook
*/
constructor(event, finalHandler, id) {
this.id = id;
this.event = event;
this.hooks = [];
this._finalHandler = finalHandler;
this.handler = async (...arguments_) => {
const initialArgs = arguments_.length === 1 ? arguments_[0] : arguments_;
const results = [];
for (const hook of this.hooks) {
const result = await hook({
initialArgs,
results: [...results]
});
results.push({
hook,
result
});
}
await this._finalHandler({
initialArgs,
results: [...results]
});
};
}
/**
* Adds a hook function to the end of the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to add
*/
addHook(hook) {
this.hooks.push(hook);
}
/**
* Removes a specific hook function from the waterfall chain
* @param {WaterfallHookFn} hook - The hook function to remove
* @returns {boolean} true if the hook was found and removed
*/
removeHook(hook) {
const index = this.hooks.indexOf(hook);
if (index !== -1) {
this.hooks.splice(index, 1);
return true;
}
return false;
}
};
//#endregion
//#region src/index.ts
var Hookified = class extends Eventified {
_hooks;
_throwOnHookError = false;
_enforceBeforeAfter = false;
_deprecatedHooks;
_allowDeprecated = true;
_useHookClone = true;
constructor(options) {
super({
eventLogger: options?.eventLogger,
throwOnEmitError: options?.throwOnEmitError,
throwOnEmptyListeners: options?.throwOnEmptyListeners
});
this._hooks = /* @__PURE__ */ new Map();
this._deprecatedHooks = options?.deprecatedHooks ? new Map(options.deprecatedHooks) : /* @__PURE__ */ new Map();
if (options?.throwOnHookError !== void 0) this._throwOnHookError = options.throwOnHookError;
if (options?.enforceBeforeAfter !== void 0) this._enforceBeforeAfter = options.enforceBeforeAfter;
if (options?.allowDeprecated !== void 0) this._allowDeprecated = options.allowDeprecated;
if (options?.useHookClone !== void 0) this._useHookClone = options.useHookClone;
}
/**
* Gets all hooks
* @returns {Map<string, IHook[]>}
*/
get hooks() {
return this._hooks;
}
/**
* Gets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @returns {boolean}
*/
get throwOnHookError() {
return this._throwOnHookError;
}
/**
* Sets whether an error should be thrown when a hook throws an error. Default is false and only emits an error event.
* @param {boolean} value
*/
set throwOnHookError(value) {
this._throwOnHookError = value;
}
/**
* Gets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @returns {boolean}
* @default false
*/
get enforceBeforeAfter() {
return this._enforceBeforeAfter;
}
/**
* Sets whether to enforce that all hook names start with 'before' or 'after'. Default is false.
* @param {boolean} value
*/
set enforceBeforeAfter(value) {
this._enforceBeforeAfter = value;
}
/**
* Gets the map of deprecated hook names to deprecation messages.
* @returns {Map<string, string>}
*/
get deprecatedHooks() {
return this._deprecatedHooks;
}
/**
* Sets the map of deprecated hook names to deprecation messages.
* @param {Map<string, string>} value
*/
set deprecatedHooks(value) {
this._deprecatedHooks = value;
}
/**
* Gets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @returns {boolean}
*/
get allowDeprecated() {
return this._allowDeprecated;
}
/**
* Sets whether deprecated hooks are allowed to be registered and executed. Default is true.
* @param {boolean} value
*/
set allowDeprecated(value) {
this._allowDeprecated = value;
}
/**
* Gets whether hook objects are cloned before storing. Default is true.
* @returns {boolean}
*/
get useHookClone() {
return this._useHookClone;
}
/**
* Sets whether hook objects are cloned before storing. Default is true.
* When false, the original IHook reference is stored directly.
* @param {boolean} value
*/
set useHookClone(value) {
this._useHookClone = value;
}
onHook(hookOrEvent, optionsOrHandler) {
let hook;
let options;
if (typeof hookOrEvent === "string") {
if (typeof optionsOrHandler !== "function") throw new TypeError("When calling onHook(event, handler), the second argument must be a function");
hook = {
event: hookOrEvent,
handler: optionsOrHandler
};
options = void 0;
} else {
hook = hookOrEvent;
options = optionsOrHandler;
}
this.validateHookName(hook.event);
if (!this.checkDeprecatedHook(hook.event)) return;
const entry = options?.useHookClone ?? this._useHookClone ? {
id: hook.id,
event: hook.event,
handler: hook.handler
} : hook;
entry.id = entry.id ?? crypto.randomUUID();
const eventHandlers = this._hooks.get(hook.event);
if (eventHandlers) {
const existingIndex = eventHandlers.findIndex((h) => h.id === entry.id);
if (existingIndex !== -1) eventHandlers[existingIndex] = entry;
else {
const position = options?.position ?? "Bottom";
if (position === "Top") eventHandlers.unshift(entry);
else if (position === "Bottom") eventHandlers.push(entry);
else {
const index = Math.max(0, Math.min(position, eventHandlers.length));
eventHandlers.splice(index, 0, entry);
}
}
} else this._hooks.set(hook.event, [entry]);
return entry;
}
/**
* Alias for onHook. This is provided for compatibility with other libraries that use the `addHook` method.
* @param {string} event - the event name
* @param {HookFn} handler - the handler function
* @returns {void}
*/
addHook(event, handler) {
this.onHook({
event,
handler
});
}
/**
* Adds handler functions for specific events
* @param {Array<IHook>} hooks
* @param {OnHookOptions} [options] - optional per-call options (e.g., useHookClone override, position)
* @returns {void}
*/
onHooks(hooks, options) {
for (const hook of hooks) this.onHook(hook, options);
}
/**
* Adds a handler function for a specific event that runs before all other handlers.
* Equivalent to calling `onHook(hook, { position: "Top" })`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependHook(hook, options) {
return this.onHook(hook, {
...options,
position: "Top"
});
}
/**
* Adds a handler that only executes once for a specific event before all other handlers.
* Equivalent to calling `onHook` with a self-removing wrapper and `{ position: "Top" }`.
* @param {IHook} hook - the hook containing event name and handler
* @param {PrependHookOptions} [options] - optional per-call options (e.g., useHookClone override)
* @returns {IHook | undefined} the stored hook, or undefined if blocked by deprecation
*/
prependOnceHook(hook, options) {
const wrappedHandler = async (...arguments_) => {
this.removeHook({
event: hook.event,
handler: wrappedHandler
});
return hook.handler(...arguments_);
};
return this.onHook({
id: hook.id,
event: hook.event,
handler: wrappedHandler
}, {
...options,
position: "Top"
});
}
/**
* Adds a handler that only executes once for a specific event
* @param {IHook} hook - the hook containing event name and handler
*/
onceHook(hook) {
this.validateHookName(hook.event);
if (!this.checkDeprecatedHook(hook.event)) return;
const wrappedHandler = async (...arguments_) => {
this.removeHook({
event: hook.event,
handler: wrappedHandler
});
return hook.handler(...arguments_);
};
this.onHook({
id: hook.id,
event: hook.event,
handler: wrappedHandler
});
}
/**
* Removes a handler function for a specific event
* @param {IHook} hook - the hook containing event name and handler to remove
* @returns {IHook | undefined} the removed hook, or undefined if not found
*/
removeHook(hook) {
this.validateHookName(hook.event);
const eventHandlers = this._hooks.get(hook.event);
if (eventHandlers) {
const index = eventHandlers.findIndex((h) => h.handler === hook.handler);
if (index !== -1) {
eventHandlers.splice(index, 1);
if (eventHandlers.length === 0) this._hooks.delete(hook.event);
return {
event: hook.event,
handler: hook.handler
};
}
}
}
/**
* Removes multiple hook handlers
* @param {Array<IHook>} hooks
* @returns {IHook[]} the hooks that were successfully removed
*/
removeHooks(hooks) {
const removed = [];
for (const hook of hooks) {
const result = this.removeHook(hook);
if (result) removed.push(result);
}
return removed;
}
/**
* Calls all handlers for a specific event
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
async hook(event, ...arguments_) {
this.validateHookName(event);
if (!this.checkDeprecatedHook(event)) return;
const eventHandlers = this._hooks.get(event);
if (eventHandlers) for (const hook of [...eventHandlers]) try {
await hook.handler(...arguments_);
} catch (error) {
const message = `${event}: ${error.message}`;
this.emit("error", new Error(message));
if (this._throwOnHookError) throw new Error(message);
}
}
/**
* Calls all synchronous handlers for a specific event.
* Async handlers (declared with `async` keyword) are silently skipped.
*
* Note: The `hook` method is preferred as it executes both sync and async functions.
* Use `hookSync` only when you specifically need synchronous execution.
* @param {string} event
* @param {T[]} arguments_
* @returns {void}
*/
hookSync(event, ...arguments_) {
this.validateHookName(event);
if (!this.checkDeprecatedHook(event)) return;
const eventHandlers = this._hooks.get(event);
if (eventHandlers) for (const hook of [...eventHandlers]) {
if (hook.handler.constructor.name === "AsyncFunction") continue;
try {
hook.handler(...arguments_);
} catch (error) {
const message = `${event}: ${error.message}`;
this.emit("error", new Error(message));
if (this._throwOnHookError) throw new Error(message);
}
}
}
/**
* Prepends the word `before` to your hook. Example is event is `test`, the before hook is `before:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
async beforeHook(event, ...arguments_) {
await this.hook(`before:${event}`, ...arguments_);
}
/**
* Prepends the word `after` to your hook. Example is event is `test`, the after hook is `after:test`.
* @param {string} event - The event name
* @param {T[]} arguments_ - The arguments to pass to the hook
*/
async afterHook(event, ...arguments_) {
await this.hook(`after:${event}`, ...arguments_);
}
/**
* Calls all handlers for a specific event. This is an alias for `hook` and is provided for
* compatibility with other libraries that use the `callHook` method.
* @param {string} event
* @param {T[]} arguments_
* @returns {Promise<void>}
*/
async callHook(event, ...arguments_) {
await this.hook(event, ...arguments_);
}
/**
* Gets all hooks for a specific event
* @param {string} event
* @returns {IHook[]}
*/
getHooks(event) {
this.validateHookName(event);
return this._hooks.get(event);
}
/**
* Gets a specific hook by id, searching across all events
* @param {string} id - the hook id
* @returns {IHook | undefined} the hook if found, or undefined
*/
getHook(id) {
for (const eventHandlers of this._hooks.values()) {
const found = eventHandlers.find((h) => h.id === id);
if (found) return found;
}
}
/**
* Removes one or more hooks by id, searching across all events
* @param {string | string[]} id - the hook id or array of hook ids to remove
* @returns {IHook | IHook[] | undefined} the removed hook(s), or undefined/empty array if not found
*/
removeHookById(id) {
if (Array.isArray(id)) {
const removed = [];
for (const singleId of id) {
const result = this.removeHookById(singleId);
if (result && !Array.isArray(result)) removed.push(result);
}
return removed;
}
for (const [event, eventHandlers] of this._hooks.entries()) {
const index = eventHandlers.findIndex((h) => h.id === id);
if (index !== -1) {
const [removed] = eventHandlers.splice(index, 1);
if (eventHandlers.length === 0) this._hooks.delete(event);
return removed;
}
}
}
/**
* Removes all hooks
* @returns {void}
*/
clearHooks() {
this._hooks.clear();
}
/**
* Removes all hooks for a specific event and returns the removed hooks.
* @param {string} event - The event name to remove hooks for.
* @returns {IHook[]} the hooks that were removed
*/
removeEventHooks(event) {
this.validateHookName(event);
const eventHandlers = this._hooks.get(event);
if (eventHandlers) {
const removed = [...eventHandlers];
this._hooks.delete(event);
return removed;
}
return [];
}
/**
* Validates hook event name if enforceBeforeAfter is enabled
* @param {string} event - The event name to validate
* @throws {Error} If enforceBeforeAfter is true and event doesn't start with 'before' or 'after'
*/
validateHookName(event) {
if (this._enforceBeforeAfter) {
const eventValue = event.trim().toLocaleLowerCase();
if (!eventValue.startsWith("before") && !eventValue.startsWith("after")) throw new Error(`Hook event "${event}" must start with "before" or "after" when enforceBeforeAfter is enabled`);
}
}
/**
* Checks if a hook is deprecated and emits a warning if it is
* @param {string} event - The event name to check
* @returns {boolean} - Returns true if the hook should proceed, false if it should be blocked
*/
checkDeprecatedHook(event) {
if (this._deprecatedHooks.has(event)) {
const message = this._deprecatedHooks.get(event);
const warningMessage = `Hook "${event}" is deprecated${message ? `: ${message}` : ""}`;
this.emit("warn", {
hook: event,
message: warningMessage
});
return this._allowDeprecated;
}
return true;
}
};
//#endregion
export { Eventified, Hook, Hookified, ParallelHook, WaterfallHook };

View File

@@ -0,0 +1,94 @@
{
"name": "hookified",
"version": "2.2.0",
"description": "Event Emitting and Middleware Hooks",
"type": "module",
"main": "./dist/node/index.js",
"module": "./dist/node/index.js",
"types": "./dist/node/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/node/index.d.ts",
"default": "./dist/node/index.js"
},
"require": {
"types": "./dist/node/index.d.cts",
"default": "./dist/node/index.cjs"
},
"default": "./dist/node/index.js"
},
"./browser": {
"types": "./dist/node/index.d.ts",
"import": "./dist/browser/index.js",
"default": "./dist/browser/index.global.js"
}
},
"scripts": {
"lint": "biome check --write --error-on-warnings",
"test": "pnpm lint && vitest run --coverage",
"test:ci": "biome check --error-on-warnings && vitest run --coverage",
"clean": "rimraf ./dist ./coverage ./site/dist",
"build": "tsdown",
"benchmark": "pnpm benchmark:hooks && pnpm benchmark:emit",
"benchmark:hooks": "pnpm tsx benchmark/hook.ts",
"benchmark:emit": "pnpm tsx benchmark/emit.ts",
"benchmark:readme": "pnpm tsx scripts/benchmark-readme.ts",
"website:build": "docula build",
"website:serve": "docula serve",
"website:dev": "docula dev",
"prepublishOnly": "pnpm build"
},
"keywords": [
"hooks",
"eventemitter",
"eventemitter3",
"middleware",
"events",
"hooks",
"event-hooks",
"hook-system",
"event-driven",
"event-emitter",
"hook-handlers",
"middleware",
"emit",
"event-management",
"before-after-hooks",
"event-listeners",
"custom-hooks",
"hook-utilities",
"typescript-hooks"
],
"repository": {
"type": "git",
"url": "git+https://github.com/jaredwray/hookified.git"
},
"author": "Jared Wray <me@jaredwray.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/jaredwray/hookified/issues"
},
"homepage": "https://github.com/jaredwray/hookified#readme",
"devDependencies": {
"@biomejs/biome": "^2.4.13",
"@monstermann/tinybench-pretty-printer": "^0.3.0",
"@types/node": "^24.12.2",
"@vitest/coverage-v8": "^4.1.5",
"docula": "^1.14.0",
"emittery": "^2.0.0",
"eventemitter3": "^5.0.4",
"hookable": "^6.1.1",
"pino": "^10.3.1",
"rimraf": "^6.1.3",
"tinybench": "^6.0.0",
"tsdown": "^0.21.10",
"tsx": "^4.21.0",
"typescript": "^6.0.3",
"vitest": "^4.1.5"
},
"files": [
"dist",
"LICENSE"
]
}

50
node_modules/qified/package.json generated vendored Normal file
View File

@@ -0,0 +1,50 @@
{
"name": "qified",
"version": "0.10.1",
"description": "Task and Message Queues with Multiple Providers",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"exports": {
".": {
"require": "./dist/index.cjs",
"import": "./dist/index.mjs"
}
},
"engines": {
"node": ">=20"
},
"keywords": [
"queue",
"task",
"message",
"provider",
"qified"
],
"repository": {
"type": "git",
"url": "git+https://github.com/jaredwray/qified.git"
},
"author": "Jared Wray <me@jaredwray.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/jaredwray/qified/issues"
},
"homepage": "https://github.com/jaredwray/qified#readme",
"files": [
"dist",
"LICENSE"
],
"dependencies": {
"hookified": "^2.1.1"
},
"scripts": {
"lint": "biome check --write --error-on-warnings",
"test": "pnpm lint && vitest run --coverage",
"test:ci": "biome check --error-on-warnings && vitest run --coverage",
"clean": "rimraf ./dist ./coverage ./site/dist",
"build": "tsdown src/index.ts --format esm --format cjs --dts",
"build:publish": "pnpm build && pnpm publish --access public --no-git-checks"
}
}