@kellanjs/eventcraft
v0.2.0
Published
Type-safe events for TypeScript: define events as a tree, subscribe to exactly the ones you need, with typed payloads and an optional React hook.
Downloads
23
Maintainers
Readme
eventcraft
Type-safe events for TypeScript: define your events once as a tree, then subscribe to exactly the ones you need, with every payload typed.
import { event, eventcraft } from "@kellanjs/eventcraft";
const events = eventcraft()
.events({
notes: {
created: event<{ id: string; title: string }>(),
deleted: event<{ id: string }>(),
},
saved: event(),
})
.build();
events.notes.created.$subscribe((note) => {
console.log("New note:", note.title); // note is { id: string; title: string }
});
await events.notes.created({ id: "1", title: "Groceries" });The problem
A typical event bus identifies events with strings:
bus.on("notes:created", (payload) => {
/* payload is `any` */
});
bus.emit("note:created", { id: 1 }); // typo, wrong payload: no errorNothing connects the event's name to its payload, typos fail silently, and
listening to "every note event" means wildcard strings like "notes:*".
What eventcraft does
- Events are typed objects, not strings.
events.notes.createdis the event: you emit it by calling it, and TypeScript checks the payload. - The tree is the subscription model. Subscribe to one event
(
events.notes.created), a whole branch (events.notes), or everything (events), with no wildcards. - Named groups collect events from anywhere in the tree, for things like "every event that should refresh search results".
- Listeners get exact types. A listener for
events.notesreceives a union that narrows by event name. - Optional React hook.
useEventsubscribes a component and cleans up when it unmounts.
It has no dependencies, and the core works anywhere JavaScript runs. React is only needed for the hook.
Install
npm install @kellanjs/eventcraftRequirements
- TypeScript 5.0 or newer.
strictmode is recommended, but not required. - An ES2022 runtime: Node 18+, Chrome 93+, Firefox 92+, Safari 15.4+.
- ES modules. The package has no CommonJS build.
- React 16.8 or newer, only if you use
useEvent.
Quick start
1. Define your events
import { event, eventcraft, group } from "@kellanjs/eventcraft";
export const events = eventcraft()
.events({
notes: {
created: event<{ id: string; title: string }>(),
updated: event<{ id: string; title: string }>(),
deleted: event<{ id: string }>(),
},
tags: {
renamed: event<{ id: string; name: string }>(),
},
saved: event(), // no payload
})
.groups((events) => ({
searchInvalidating: group(events.notes, events.tags.renamed),
}))
.build();event<Payload>() defines an event and its payload type. Nesting objects
creates branches, and each event's name is its path: "notes.created".
.groups() is optional. It names sets of events so you can subscribe to them
together (see Groups).
2. Subscribe
// One event: the listener receives the payload, then the full event
events.notes.deleted.$subscribe((payload) => {
removeFromList(payload.id);
});
// A branch: the listener receives the full event, for every event below it
events.notes.$subscribe((event) => {
console.log(event.name); // "notes.created" | "notes.updated" | "notes.deleted"
});
// A group
events.searchInvalidating.$subscribe(() => {
refreshSearch();
});Every $subscribe returns a function that unsubscribes.
3. Emit
await events.notes.created({ id: "1", title: "Groceries" });
await events.saved();Calling an event emits it. The payload is checked: a missing title, or any
argument to events.saved(), is a compile error.
How events are delivered
Every listener receives an event envelope:
{
id: "c1a5…", // unique per emit
name: "notes.created", // the event's full name
payload: { id: "1", title: "Groceries" },
timestamp: 1767225600000, // Date.now() when emitted
}What the listener's arguments are depends on what you subscribed to:
| Subscribed to | Listener receives |
| -------------------------------------------- | -------------------- |
| One event (events.notes.created) | (payload, event) |
| Anything else (branch, group, registry, ...) | (event) |
A single event's listener usually only needs the payload, so it comes first.
Everything else can deliver several kinds of event, so its listeners get the
envelope and can check event.name, which narrows event.payload:
events.notes.$subscribe((event) => {
if (event.name === "notes.deleted") {
event.payload; // { id: string }
} else {
event.payload; // { id: string; title: string }
}
});Guide
Emitting: to wait or not to wait
An emit returns a promise. You choose, at each emit, whether to wait for it:
// Wait: continues once every listener has finished, async ones included
await events.notes.updated({ id: "1", title: "New title" });
// Don't wait: starts the listeners and carries on immediately
void events.notes.updated({ id: "1", title: "New title" });Either way, every listener runs. Synchronous listeners run immediately, in the order they subscribed, before the emit call returns.
Waiting is useful when the emitter's work isn't done until listeners have reacted. For example, a save that should stay "pending" until search results are refreshed, or a test that checks the effects of an event. Not waiting is right when the emitter shouldn't be slowed down by whoever is listening.
Both are safe: a failing listener never makes the emit fail (see When a listener fails).
You can also emit with $emit, which is the same function:
await events.notes.deleted.$emit({ id: "1" });Branches and the registry
Every object in your definition is a branch, and you can subscribe to it. The registry itself is the root branch:
events.notes.$subscribe((event) => {}); // every notes.* event
events.$subscribe((event) => {}); // every eventGroups
A group names a set of events from anywhere in the tree. Define groups in
.groups(), which receives the events:
const events = eventcraft()
.events({
notes: { created: event<{ id: string }>(), deleted: event<{ id: string }>() },
tags: { renamed: event<{ id: string; name: string }>() },
})
.groups((events) => ({
searchInvalidating: group(events.notes, events.tags.renamed),
cache: {
// groups can be nested in folders...
tags: group(events.tags),
},
}))
.build();
events.searchInvalidating.$subscribe((event) => {});
events.cache.tags.$subscribe((event) => {});group() accepts single events, branches and other groups.
.groups() can be called more than once. Each call adds groups, and its
callback also receives the groups from earlier calls, so groups can build on
each other:
eventcraft()
.events({ a: event(), b: event(), c: event() })
.groups((events) => ({ first: group(events.a, events.b) }))
.groups((events) => ({ everything: group(events.first, events.c) }))
.build();Group names follow the same rules as event names, and can't reuse the name of
an existing event, branch or group: those are compile errors. Groups can go
inside a branch (notes: { recent: group(...) }), but that doesn't make
their events part of the branch: events.notes still delivers only the
notes.* events.
One-off selections
For a combination you only need once, select sources without naming a group:
events.$select([events.notes, events.tags.renamed]).$subscribe((event) => {});The standalone select() does the same without the registry, and can combine
events from different registries:
import { select } from "@kellanjs/eventcraft";
select([events.notes.created, otherEvents.saved]).$subscribe((event) => {});Overlapping sources deliver each event once. Selecting both events.notes
and events.notes.created doesn't call the listener twice for
notes.created. The same goes for groups.
Unsubscribing
$subscribe returns an unsubscribe function, which is safe to call more than
once:
const unsubscribe = events.saved.$subscribe(() => {});
unsubscribe();You can also pass an AbortSignal, which is handy for removing several
subscriptions at once:
const controller = new AbortController();
events.saved.$subscribe(() => {}, { signal: controller.signal });
events.notes.$subscribe(() => {}, { signal: controller.signal });
controller.abort(); // removes both$once subscribes for the next event only:
events.saved.$once(() => {
console.log("Saved for the first time");
});Each $subscribe call is its own subscription, even with the same function.
Subscribing one function twice calls it twice, and unsubscribing one doesn't
affect the other.
React
useEvent subscribes a component to any event source, and unsubscribes when
the component unmounts:
import { useEvent } from "@kellanjs/eventcraft/react";
function NoteList() {
const [notes, setNotes] = useState<Note[]>([]);
useEvent(events.notes.deleted, (payload) => {
setNotes((notes) => notes.filter((note) => note.id !== payload.id));
});
// ...
}It accepts the same sources as everything else, plus arrays:
useEvent(events.notes, (event) => {});
useEvent(events.searchInvalidating, (event) => {});
useEvent([events.notes.created, events.tags.renamed], (event) => {});
useEvent(events.$select([events.notes, events.tags.renamed]), (event) => {});You don't need useCallback or useMemo:
- The listener can change on every render. The hook always calls the latest one, without resubscribing.
- The source can be written inline, including arrays and
$select(...). The hook only resubscribes when the events it covers change.
Async iteration
Every event source can be used with for await:
for await (const event of events.notes) {
console.log(event.name);
if (event.name === "notes.deleted") break;
}The loop subscribes when it starts, and break, return or throw
unsubscribes. Events that arrive while the loop body is busy are queued, with
no limit, so a loop that falls far behind a busy source keeps every pending
event in memory.
When a listener fails
If a listener throws (or its promise rejects), eventcraft:
- still runs every other listener,
- passes the error to
onListenerError, - and resolves the emit normally.
So a bug in one listener can't break the code that emitted the event, whether or not it waited.
By default, errors are reported with reportError in browsers, which shows
up like any uncaught error (and in error trackers), and console.error
elsewhere. Pass onListenerError to handle them yourself:
const events = eventcraft({
onListenerError(error, event) {
logger.error(`Listener for ${event.name} failed`, error);
},
})
.events({ saved: event() })
.build();To make an emit reject when a listener fails, for example in tests, rethrow:
const events = eventcraft({
onListenerError: (error) => {
throw error;
},
})
.events({ saved: event() })
.build();
await events.saved(); // rejects with the listener's errorIf several listeners fail, it rejects with an AggregateError containing all
of them.
Types from the registry
Use EventOf and PayloadOf instead of writing event types by hand:
import type { EventOf, PayloadOf } from "@kellanjs/eventcraft";
type CreatedPayload = PayloadOf<typeof events.notes.created>;
// { id: string; title: string }
type NoteEvent = EventOf<typeof events.notes>;
// the envelope union a notes listener receives
function logNoteEvent(event: NoteEvent) {
console.log(event.name, event.payload.id);
}Both accept any source: a single event, a branch, a group, the registry, or an array of sources.
To type a reusable function that accepts any event, use EventEnvelope
without type arguments:
import type { EventEnvelope } from "@kellanjs/eventcraft";
events.$subscribe((event: EventEnvelope) => analytics.track(event.name));Options
eventcraft() takes options that apply to every event in the registry:
| Option | Default | Purpose |
| ----------------- | -------------------------------------------- | ----------------------------------------- |
| createId | crypto.randomUUID() | Creates each event's id |
| now | Date.now() | Creates each event's timestamp |
| onEmit | none | Called with every event, before listeners |
| onListenerError | reportError in browsers, else console.error | Called when a listener or onEmit fails |
crypto.randomUUID() only exists on secure pages (https or localhost) and
isn't a global in Node 18 modules. Where it's missing, eventcraft falls back
to an id that is unique but not cryptographically random.
createId and now make events predictable in tests:
const events = eventcraft({ createId: () => "test-id", now: () => 0 })
.events({ saved: event() })
.build();API reference
Building
| API | Description |
| -------------------------------- | ---------------------------------------------------------------- |
| eventcraft(options?) | Starts a registry |
| .events(definitions) | Defines the event tree |
| .groups((events) => groups) | Adds named groups (optional, can be repeated) |
| .build() | Creates the registry. Each call creates a new, separate registry |
| event<Payload>() / event() | Defines an event with or without a payload |
| group(...sources) | Lists a group's members inside .groups() |
| select(sources) | Creates a one-off source from several sources |
Every event source (events, branches, groups, selections, the registry)
| API | Description |
| -------------------------------- | ---------------------------------------------------------------- |
| $subscribe(listener, options?) | Subscribes. Returns an unsubscribe function |
| $once(listener, options?) | Subscribes for the next event only |
| $name | The source's name: "notes.created", "notes", "" for the registry, "$selection" for selections |
| [Symbol.asyncIterator] | Allows for await (const event of source) |
Single events
| API | Description |
| ---------------------- | ------------------------------- |
| event(payload) | Emits. Returns a promise |
| $emit(payload) | The same as calling the event |
Other sources
| API | Description |
| ----------------------- | -------------------------------------------------- |
| $members | The names of the events it delivers |
| events.$select(sources) | A one-off selection (registry only) |
React (@kellanjs/eventcraft/react)
| API | Description |
| ---------------------------- | ---------------------------------------------- |
| useEvent(source, listener) | Subscribes a component until it unmounts |
Types
| Type | Description |
| ---------------------------- | ---------------------------------------------------- |
| EventOf<Source> | The event envelope(s) a source's listeners receive |
| PayloadOf<Source> | The payload type(s) of a source |
| EventEnvelope<Name, Payload> | An event envelope. Both arguments are optional |
| EventListener<Name, Payload> | A single event's listener |
| SourceListener<Event> | A listener for any other source |
| EventRegistry, EventcraftBuilder, EventNode, GroupNode, BranchNode, RootNode | The types of the objects eventcraft creates |
| EventcraftOptions, SubscribeOptions | Option objects |
Good to know
$is reserved. eventcraft's own properties start with$, so event and group keys can't. Keys can't contain.either, since dots separate the parts of a name. Both are compile errors (and also throw inbuild(), for JavaScript users).- Groups and branches are fixed at build time. Their members don't change afterwards.
- A registry delivers only its own events. If a group includes another registry's events, subscribing to that group delivers them, but subscribing to the registry doesn't.
- Listeners added during an emit wait for the next emit. Listeners removed during an emit aren't called by it if they haven't been yet.
- Methods can be passed around.
$subscribe,$onceand$emitdon't depend onthis, soconst { $emit } = events.savedworks.
Development
npm install
npm run cinpm run ci lints, type-checks, builds, checks formatting and the package's
exports, and runs the tests:
tests/eventcraft.test.ts: the core runtimetests/use-event.test.ts: the React hooktests/eventcraft.test-d.ts: types (checked bytsc, not run)tests/package-consumer.test.ts: the built package, imported by nametests/declaration-emit.test.ts: exporting builders and registries from a project that emits.d.tsfilestests/error-messages.test.ts: the wording of compile-time errors
Thanks
If you made it this far, thanks for checking out the library, and I hope you find it useful in your projects!
License
eventcraft is open source under the MIT license.
