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 πŸ™

Β© 2025 – Pkg Stats / Ryan Hefner

kitsune-san

v1.0.0

Published

🦊 A polite, reliable event bus that quietly manages your application's messages with the wisdom of a fox spirit

Readme

🦊 Kitsune-san

"Kitsune-san always delivers messages on time."

A polite, reliable event bus that quietly manages your application's messages with the wisdom of a fox spirit. Perfect for decoupled communication in modern JavaScript and TypeScript applications.

✨ Features

  • 🎯 Type-safe: Full TypeScript support with generic event types
  • πŸš€ Lightweight: Zero dependencies, minimal footprint
  • 🧠 Smart: Priority-based listener ordering and timeout management
  • πŸ›‘οΈ Reliable: Comprehensive error handling and memory management
  • πŸ”„ Flexible: Works with any framework or vanilla JavaScript
  • πŸ“Š Observable: Built-in statistics and debugging capabilities
  • πŸ§ͺ Well-tested: 100% test coverage with comprehensive test suite

πŸ“¦ Installation

npm install kitsune-san

πŸš€ Quick Start

Simple Usage

import kitsuneSan from "kitsune-san";

// Listen for events
kitsuneSan.on("user:login", (event) => {
  console.log("User logged in:", event.detail);
});

// Emit events
kitsuneSan.emit("user:login", {
  userId: 123,
  username: "fox-lover",
});

Type-Safe Events

import { KitsuneSan } from "kitsune-san";
import type { KitsuneEvent } from "kitsune-san";

interface UserData {
  id: number;
  name: string;
  email: string;
}

const kitsuneSan = new KitsuneSan();

// Type-safe event listener
kitsuneSan.on<UserData>("user:created", (event: KitsuneEvent<UserData>) => {
  // event.detail is fully typed as UserData
  console.log(`Welcome ${event.detail.name}!`);
});

// Type-safe emission
kitsuneSan.emit<UserData>("user:created", {
  id: 456,
  name: "Kitsune",
  email: "[email protected]",
});

πŸ“– API Reference

KitsuneSan Class

on<T>(eventName, callback, options?)

Registers an event listener with optional configuration.

kitsuneSan.on(
  "event:name",
  (event) => {
    console.log(event.detail);
  },
  {
    once: false, // Remove after first execution
    timeout: 5000, // Auto-remove after 5 seconds
    priority: 10, // Higher priority listeners execute first
  }
);

Parameters:

  • eventName (string): Name of the event to listen for
  • callback (KitsuneCallback): Function to call when event is emitted
  • options (ListenerOptions): Optional configuration object

once<T>(eventName, callback, options?)

Registers a one-time event listener that removes itself after first execution.

kitsuneSan.once("app:ready", (event) => {
  console.log("App initialization complete");
});

off<T>(eventName, callback)

Removes a specific event listener.

const handler = (event) => console.log(event.detail);

kitsuneSan.on("test:event", handler);
kitsuneSan.off("test:event", handler); // Remove specific listener

emit<T>(eventName, data, errorHandler?)

Emits an event with data to all registered listeners.

kitsuneSan.emit(
  "notification:show",
  {
    message: "Hello from Kitsune-san! 🦊",
    type: "success",
  },
  (error, eventName, data) => {
    console.error(`Failed to emit ${eventName}:`, error);
  }
);

removeAllListeners(eventName?)

Removes listeners for a specific event or all events.

kitsuneSan.removeAllListeners("user:logout"); // Remove all listeners for specific event
kitsuneSan.removeAllListeners(); // Remove ALL listeners

hasListeners(eventName)

Checks if any listeners are registered for an event.

if (kitsuneSan.hasListeners("data:changed")) {
  kitsuneSan.emit("data:changed", newData);
}

getListenerCount(eventName)

Returns the number of listeners for a specific event.

const count = kitsuneSan.getListenerCount("ui:update");
console.log(`${count} components listening for UI updates`);

getEventNames()

Returns an array of all event names with registered listeners.

const activeEvents = kitsuneSan.getEventNames();
console.log("Active events:", activeEvents);

getStats()

Returns comprehensive statistics about event bus usage.

const stats = kitsuneSan.getStats();
console.log({
  totalEmissions: stats.totalEmissions,
  totalListeners: stats.totalListeners,
  uniqueEventTypes: stats.uniqueEventTypes,
  listenerCounts: stats.listenerCounts,
  emissionCounts: stats.emissionCounts,
});

resetStats()

Resets emission statistics (listeners remain active).

kitsuneSan.resetStats();

🎨 Usage Patterns

React Integration

import { useEffect, useState } from "react";
import kitsuneSan from "kitsune-san";

