@open-wa/hyperemitter 5.5.1 → 5.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @open-wa/hyperemitter
2
2
 
3
- `@open-wa/hyperemitter` is a typed event emitter used by Open-WA packages. It supports exact event names, `+` and `#` wildcard subscriptions, one-time listeners, catch-all listeners, and listener cleanup with an `AbortSignal`.
3
+ `@open-wa/hyperemitter` is a typed event emitter with direct synchronous dispatch and Effect-owned asynchronous work. It supports exact event names, `+` and trailing `#` wildcard subscriptions, one-time listeners, catch-all listeners, and listener cleanup with an `AbortSignal` or an Effect scope. Listeners can return a Promise or an Effect.
4
4
 
5
5
  ## Use
6
6
 
@@ -21,8 +21,114 @@ events.on('message.received', (message) => {
21
21
  events.emit('message.received', { id: 'message-id', body: 'Hello' });
22
22
  ```
23
23
 
24
- The repository also contains a benchmark runner for comparing other emitter libraries. Its results are measurements from that runner, not a performance guarantee.
24
+ `emit` invokes ordinary callbacks directly, entering Effect only for asynchronous listener work in fibers owned by the emitter. Callback-only use creates no PubSub. `emitEffect` batches callbacks in a lazy Effect, awaits every listener, and exposes uncaptured failures in the Effect error channel:
25
+
26
+ ```typescript
27
+ import { Effect } from 'effect';
28
+
29
+ await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
30
+ yield* events.onScoped('message.received', (message) =>
31
+ Effect.sync(() => console.log(message.body)),
32
+ );
33
+ yield* events.emitEffect('message.received', { id: 'message-id', body: 'Hello' });
34
+ })));
35
+ ```
36
+
37
+ `onScoped` and `onAnyScoped` remove their registrations and interrupt their listener fibers when the caller's scope closes. `Effect.runPromise(events.close())` removes all registrations and interrupts work owned by the emitter. A closed emitter cannot accept new subscriptions.
38
+
39
+ Each event carries one payload. `+` matches one name segment; a trailing `#` matches the rest, including an empty suffix. Set `captureRejections: true` to report listener failures through `onError` or the emitter's logger while continuing delivery.
40
+
41
+ The [Effect benchmark](https://github.com/open-wa/wa-automate-nodejs/blob/master/packages/hyperemitter/benchmarks/README.md) compares callback dispatch, Effect dispatch, asynchronous listeners, and scope cleanup on completed deliveries. Its results are measurements from that runner, not a performance guarantee.
25
42
 
26
43
  ## License
27
44
 
28
45
  Apache-2.0
46
+
47
+ ## Shared OpenWA emitter
48
+
49
+ The exported `EventEmitter` backs OpenWA's global `ev` and the socket clients'
50
+ `ev` properties. It preserves the callback API: variadic arguments, synchronous
51
+ `emit`, `*` and `**` namespace wildcards, `this.event`, listener ordering and
52
+ removal, `emitAsync` result arrays, `waitFor`, and `listenTo`. It adapts that
53
+ surface to the same tuned HyperEmitter rather than creating a second runtime.
54
+ `onScoped`, `onAnyScoped`, `emitEffect`, and `close` add Effect ownership.
55
+
56
+ The [PubSub comparison](https://github.com/open-wa/wa-automate-nodejs/blob/master/packages/hyperemitter/benchmarks/results/pubsub-node-2026-10-14.json)
57
+ measures completed deliveries with both per-event acknowledgements and batches
58
+ of 256, including consumers that drain queued messages in batches. PubSub is
59
+ a useful asynchronous stream option, but publishing does not guarantee immediate
60
+ callback invocation. A busy subscriber queues later events, which differs
61
+ from the shared emitter's dispatch contract.
62
+
63
+ ## Optional PubSub and Streams
64
+
65
+ Both `HyperEmitter` and the shared `EventEmitter` facade own a lazy native
66
+ Effect PubSub. Calling `pubsub()`, running `subscribe()`, or consuming `stream()`
67
+ enables queued observation. Ordinary callback users create no PubSub or
68
+ persistent consumer fibers.
69
+
70
+ ```ts
71
+ import { Effect, PubSub } from 'effect';
72
+ import { ev } from '@open-wa/wa-automate';
73
+
74
+ await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
75
+ // Direct native access; ev.subscribe() is the equivalent convenience API.
76
+ const subscription = yield* PubSub.subscribe(ev.pubsub());
77
+ ev.emit('app.job.finished', { jobId: 'daily-summary' });
78
+ const { event, args } = yield* PubSub.take(subscription);
79
+ console.log(event, args[0]);
80
+ })));
81
+ ```
82
+
83
+ The public facade publishes `{ event, args }`; typed `HyperEmitter<TMap>`
84
+ publishes `{ event, payload }`, preserving the relationship between event names
85
+ and payload types. Envelopes and argument arrays are immutable; payload objects
86
+ keep their original identity. Observations are published before callbacks, so
87
+ a recursive emission preserves the original queued order. They describe
88
+ emissions, including ones whose callbacks later fail.
89
+
90
+ `emit`, `emitEffect`, and `emitAsync` deliver through both interfaces once.
91
+ `emit` still returns whether callback listeners ran. `emitAsync` returns those
92
+ callbacks' results and does not wait for arbitrary PubSub consumers. Raw
93
+ `PubSub.publish(emitter.pubsub(), frame)` addresses the queued feed directly;
94
+ use emitter methods when callbacks should also run. The owning emitter shuts
95
+ the hub down on `close()`, interrupting queued readers. Consumer scopes remove
96
+ their own subscriptions. Closing does not promise to drain buffered work.
97
+
98
+ The default is unbounded with replay disabled. A slow active observer can retain
99
+ a growing backlog. Choose options on first access for an explicit finite loss
100
+ policy, or retain recent emissions for later subscribers:
101
+
102
+ ```ts
103
+ import { EventEmitter } from '@open-wa/hyperemitter';
104
+
105
+ const emitter = new EventEmitter();
106
+ const hub = emitter.pubsub({ strategy: 'sliding', capacity: 256, replay: 1 });
107
+ // Later calls return the same hub; options cannot silently replace it.
108
+ ```
109
+
110
+ `dropping` rejects new observations when full; `sliding` removes older ones.
111
+ `pubsubStatus` counts accepted and rejected emitter publications separately from
112
+ callback results; raw publication bypasses these counters. Sliding accepts the
113
+ new publication, so its rejected count does not count evicted older frames.
114
+ Lossless bounded backpressure cannot sit transparently beneath synchronous
115
+ `emit`, so observation options offer only non-blocking strategies. Use an
116
+ integration-owned Queue and effectful producer when producer suspension is
117
+ part of that integration's design.
118
+
119
+ `stream()` supplies the same observations through `Stream.fromPubSub`, with
120
+ normal Effect filtering, batching, and consumer concurrency controls. Each
121
+ stream starts its subscription when consumed; subscribe before emitting when
122
+ replay is disabled. The global `ev` feed forwards native events and enabled
123
+ session aliases even when no callback is registered. Session shutdown detaches
124
+ its bridge without closing the shared global hub.
125
+
126
+ See the [source-backed architecture review](https://github.com/open-wa/wa-automate-nodejs/blob/master/docs/research/2026-10-14-effect-event-system-designs.md)
127
+ for the responsibilities of PubSub, Queue, Stream, SubscriptionRef, services,
128
+ and scoped fibers.
129
+
130
+ The [Effect event guide](https://openwa.dev/docs/guides/effect-event-streams)
131
+ includes complete examples; the
132
+ [HyperEmitter reference](https://openwa.dev/docs/reference/hyperemitter)
133
+ documents method returns and lifecycle semantics. The Effect hybrid and
134
+ optional PubSub APIs are available from OpenWA 5.6.0.