Fox Events Fox Events

Trail (History)

Event history per channel: published, received, and unsubscribed events. Optional cap via maxHistory, and toText() for debugging.

Basic usage

ts
import { Fox } from "fox-events";

const channel = Fox.channel<{ userId: string }>("user:login");

channel.emit({ userId: "u-1" });
channel.on((payload) => console.log(payload.userId));

const snapshot = channel.trail();
console.log(snapshot.published);   // EventTrail<T>[]
console.log(snapshot.received);    // EventTrail<T>[]
console.log(snapshot.unsubscribed); // UnsubscribedHistory[]
console.log(snapshot.toText());    // formatted string for logs

maxHistory

Limit how many entries are kept in each list. Older entries are trimmed after each record.

ts
const channel = Fox.channel<{ id: string }>("user:action", {
  maxHistory: 100,
});

channel.emit({ id: "1" });
// ... after 100+ published, only the last 100 remain
const snap = channel.trail();
console.log(snap.published.length); // <= 100

clearTrail

Reset all history for that channel.

ts
channel.clearTrail();
const snap = channel.trail();
console.log(snap.published.length); // 0

Global trail

To observe all events on the page in one place (multiple channels, one list), subscribe to each channel and accumulate entries in a single state. Example:

ts
const channels = [
  { name: "app:login", channel: loginChannel },
  { name: "app:cart", channel: cartChannel },
  { name: "app:theme", channel: themeChannel },
];

const [entries, setEntries] = useState<Array<{ channel: string; payload: unknown; at: number }>>([]);
const MAX = 50;

const addEntry = (channel: string, payload: unknown) => {
  setEntries((prev) => [...prev.slice(-(MAX - 1)), { channel, payload, at: Date.now() }]);
};

useEffect(() => {
  const unsubs = channels.map(({ name, channel }) =>
    channel.on((payload: unknown) => addEntry(name, payload))
  );
  return () => unsubs.forEach((u) => u());
}, []);

You get a single list (channel + payload + timestamp) for debugging or to show the user. Capping with MAX keeps the list from growing indefinitely.

Types

Exported from fox-events:

  • EventTrail<T>{ name: string; payload: T; timestamp: number }
  • UnsubscribedHistory{ name: string; timestamp: number }
  • HistorySnapshot<T>{ published: EventTrail<T>[]; received: EventTrail<T>[]; unsubscribed: UnsubscribedHistory[]; toText(): string }
ts
import type { EventTrail, UnsubscribedHistory, HistorySnapshot } from "fox-events";