function UserProfile() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const handleUserUpdate = (event) => {
      setUser(event.detail);
    };

    kitsuneSan.on("user:updated", handleUserUpdate);

    // Cleanup on unmount
    return () => {
      kitsuneSan.off("user:updated", handleUserUpdate);
    };
  }, []);

  return user ? <div>Hello {user.name}!</div> : <div>Loading...</div>;
}

Vue Integration

import { ref, onMounted, onUnmounted } from "vue";
import kitsuneSan from "kitsune-san";

export function useUserData() {
  const user = ref(null);

  const handleUserData = (event) => {
    user.value = event.detail;
  };

  onMounted(() => {
    kitsuneSan.on("user:data", handleUserData);
  });

  onUnmounted(() => {
    kitsuneSan.off("user:data", handleUserData);
  });

  return { user };
}

Microfrontend Communication

// Host application
import kitsuneSan from "kitsune-san";

class HostApp {
  broadcastAuthData(authData) {
    kitsuneSan.emit("auth:updated", authData);
  }
}

// Guest application
import kitsuneSan from "kitsune-san";

class GuestApp {
  init() {
    kitsuneSan.on("auth:updated", (event) => {
      this.updateUserInterface(event.detail);
    });
  }
}

Error Handling

import kitsuneSan from "kitsune-san";

// Global error handler
const globalErrorHandler = (error, eventName, data) => {
  console.error(`Event emission failed for '${eventName}':`, error);
  // Send to error tracking service
  errorTracker.captureException(error, { eventName, data });
};

// Use with all emissions
kitsuneSan.emit("critical:operation", data, globalErrorHandler);

Priority-Based Execution

// High priority - security checks
kitsuneSan.on("user:action", securityHandler, { priority: 100 });

// Medium priority - business logic
kitsuneSan.on("user:action", businessLogicHandler, { priority: 50 });

// Low priority - analytics
kitsuneSan.on("user:action", analyticsHandler, { priority: 1 });

// Handlers execute in priority order: security -> business -> analytics
kitsuneSan.emit("user:action", actionData);

πŸ”§ Advanced Features

Timeout Management

// Auto-cleanup after timeout
kitsuneSan.on("temporary:event", handler, { timeout: 30000 }); // 30 seconds

// One-time listener with timeout
kitsuneSan.once("initialization:complete", handler, { timeout: 10000 });

Statistics and Monitoring

// Monitor event bus health
setInterval(() => {
  const stats = kitsuneSan.getStats();

  if (stats.totalListeners > 1000) {
    console.warn("High listener count detected:", stats.totalListeners);
  }

  console.log("Event activity:", stats.emissionCounts);
}, 60000);

Custom Error Handling

class CustomEventBus extends KitsuneSan {
  emit(eventName, data, errorHandler) {
    const customErrorHandler = (error, eventName, data) => {
      // Custom error handling logic
      this.logError(error, eventName, data);
      errorHandler?.(error, eventName, data);
    };

    super.emit(eventName, data, customErrorHandler);
  }

  private logError(error, eventName, data) {
    // Custom logging implementation
  }
}

πŸ§ͺ Testing

Kitsune-san is designed to be easily testable:

import { KitsuneSan } from "kitsune-san";

describe("Component with EventBus", () => {
  let kitsuneSan;

  beforeEach(() => {
    kitsuneSan = new KitsuneSan();
  });

  afterEach(() => {
    kitsuneSan.removeAllListeners();
  });

  test("should handle user data", () => {
    const mockHandler = jest.fn();

    kitsuneSan.on("user:data", mockHandler);
    kitsuneSan.emit("user:data", { id: 123 });

    expect(mockHandler).toHaveBeenCalledWith(
      expect.objectContaining({
        detail: { id: 123 },
      })
    );
  });
});

πŸ“Š Performance

Kitsune-san is optimized for performance:

  • Lightweight: ~2KB gzipped
  • Fast: Efficient listener management with priority queues
  • Memory-safe: Automatic cleanup and leak prevention
  • Scalable: Tested with thousands of listeners and rapid emissions

πŸ›‘οΈ Browser Support

  • Modern browsers: Full ES2018+ support
  • Legacy support: Transpile with Babel if needed
  • Node.js: Full compatibility for server-side usage
  • TypeScript: First-class TypeScript support

🀝 Contributing

We welcome contributions! Please see our contributing guidelines for details.

πŸ“„ License

MIT License - see LICENSE file for details.

πŸ™ Acknowledgments

Inspired by the wisdom of fox spirits in Japanese folklore, Kitsune-san brings that same reliability and intelligence to your application's event system.


Made with ❀️ and 🦊 by the Reval Admin Team