npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

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

About

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

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

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

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

Open Software & Tools

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

© 2024 – Pkg Stats / Ryan Hefner

@maxiedev/events

v1.0.0

Published

Typesafe event emitter with async support

Downloads

174

Readme

@maxiedev/events

Event emitter with strong typing, async support, but not covering the basic EventEmitter API.

Features:

  • ⚓ Strong typing
  • 🚀 Async support
  • 📦 No dependencies

Installation

npm i @maxiedev/events

Basic Usage

import { createEmitter } from '@maxiedev/events';

const ee = createEmitter<{
    clientAdded: [id: number, name: string];
    clientRemoved: [id: number];
}>();

ee.on('clientAdded', (id, name) => { // <- id = number, name = string
    console.log(`Client ${name} added with id ${id}`);
});

ee.emit('clientAdded', 1, 'FooBarMan'); // <- forced to pass valid arguments

API

import { createEmitter } from '@maxiedev/events';

export type Options = {
    /**
     * Determines how errors are handled when they occur in a listener.
     * - `if-missing-listener`: Errors are thrown if there are no listeners for the event-errors (onError & offError)
     * - `always`: Errors are always thrown
     * - `never`: Errors are never thrown
     */
    throwErrors: 'if-missing-listener' | 'always' | 'never';
};

export type EventEmitter<Events extends Record<string, [...any]>> = {
    /**
     * Registers a listener for the specified event.
     */
    on<Name extends keyof Events>(
        name: Name,
        listener: (...args: Events[Name]) => void,
    ): () => void;

    /**
     * Registers a listener for the specified event that will be called at most once.
     */
    once<Name extends keyof Events>(
        name: Name,
        listener: (...args: Events[Name]) => void,
    ): () => void;

    /**
     * Emits the specified event with the given arguments.
     */
    emit<Name extends keyof Events>(
        name: Name,
        ...args: Events[Name],
    ): void;

    /**
     * Removes a listener for the specified event.
     */
    off<Name extends keyof Events>(
        name: Name,
        listener?: (...args: Events[Name]) => void,
    ): void;

    /**
     * Returns a promise that resolves when the specified event is emitted.
     */
    until<Name extends keyof Events>(
        name: Name,
    ): Promise<Events[Name]>;

    /**
     * Returns a promise that resolves when the specified event is emitted or the timeout is reached.
     */
    untilOrPass<Name extends keyof Events>(
        name: Name,
        timeout: number,
    ): Promise<Events[Name] | []>;

    /**
     * Returns a promise that resolves when the specified event is emitted or the timeout is reached.
     */
    untilOrThrow<Name extends keyof Events>(
        name: Name,
        timeout: number,
    ): Promise<Events[Name]>;

    /**
     * Returns an async generator that yields each time the specified event is emitted.
     */
    stream<Name extends keyof Events>(
        name: Name,
    ): AsyncGenerator<Events[Name]>;

    /**
     * Registers a listener for errors that occur in event listeners.
     */
    onError(listener: <T extends keyof Events>(
        eventName: T,
        eventArgs: Events[T],
        error: any,
    ) => void): void;

    /**
     * Removes a listener for errors that occur in event listeners.
     */
    offError(listener: <T extends keyof Events>(
        eventName: T,
        eventArgs: Events[T],
        error: any,
    ) => void): void;
};

Examples

Error handling

import { createEmitter } from '@maxiedev/events';

const ee = createEmitter<{
    add: [num: number];
}>({
    throwErrors: 'if-missing-listener',
});

ee.on('add', (num) => {
    if (num < 0) {
        throw new Error('Negative numbers are not allowed');
    }
});

ee.emit('add', 1); // <- No error
ee.emit('add', -1); // <- Error: Negative numbers are not allowed

// but because of the `throwErrors: 'if-missing-listener'` option, we can catch the error:
ee.onError((name, args, error) => {
    console.error(`Error in event "${name}" with args ${args}: ${error.message}`);
});

// then the error will be caught:
ee.emit('add', -1); // <- No error, but above error handler will log the error

Async support

Naive waiting for the first event:

import { createEmitter } from '@maxiedev/events';

const ee = createEmitter<{
    add: [num: number];
}>();

const printAfterFirstChange = async () => {
    const [num] = await ee.until('add'); // <- Wait for the first from now `add` event occurs
    console.log(`Number changed to ${num}`);
};

printAfterFirstChange();

ee.emit('add', 1); // <- Number changed to 1

Timeout-able waiting for the first event:

import { createEmitter } from '@maxiedev/events';

const ee = createEmitter<{
    add: [num: number];
}>();

const printAfterFirstChange = async () => {
    const [num] = await ee.untilOrPass('add', 1000); // <- Wait for the first from now `add` event occurs or 1 second
    if (num) {
        console.log(`Number changed to ${num}`);
    } else {
        console.log('Number not changed yet');
    }
};

printAfterFirstChange(); // <- Number not changed yet

Timeout-able waiting for the first event with error:

import { createEmitter } from '@maxiedev/events';

const ee = createEmitter<{
    add: [num: number];
}>();

const printAfterFirstChange = async () => {
    const [num] = await ee.untilOrThrow('add', 1000); // <- Wait for the first from now `add` event occurs or 1 second
    console.log(`Number changed to ${num}`);
};

printAfterFirstChange(); // <- Throws an error after 1 second

Generators

import { createEmitter } from '@maxiedev/events';

const ee = createEmitter<{
    add: [num: number];
}>();

const printAfterChange = async () => {
    let sum = 0;

    for await (const [num] of ee.stream('add')) { // <- Wait for each `add` event occurs
        sum += num;
        console.log(`Number changed to ${num}`);

        if (sum >= 10) {
            break;
        }
    }
};

printAfterChange();

for (let i = 1; i <= 5; i++) {
    // We push 1..5 numbers to the `add` event:
    ee.emit('add', i); // <- Number changed to 1, 2, 3, 4, because the last number breaks the loop
}

License

LICENCE