@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 +108 -2
- package/dist/index.cjs +771 -129
- package/dist/index.d.cts +167 -12
- package/dist/index.d.cts.map +1 -1
- package/package.json +7 -4
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let effect = require("effect");
|
|
2
3
|
let _open_wa_logger = require("@open-wa/logger");
|
|
3
4
|
//#region src/routing/RadixNode.ts
|
|
4
5
|
/**
|
|
@@ -20,102 +21,180 @@ var RadixNode = class {
|
|
|
20
21
|
};
|
|
21
22
|
//#endregion
|
|
22
23
|
//#region src/routing/RadixTree.ts
|
|
23
|
-
/**
|
|
24
|
-
* Radix tree with MQTT-style wildcards.
|
|
25
|
-
* Complexity: O(K) where K = number of path segments.
|
|
26
|
-
*/
|
|
24
|
+
/** Segment trie; multi-segment wildcard states are deduplicated during matching. */
|
|
27
25
|
var RadixTree = class {
|
|
28
26
|
delimiter;
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
style;
|
|
28
|
+
root = new RadixNode("");
|
|
29
|
+
single;
|
|
30
|
+
multi;
|
|
31
|
+
constructor(delimiter = ".", style = "mqtt") {
|
|
31
32
|
this.delimiter = delimiter;
|
|
32
|
-
this.
|
|
33
|
+
this.style = style;
|
|
34
|
+
this.single = style === "mqtt" ? "+" : "*";
|
|
35
|
+
this.multi = style === "mqtt" ? "#" : "**";
|
|
33
36
|
}
|
|
34
|
-
insert(pattern, value) {
|
|
35
|
-
const segments = this.tokenize(pattern);
|
|
37
|
+
insert(pattern, value, prepend = false) {
|
|
36
38
|
let node = this.root;
|
|
37
|
-
for (const segment of
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
if (segment === "#") {
|
|
44
|
-
if (!node.wildcardMulti) node.wildcardMulti = new RadixNode("#");
|
|
45
|
-
node = node.wildcardMulti;
|
|
46
|
-
break;
|
|
47
|
-
}
|
|
48
|
-
if (!node.children) node.children = /* @__PURE__ */ new Map();
|
|
39
|
+
for (const segment of pattern.split(this.delimiter)) if (segment === this.single) node = node.wildcardSingle ??= new RadixNode(this.single);
|
|
40
|
+
else if (segment === this.multi) {
|
|
41
|
+
node = node.wildcardMulti ??= new RadixNode(this.multi);
|
|
42
|
+
if (this.style === "mqtt") break;
|
|
43
|
+
} else {
|
|
44
|
+
node.children ??= /* @__PURE__ */ new Map();
|
|
49
45
|
let child = node.children.get(segment);
|
|
50
|
-
if (!child)
|
|
51
|
-
child = new RadixNode(segment);
|
|
52
|
-
node.children.set(segment, child);
|
|
53
|
-
}
|
|
46
|
+
if (!child) node.children.set(segment, child = new RadixNode(segment));
|
|
54
47
|
node = child;
|
|
55
48
|
}
|
|
56
|
-
node.listeners.
|
|
49
|
+
if (prepend) node.listeners.unshift(value);
|
|
50
|
+
else node.listeners.push(value);
|
|
57
51
|
}
|
|
58
52
|
remove(pattern, value) {
|
|
59
|
-
const path = [];
|
|
60
53
|
let node = this.root;
|
|
61
|
-
const
|
|
62
|
-
for (const segment of
|
|
63
|
-
|
|
64
|
-
if (
|
|
65
|
-
|
|
66
|
-
node
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
54
|
+
const path = [];
|
|
55
|
+
for (const segment of pattern.split(this.delimiter)) {
|
|
56
|
+
const child = segment === this.single ? node.wildcardSingle : segment === this.multi ? node.wildcardMulti : node.children?.get(segment);
|
|
57
|
+
if (!child) return;
|
|
58
|
+
path.push([
|
|
59
|
+
node,
|
|
60
|
+
child,
|
|
61
|
+
segment
|
|
62
|
+
]);
|
|
63
|
+
node = child;
|
|
64
|
+
if (segment === this.multi && this.style === "mqtt") break;
|
|
65
|
+
}
|
|
66
|
+
const index = node.listeners.indexOf(value);
|
|
67
|
+
if (index >= 0) node.listeners.splice(index, 1);
|
|
68
|
+
for (const [parent, child, segment] of path.reverse()) {
|
|
69
|
+
if (child.listeners.length || child.children?.size || child.wildcardSingle || child.wildcardMulti) break;
|
|
70
|
+
if (segment === this.single) parent.wildcardSingle = null;
|
|
71
|
+
else if (segment === this.multi) parent.wildcardMulti = null;
|
|
72
|
+
else parent.children?.delete(segment);
|
|
77
73
|
}
|
|
78
|
-
const idx = node.listeners.indexOf(value);
|
|
79
|
-
if (idx !== -1) node.listeners.splice(idx, 1);
|
|
80
74
|
}
|
|
81
75
|
match(event) {
|
|
82
|
-
const segments = this.
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
76
|
+
const segments = event.split(this.delimiter);
|
|
77
|
+
if (this.style === "mqtt") {
|
|
78
|
+
const stack = [[this.root, 0]];
|
|
79
|
+
const results = [];
|
|
80
|
+
while (stack.length) {
|
|
81
|
+
const [node, index] = stack.pop();
|
|
82
|
+
if (node.wildcardMulti) results.push(...node.wildcardMulti.listeners);
|
|
83
|
+
if (index === segments.length) {
|
|
84
|
+
results.push(...node.listeners);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (node.wildcardSingle) stack.push([node.wildcardSingle, index + 1]);
|
|
88
|
+
const child = node.children?.get(segments[index]);
|
|
89
|
+
if (child) stack.push([child, index + 1]);
|
|
94
90
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
91
|
+
return results;
|
|
92
|
+
}
|
|
93
|
+
const stack = [[this.root, 0]];
|
|
94
|
+
const visited = /* @__PURE__ */ new Map();
|
|
95
|
+
const collected = /* @__PURE__ */ new Set();
|
|
96
|
+
const results = [];
|
|
97
|
+
while (stack.length) {
|
|
98
|
+
const [node, index] = stack.pop();
|
|
99
|
+
let indices = visited.get(node);
|
|
100
|
+
if (indices?.has(index)) continue;
|
|
101
|
+
if (!indices) visited.set(node, indices = /* @__PURE__ */ new Set());
|
|
102
|
+
indices.add(index);
|
|
103
|
+
if ((index === segments.length || node.segment === this.multi) && !collected.has(node)) {
|
|
104
|
+
results.push(...node.listeners);
|
|
105
|
+
collected.add(node);
|
|
102
106
|
}
|
|
103
|
-
if (node.
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
if (
|
|
109
|
-
stack.push({
|
|
110
|
-
node: node.wildcardMulti,
|
|
111
|
-
index: index + 1
|
|
112
|
-
});
|
|
107
|
+
if (node.wildcardMulti) stack.push([node.wildcardMulti, index]);
|
|
108
|
+
if (index < segments.length) {
|
|
109
|
+
if (node.segment === this.multi) stack.push([node, index + 1]);
|
|
110
|
+
if (node.wildcardSingle) stack.push([node.wildcardSingle, index + 1]);
|
|
111
|
+
const child = node.children?.get(segments[index]);
|
|
112
|
+
if (child) stack.push([child, index + 1]);
|
|
113
113
|
}
|
|
114
114
|
}
|
|
115
115
|
return results;
|
|
116
116
|
}
|
|
117
|
-
|
|
118
|
-
|
|
117
|
+
};
|
|
118
|
+
//#endregion
|
|
119
|
+
//#region src/routing/patternsIntersect.ts
|
|
120
|
+
/** Whether two namespace patterns share at least one concrete event name. */
|
|
121
|
+
function patternsIntersect(left, right, delimiter = ".") {
|
|
122
|
+
const a = left.split(delimiter), b = right.split(delimiter);
|
|
123
|
+
const stack = [[0, 0]];
|
|
124
|
+
const seen = /* @__PURE__ */ new Set();
|
|
125
|
+
while (stack.length) {
|
|
126
|
+
const [i, j] = stack.pop();
|
|
127
|
+
const state = `${i}:${j}`;
|
|
128
|
+
if (seen.has(state)) continue;
|
|
129
|
+
seen.add(state);
|
|
130
|
+
if (i === a.length && j === b.length) return true;
|
|
131
|
+
if (a[i] === "**") stack.push([i + 1, j]);
|
|
132
|
+
if (b[j] === "**") stack.push([i, j + 1]);
|
|
133
|
+
if (i === a.length || j === b.length) continue;
|
|
134
|
+
if (a[i] === b[j] || a[i] === "*" || a[i] === "**" || b[j] === "*" || b[j] === "**") stack.push([a[i] === "**" ? i : i + 1, b[j] === "**" ? j : j + 1]);
|
|
135
|
+
}
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region src/core/EmissionHub.ts
|
|
140
|
+
/** Optional queued observation; normal callbacks never depend on consumers draining. */
|
|
141
|
+
var EmissionHub = class {
|
|
142
|
+
hub;
|
|
143
|
+
configuration;
|
|
144
|
+
accepted = 0;
|
|
145
|
+
rejected = 0;
|
|
146
|
+
get enabled() {
|
|
147
|
+
return !!this.hub && !effect.PubSub.isShutdownUnsafe(this.hub);
|
|
148
|
+
}
|
|
149
|
+
get(options) {
|
|
150
|
+
if (this.hub && options === void 0) return this.hub;
|
|
151
|
+
const strategy = options?.strategy ?? "unbounded";
|
|
152
|
+
const capacity = options && "capacity" in options ? options.capacity : Infinity;
|
|
153
|
+
const replay = options?.replay ?? 0;
|
|
154
|
+
if (![
|
|
155
|
+
"unbounded",
|
|
156
|
+
"dropping",
|
|
157
|
+
"sliding"
|
|
158
|
+
].includes(strategy)) throw new TypeError("PubSub observations require a non-blocking strategy");
|
|
159
|
+
if (strategy === "unbounded" && options && "capacity" in options) throw new TypeError("Choose dropping or sliding when specifying PubSub capacity");
|
|
160
|
+
if (strategy !== "unbounded" && (!Number.isInteger(capacity) || capacity <= 0)) throw new TypeError("PubSub capacity must be a positive integer");
|
|
161
|
+
if (!Number.isInteger(replay) || replay < 0) throw new TypeError("PubSub replay must be a non-negative integer");
|
|
162
|
+
if (this.hub) {
|
|
163
|
+
const current = this.configuration;
|
|
164
|
+
if (current.strategy !== strategy || current.capacity !== capacity || current.replay !== replay) throw new Error("PubSub is already configured; choose its options before subscribing");
|
|
165
|
+
return this.hub;
|
|
166
|
+
}
|
|
167
|
+
const hub = effect.Effect.runSync(strategy === "unbounded" ? effect.PubSub.unbounded({ replay }) : strategy === "dropping" ? effect.PubSub.dropping({
|
|
168
|
+
capacity,
|
|
169
|
+
replay
|
|
170
|
+
}) : effect.PubSub.sliding({
|
|
171
|
+
capacity,
|
|
172
|
+
replay
|
|
173
|
+
}));
|
|
174
|
+
this.configuration = {
|
|
175
|
+
strategy,
|
|
176
|
+
capacity,
|
|
177
|
+
replay
|
|
178
|
+
};
|
|
179
|
+
this.hub = hub;
|
|
180
|
+
return hub;
|
|
181
|
+
}
|
|
182
|
+
publish(value) {
|
|
183
|
+
if (!this.hub) return;
|
|
184
|
+
if (this.configuration.strategy === "sliding" ? effect.Effect.runSync(effect.PubSub.publish(this.hub, value)) : effect.PubSub.publishUnsafe(this.hub, value)) this.accepted++;
|
|
185
|
+
else this.rejected++;
|
|
186
|
+
}
|
|
187
|
+
status() {
|
|
188
|
+
return {
|
|
189
|
+
enabled: !!this.hub,
|
|
190
|
+
shutdown: !!this.hub && effect.PubSub.isShutdownUnsafe(this.hub),
|
|
191
|
+
strategy: this.configuration?.strategy,
|
|
192
|
+
accepted: this.accepted,
|
|
193
|
+
rejected: this.rejected
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
close() {
|
|
197
|
+
return this.hub ? effect.PubSub.shutdown(this.hub) : effect.Effect.void;
|
|
119
198
|
}
|
|
120
199
|
};
|
|
121
200
|
//#endregion
|
|
@@ -124,6 +203,7 @@ function createRecord(fn, opts, finalizer) {
|
|
|
124
203
|
const record = {
|
|
125
204
|
fn,
|
|
126
205
|
once: false,
|
|
206
|
+
any: false,
|
|
127
207
|
signal: opts.signal,
|
|
128
208
|
captureRejections: opts.captureRejections
|
|
129
209
|
};
|
|
@@ -155,9 +235,12 @@ function cleanupAbort(record) {
|
|
|
155
235
|
}
|
|
156
236
|
//#endregion
|
|
157
237
|
//#region src/core/HyperEmitter.ts
|
|
238
|
+
const emitted = effect.Effect.succeed(true);
|
|
239
|
+
const noListeners = effect.Effect.succeed(false);
|
|
158
240
|
var HyperEmitter = class {
|
|
159
241
|
delimiter;
|
|
160
242
|
captureRejections;
|
|
243
|
+
wildcardStyle;
|
|
161
244
|
onError;
|
|
162
245
|
finalizer;
|
|
163
246
|
logger;
|
|
@@ -167,9 +250,33 @@ var HyperEmitter = class {
|
|
|
167
250
|
wildcardTree;
|
|
168
251
|
wildcardIndex;
|
|
169
252
|
hasWildcards = false;
|
|
170
|
-
anyListeners = /* @__PURE__ */ new
|
|
253
|
+
anyListeners = /* @__PURE__ */ new Map();
|
|
254
|
+
scope = effect.Scope.makeUnsafe();
|
|
255
|
+
closed = false;
|
|
256
|
+
observations = new EmissionHub();
|
|
257
|
+
get isClosed() {
|
|
258
|
+
return this.closed;
|
|
259
|
+
}
|
|
260
|
+
/** Enable queued observations lazily; direct PubSub publishing reaches this feed only. */
|
|
261
|
+
pubsub(options) {
|
|
262
|
+
this.assertOpen();
|
|
263
|
+
return this.observations.get(options);
|
|
264
|
+
}
|
|
265
|
+
get hasPubSub() {
|
|
266
|
+
return !this.closed && this.observations.enabled;
|
|
267
|
+
}
|
|
268
|
+
get pubsubStatus() {
|
|
269
|
+
return this.observations.status();
|
|
270
|
+
}
|
|
271
|
+
subscribe(options) {
|
|
272
|
+
return effect.Effect.suspend(() => effect.PubSub.subscribe(this.pubsub(options)));
|
|
273
|
+
}
|
|
274
|
+
stream(options) {
|
|
275
|
+
return effect.Stream.suspend(() => effect.Stream.fromPubSub(this.pubsub(options)));
|
|
276
|
+
}
|
|
171
277
|
constructor(options = {}) {
|
|
172
278
|
this.delimiter = options.delimiter ?? ".";
|
|
279
|
+
this.wildcardStyle = options.wildcardStyle ?? "mqtt";
|
|
173
280
|
this.captureRejections = options.captureRejections ?? false;
|
|
174
281
|
this.onError = options.onError;
|
|
175
282
|
this.debugEnabled = !!options.debug;
|
|
@@ -185,20 +292,30 @@ var HyperEmitter = class {
|
|
|
185
292
|
if (token && typeof token === "object") {}
|
|
186
293
|
});
|
|
187
294
|
this.exactListeners = /* @__PURE__ */ new Map();
|
|
188
|
-
this.wildcardTree = new RadixTree(this.delimiter);
|
|
295
|
+
this.wildcardTree = new RadixTree(this.delimiter, this.wildcardStyle);
|
|
189
296
|
this.wildcardIndex = /* @__PURE__ */ new Map();
|
|
190
297
|
}
|
|
191
298
|
on(event, listener, options = {}) {
|
|
192
299
|
const record = createRecord(listener, options, this.finalizer);
|
|
193
|
-
this.add(event, record);
|
|
300
|
+
this.add(event, record, options.prepend);
|
|
194
301
|
return this;
|
|
195
302
|
}
|
|
196
303
|
once(event, listener, options = {}) {
|
|
197
304
|
const record = createRecord(listener, options, this.finalizer);
|
|
198
305
|
record.once = true;
|
|
199
|
-
this.add(event, record);
|
|
306
|
+
this.add(event, record, options.prepend);
|
|
200
307
|
return this;
|
|
201
308
|
}
|
|
309
|
+
/** Register a listener and own its in-flight Effects until the caller's scope closes. */
|
|
310
|
+
onScoped(event, listener, options = {}) {
|
|
311
|
+
return effect.Effect.acquireRelease(effect.Effect.sync(() => {
|
|
312
|
+
this.assertOpen();
|
|
313
|
+
const record = createRecord(listener, options, this.finalizer);
|
|
314
|
+
record.scope = effect.Scope.forkUnsafe(this.scope);
|
|
315
|
+
this.add(event, record, options.prepend);
|
|
316
|
+
return record;
|
|
317
|
+
}), (record) => effect.Effect.sync(() => this.offListener(record)).pipe(effect.Effect.andThen(effect.Scope.close(record.scope, effect.Exit.void)))).pipe(effect.Effect.asVoid);
|
|
318
|
+
}
|
|
202
319
|
off(event, listener) {
|
|
203
320
|
const list = this.exactListeners.get(event);
|
|
204
321
|
if (list) {
|
|
@@ -209,46 +326,140 @@ var HyperEmitter = class {
|
|
|
209
326
|
}
|
|
210
327
|
if (list.length === 0) this.exactListeners.delete(event);
|
|
211
328
|
}
|
|
212
|
-
if (this.hasWildcards &&
|
|
329
|
+
if (this.hasWildcards && this.isWildcard(event)) this.removeWildcard(event, listener);
|
|
213
330
|
return this;
|
|
214
331
|
}
|
|
215
332
|
emit(event, payload) {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
333
|
+
if (this.closed) return false;
|
|
334
|
+
if (this.observations.enabled) this.observations.publish(Object.freeze({
|
|
335
|
+
event,
|
|
336
|
+
payload
|
|
337
|
+
}));
|
|
338
|
+
if (this.exactListeners.size === 0 && this.wildcardIndex.size === 0 && this.anyListeners.size === 0) return false;
|
|
339
|
+
const records = this.snapshot(event);
|
|
340
|
+
let called = false;
|
|
341
|
+
for (const record of records) {
|
|
342
|
+
if (!this.prepare(record)) continue;
|
|
343
|
+
called = true;
|
|
344
|
+
try {
|
|
345
|
+
const result = record.any ? record.fn(event, payload) : record.fn(payload);
|
|
346
|
+
if (effect.Effect.isEffect(result) || result && typeof result.then === "function") effect.Effect.runSync(effect.Effect.forkIn(this.resultEffect(result).pipe(effect.Effect.catchCause((cause) => effect.Effect.sync(() => {
|
|
347
|
+
if (!effect.Cause.hasInterruptsOnly(cause)) this.handleRejection(record, effect.Cause.squash(cause));
|
|
348
|
+
}))), record.scope ?? this.scope, { startImmediately: true }));
|
|
349
|
+
} catch (error) {
|
|
350
|
+
if (!this.shouldCapture(record)) throw error;
|
|
351
|
+
this.handleRejection(record, error);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return called;
|
|
355
|
+
}
|
|
356
|
+
/** Emit lazily and await every listener, including Promise and Effect callbacks. */
|
|
357
|
+
emitEffect(event, payload) {
|
|
358
|
+
return this.dispatch(event, payload, true);
|
|
359
|
+
}
|
|
360
|
+
dispatch(event, payload, awaitListeners) {
|
|
361
|
+
return effect.Effect.suspend(() => {
|
|
362
|
+
if (this.closed) return noListeners;
|
|
363
|
+
if (this.observations.enabled) this.observations.publish(Object.freeze({
|
|
364
|
+
event,
|
|
365
|
+
payload
|
|
366
|
+
}));
|
|
367
|
+
const records = this.snapshot(event);
|
|
368
|
+
if (records.length === 0) return noListeners;
|
|
369
|
+
let pending;
|
|
370
|
+
let called = false;
|
|
371
|
+
let hasAsync = false;
|
|
372
|
+
const loop = (start) => {
|
|
373
|
+
for (let index = start; index < records.length; index++) {
|
|
374
|
+
const record = records[index];
|
|
375
|
+
if (!this.prepare(record)) continue;
|
|
376
|
+
called = true;
|
|
377
|
+
let result;
|
|
378
|
+
try {
|
|
379
|
+
result = record.any ? record.fn(event, payload) : record.fn(payload);
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (!this.shouldCapture(record)) return effect.Effect.fail(error);
|
|
382
|
+
this.handleRejection(record, error);
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
if (!effect.Effect.isEffect(result) && !(result && typeof result.then === "function")) continue;
|
|
386
|
+
hasAsync = true;
|
|
387
|
+
const work = this.resultEffect(result);
|
|
388
|
+
const handled = !awaitListeners || this.shouldCapture(record) ? work.pipe(effect.Effect.catchCause((cause) => effect.Effect.sync(() => {
|
|
389
|
+
if (!effect.Cause.hasInterruptsOnly(cause)) this.handleRejection(record, effect.Cause.squash(cause));
|
|
390
|
+
}))) : work;
|
|
391
|
+
return effect.Effect.forkIn(handled, record.scope ?? this.scope, { startImmediately: true }).pipe(effect.Effect.flatMap((fiber) => {
|
|
392
|
+
if (awaitListeners) (pending ??= []).push(fiber);
|
|
393
|
+
return effect.Effect.suspend(() => loop(index + 1));
|
|
394
|
+
}));
|
|
395
|
+
}
|
|
396
|
+
return pending ? effect.Fiber.joinAll(pending).pipe(effect.Effect.as(called)) : called ? emitted : noListeners;
|
|
397
|
+
};
|
|
398
|
+
const program = loop(0);
|
|
399
|
+
return awaitListeners && hasAsync ? program.pipe(effect.Effect.ensuring(effect.Effect.suspend(() => pending ? effect.Fiber.interruptAll(pending) : effect.Effect.void))) : program;
|
|
400
|
+
});
|
|
223
401
|
}
|
|
224
402
|
/**
|
|
225
403
|
* Register a catch-all listener that fires on every emit with (event, payload).
|
|
226
404
|
* Useful for event bridging / debugging.
|
|
227
405
|
*/
|
|
228
|
-
onAny(listener) {
|
|
229
|
-
this.
|
|
406
|
+
onAny(listener, options = {}) {
|
|
407
|
+
this.assertOpen();
|
|
408
|
+
const existing = this.anyListeners.get(listener);
|
|
409
|
+
if (existing) cleanupAbort(existing);
|
|
410
|
+
const record = createRecord(listener, options, this.finalizer);
|
|
411
|
+
record.any = true;
|
|
412
|
+
if (options.prepend) this.anyListeners = new Map([[listener, record], ...this.anyListeners]);
|
|
413
|
+
else this.anyListeners.set(listener, record);
|
|
414
|
+
attachAbort(record, () => this.offAny(listener));
|
|
230
415
|
return this;
|
|
231
416
|
}
|
|
417
|
+
onAnyScoped(listener, options = {}) {
|
|
418
|
+
const owned = (event, payload) => listener(event, payload);
|
|
419
|
+
return effect.Effect.acquireRelease(effect.Effect.sync(() => {
|
|
420
|
+
this.assertOpen();
|
|
421
|
+
const record = createRecord(owned, options, this.finalizer);
|
|
422
|
+
record.original = listener;
|
|
423
|
+
record.any = true;
|
|
424
|
+
record.scope = effect.Scope.forkUnsafe(this.scope);
|
|
425
|
+
this.anyListeners.set(owned, record);
|
|
426
|
+
attachAbort(record, () => this.offAny(owned));
|
|
427
|
+
return record;
|
|
428
|
+
}), (record) => effect.Effect.sync(() => this.offAny(owned)).pipe(effect.Effect.andThen(effect.Scope.close(record.scope, effect.Exit.void)))).pipe(effect.Effect.asVoid);
|
|
429
|
+
}
|
|
232
430
|
/**
|
|
233
431
|
* Remove a catch-all listener registered via onAny.
|
|
234
432
|
*/
|
|
235
433
|
offAny(listener) {
|
|
236
|
-
this.anyListeners.
|
|
434
|
+
const record = this.anyListeners.get(listener) ?? [...this.anyListeners.values()].find((record) => record.original === listener);
|
|
435
|
+
if (record) {
|
|
436
|
+
cleanupAbort(record);
|
|
437
|
+
this.anyListeners.delete(record.fn);
|
|
438
|
+
}
|
|
237
439
|
return this;
|
|
238
440
|
}
|
|
441
|
+
listeners(event) {
|
|
442
|
+
return this.snapshot(event).filter((record) => !record.any && this.isLive(record)).map((record) => record.fn);
|
|
443
|
+
}
|
|
444
|
+
hasListeners(event) {
|
|
445
|
+
return this.snapshot(event).some((record) => this.isLive(record));
|
|
446
|
+
}
|
|
239
447
|
listenerCount(event) {
|
|
240
448
|
if (!event) {
|
|
241
|
-
let total =
|
|
449
|
+
let total = this.wildcardIndex.size + this.anyListeners.size;
|
|
242
450
|
for (const arr of this.exactListeners.values()) total += arr.length;
|
|
243
451
|
return total;
|
|
244
452
|
}
|
|
245
|
-
return this.
|
|
453
|
+
return this.listeners(event).length;
|
|
246
454
|
}
|
|
247
455
|
removeAllListeners(event) {
|
|
248
456
|
if (!event) {
|
|
249
457
|
for (const arr of this.exactListeners.values()) arr.forEach(cleanupAbort);
|
|
250
458
|
this.exactListeners.clear();
|
|
251
|
-
|
|
459
|
+
for (const record of this.wildcardIndex.keys()) cleanupAbort(record);
|
|
460
|
+
for (const record of this.anyListeners.values()) cleanupAbort(record);
|
|
461
|
+
this.anyListeners.clear();
|
|
462
|
+
this.wildcardTree = new RadixTree(this.delimiter, this.wildcardStyle);
|
|
252
463
|
this.hasWildcards = false;
|
|
253
464
|
this.wildcardIndex.clear();
|
|
254
465
|
return this;
|
|
@@ -258,20 +469,30 @@ var HyperEmitter = class {
|
|
|
258
469
|
list.forEach(cleanupAbort);
|
|
259
470
|
this.exactListeners.delete(event);
|
|
260
471
|
}
|
|
261
|
-
if (this.hasWildcards &&
|
|
472
|
+
if (this.hasWildcards && this.isWildcard(event)) {
|
|
262
473
|
for (const [record, pattern] of this.wildcardIndex.entries()) if (pattern === event) {
|
|
474
|
+
cleanupAbort(record);
|
|
263
475
|
this.wildcardTree.remove(pattern, record);
|
|
264
476
|
this.wildcardIndex.delete(record);
|
|
265
477
|
}
|
|
266
478
|
}
|
|
267
479
|
return this;
|
|
268
480
|
}
|
|
481
|
+
/** Remove subscriptions and interrupt listener work owned by this emitter. */
|
|
482
|
+
close() {
|
|
483
|
+
return effect.Effect.suspend(() => {
|
|
484
|
+
if (this.closed) return effect.Effect.void;
|
|
485
|
+
this.closed = true;
|
|
486
|
+
this.removeAllListeners();
|
|
487
|
+
return this.observations.close().pipe(effect.Effect.andThen(effect.Scope.close(this.scope, effect.Exit.void)));
|
|
488
|
+
});
|
|
489
|
+
}
|
|
269
490
|
/**
|
|
270
491
|
* Bridge from a Node EventEmitter: forward Node events into this emitter.
|
|
271
492
|
*/
|
|
272
493
|
fromNodeEmitter(emitter, event) {
|
|
273
494
|
const handler = (...args) => {
|
|
274
|
-
this.emit(event,
|
|
495
|
+
this.emit(event, args[0]);
|
|
275
496
|
};
|
|
276
497
|
emitter.on(event, handler);
|
|
277
498
|
return () => emitter.off(event, handler);
|
|
@@ -280,14 +501,12 @@ var HyperEmitter = class {
|
|
|
280
501
|
* Bridge to a Node EventEmitter: emit HyperEmitter events on a provided Node emitter.
|
|
281
502
|
*/
|
|
282
503
|
toNodeEmitter(target) {
|
|
283
|
-
const forwarder = (event,
|
|
284
|
-
|
|
285
|
-
this.emit = (ev, ...args) => {
|
|
286
|
-
forwarder(ev, args);
|
|
287
|
-
return original.call(this, ev, ...args);
|
|
504
|
+
const forwarder = (event, payload) => {
|
|
505
|
+
target.emit(event, payload);
|
|
288
506
|
};
|
|
507
|
+
this.onAny(forwarder);
|
|
289
508
|
return () => {
|
|
290
|
-
this.
|
|
509
|
+
this.offAny(forwarder);
|
|
291
510
|
};
|
|
292
511
|
}
|
|
293
512
|
/**
|
|
@@ -300,16 +519,19 @@ var HyperEmitter = class {
|
|
|
300
519
|
target.addEventListener(type, handler);
|
|
301
520
|
return () => target.removeEventListener(type, handler);
|
|
302
521
|
}
|
|
303
|
-
add(event, record) {
|
|
304
|
-
|
|
522
|
+
add(event, record, prepend = false) {
|
|
523
|
+
this.assertOpen();
|
|
524
|
+
const isWildcard = this.isWildcard(event);
|
|
305
525
|
if (isWildcard) {
|
|
306
526
|
this.hasWildcards = true;
|
|
307
|
-
this.wildcardTree.insert(event, record);
|
|
527
|
+
this.wildcardTree.insert(event, record, prepend);
|
|
308
528
|
this.wildcardIndex.set(record, event);
|
|
309
529
|
} else {
|
|
310
530
|
const list = this.exactListeners.get(event);
|
|
311
|
-
if (list)
|
|
312
|
-
|
|
531
|
+
if (list) {
|
|
532
|
+
if (prepend) list.unshift(record);
|
|
533
|
+
else list.push(record);
|
|
534
|
+
} else this.exactListeners.set(event, [record]);
|
|
313
535
|
}
|
|
314
536
|
attachAbort(record, () => this.off(event, record.fn));
|
|
315
537
|
this.logDebug("listener_registered", {
|
|
@@ -318,30 +540,58 @@ var HyperEmitter = class {
|
|
|
318
540
|
wildcard: isWildcard
|
|
319
541
|
});
|
|
320
542
|
}
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
543
|
+
listenersAny() {
|
|
544
|
+
return [...this.anyListeners.values()].filter((record) => this.isLive(record)).map((record) => record.original ?? record.fn);
|
|
545
|
+
}
|
|
546
|
+
eventNames() {
|
|
547
|
+
return [.../* @__PURE__ */ new Set([...this.exactListeners.keys(), ...this.wildcardIndex.values()])];
|
|
548
|
+
}
|
|
549
|
+
isWildcard(event) {
|
|
550
|
+
if (this.wildcardStyle === "mqtt" ? !event.includes("+") && !event.includes("#") : !event.includes("*")) return false;
|
|
551
|
+
const tokens = this.wildcardStyle === "mqtt" ? ["+", "#"] : ["*", "**"];
|
|
552
|
+
return event.split(this.delimiter).some((segment) => tokens.includes(segment));
|
|
553
|
+
}
|
|
554
|
+
assertOpen() {
|
|
555
|
+
if (this.closed) throw new Error("HyperEmitter is closed");
|
|
556
|
+
}
|
|
557
|
+
snapshot(event) {
|
|
558
|
+
if (this.wildcardStyle === "eventemitter" && this.isWildcard(event)) {
|
|
559
|
+
const records = [...this.anyListeners.values()];
|
|
560
|
+
for (const [pattern, listeners] of this.exactListeners) if (patternsIntersect(pattern, event, this.delimiter)) records.push(...listeners);
|
|
561
|
+
for (const [record, pattern] of this.wildcardIndex) if (patternsIntersect(pattern, event, this.delimiter)) records.push(record);
|
|
562
|
+
return records;
|
|
334
563
|
}
|
|
335
|
-
|
|
564
|
+
const exact = this.exactListeners.get(event);
|
|
565
|
+
if (!this.hasWildcards && this.anyListeners.size === 0) return exact?.slice() ?? [];
|
|
566
|
+
return [
|
|
567
|
+
...this.wildcardStyle === "eventemitter" ? this.anyListeners.values() : [],
|
|
568
|
+
...exact ?? [],
|
|
569
|
+
...this.hasWildcards ? this.wildcardTree.match(event) : [],
|
|
570
|
+
...this.wildcardStyle === "mqtt" ? this.anyListeners.values() : []
|
|
571
|
+
];
|
|
572
|
+
}
|
|
573
|
+
isLive(record) {
|
|
574
|
+
return !record.signal?.aborted && (!record.weakRef || !!record.weakRef.deref());
|
|
336
575
|
}
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
576
|
+
prepare(record) {
|
|
577
|
+
if (!this.isLive(record)) {
|
|
578
|
+
this.offListener(record);
|
|
579
|
+
return false;
|
|
580
|
+
}
|
|
581
|
+
if (record.once) {
|
|
582
|
+
if (record.fired) return false;
|
|
583
|
+
record.fired = true;
|
|
584
|
+
this.offListener(record);
|
|
344
585
|
}
|
|
586
|
+
return true;
|
|
587
|
+
}
|
|
588
|
+
resultEffect(result) {
|
|
589
|
+
if (effect.Effect.isEffect(result)) return result;
|
|
590
|
+
if (result && typeof result.then === "function") return effect.Effect.tryPromise({
|
|
591
|
+
try: () => Promise.resolve(result),
|
|
592
|
+
catch: (error) => error
|
|
593
|
+
});
|
|
594
|
+
return effect.Effect.succeed(result);
|
|
345
595
|
}
|
|
346
596
|
offListener(record) {
|
|
347
597
|
for (const [event, arr] of this.exactListeners.entries()) {
|
|
@@ -355,12 +605,18 @@ var HyperEmitter = class {
|
|
|
355
605
|
}
|
|
356
606
|
const pattern = this.wildcardIndex.get(record);
|
|
357
607
|
if (pattern) {
|
|
608
|
+
cleanupAbort(record);
|
|
358
609
|
this.wildcardTree.remove(pattern, record);
|
|
359
610
|
this.wildcardIndex.delete(record);
|
|
611
|
+
return;
|
|
360
612
|
}
|
|
613
|
+
if (this.anyListeners.get(record.fn) === record) this.offAny(record.fn);
|
|
614
|
+
}
|
|
615
|
+
shouldCapture(record) {
|
|
616
|
+
return record.captureRejections ?? this.captureRejections;
|
|
361
617
|
}
|
|
362
618
|
handleRejection(record, err) {
|
|
363
|
-
if (!(record
|
|
619
|
+
if (!this.shouldCapture(record)) {
|
|
364
620
|
queueMicrotask(() => {
|
|
365
621
|
throw err;
|
|
366
622
|
});
|
|
@@ -394,4 +650,390 @@ var HyperEmitter = class {
|
|
|
394
650
|
}
|
|
395
651
|
};
|
|
396
652
|
//#endregion
|
|
653
|
+
//#region src/core/EventEmitter.ts
|
|
654
|
+
/** The process-level OpenWA API, backed by the tuned HyperEmitter dispatcher. */
|
|
655
|
+
var EventEmitter = class EventEmitter {
|
|
656
|
+
options;
|
|
657
|
+
static defaultMaxListeners = 10;
|
|
658
|
+
delimiter;
|
|
659
|
+
wildcard = true;
|
|
660
|
+
ignoreErrors;
|
|
661
|
+
event = "";
|
|
662
|
+
engine;
|
|
663
|
+
registrations = /* @__PURE__ */ new Map();
|
|
664
|
+
symbolRoutes = /* @__PURE__ */ new Map();
|
|
665
|
+
observers = /* @__PURE__ */ new Set();
|
|
666
|
+
pendingWaits = /* @__PURE__ */ new Set();
|
|
667
|
+
maxListeners;
|
|
668
|
+
closed = false;
|
|
669
|
+
observations = new EmissionHub();
|
|
670
|
+
constructor(options = {}) {
|
|
671
|
+
this.options = options;
|
|
672
|
+
this.delimiter = options.delimiter ?? ".";
|
|
673
|
+
this.ignoreErrors = options.ignoreErrors ?? false;
|
|
674
|
+
this.maxListeners = options.maxListeners ?? EventEmitter.defaultMaxListeners;
|
|
675
|
+
this.engine = new HyperEmitter({
|
|
676
|
+
delimiter: this.delimiter,
|
|
677
|
+
wildcardStyle: "eventemitter"
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
get isClosed() {
|
|
681
|
+
return this.closed || this.engine.isClosed;
|
|
682
|
+
}
|
|
683
|
+
/** Raw queued observation; use emit/emitEffect to deliver through both interfaces. */
|
|
684
|
+
pubsub(options) {
|
|
685
|
+
if (this.isClosed) throw new Error("EventEmitter is closed");
|
|
686
|
+
return this.observations.get(options);
|
|
687
|
+
}
|
|
688
|
+
get hasPubSub() {
|
|
689
|
+
return !this.isClosed && this.observations.enabled;
|
|
690
|
+
}
|
|
691
|
+
get pubsubStatus() {
|
|
692
|
+
return this.observations.status();
|
|
693
|
+
}
|
|
694
|
+
subscribe(options) {
|
|
695
|
+
return effect.Effect.suspend(() => effect.PubSub.subscribe(this.pubsub(options)));
|
|
696
|
+
}
|
|
697
|
+
stream(options) {
|
|
698
|
+
return effect.Stream.suspend(() => effect.Stream.fromPubSub(this.pubsub(options)));
|
|
699
|
+
}
|
|
700
|
+
on(event, listener, options) {
|
|
701
|
+
return this.register(event, listener, options);
|
|
702
|
+
}
|
|
703
|
+
addListener(event, listener, options) {
|
|
704
|
+
return this.register(event, listener, options);
|
|
705
|
+
}
|
|
706
|
+
prependListener(event, listener, options) {
|
|
707
|
+
return this.register(event, listener, options, true);
|
|
708
|
+
}
|
|
709
|
+
once(event, listener, options) {
|
|
710
|
+
return this.register(event, listener, options, false, 1);
|
|
711
|
+
}
|
|
712
|
+
prependOnceListener(event, listener, options) {
|
|
713
|
+
return this.register(event, listener, options, true, 1);
|
|
714
|
+
}
|
|
715
|
+
many(event, times, listener, options) {
|
|
716
|
+
return this.register(event, listener, options, false, times);
|
|
717
|
+
}
|
|
718
|
+
prependMany(event, times, listener, options) {
|
|
719
|
+
return this.register(event, listener, options, true, times);
|
|
720
|
+
}
|
|
721
|
+
onAny(listener) {
|
|
722
|
+
this.register("", listener, void 0, false, Infinity, true);
|
|
723
|
+
return this;
|
|
724
|
+
}
|
|
725
|
+
prependAny(listener) {
|
|
726
|
+
this.register("", listener, void 0, true, Infinity, true);
|
|
727
|
+
return this;
|
|
728
|
+
}
|
|
729
|
+
offAny(listener) {
|
|
730
|
+
for (const registration of this.registrations.values()) if (registration.any && (!listener || registration.listener === listener)) {
|
|
731
|
+
this.remove(registration);
|
|
732
|
+
if (listener) break;
|
|
733
|
+
}
|
|
734
|
+
return this;
|
|
735
|
+
}
|
|
736
|
+
off(event, listener) {
|
|
737
|
+
const route = this.route(event);
|
|
738
|
+
for (const registration of this.registrations.values()) if (!registration.any && registration.route === route && (registration.listener === listener || registration.wrapped === listener)) {
|
|
739
|
+
this.remove(registration);
|
|
740
|
+
break;
|
|
741
|
+
}
|
|
742
|
+
return this;
|
|
743
|
+
}
|
|
744
|
+
removeListener(event, listener) {
|
|
745
|
+
return this.off(event, listener);
|
|
746
|
+
}
|
|
747
|
+
removeAllListeners(event) {
|
|
748
|
+
const matches = event === void 0 ? void 0 : new Set(this.engine.listeners(this.route(event)));
|
|
749
|
+
for (const registration of this.registrations.values()) if (!registration.any && (!matches || matches.has(registration.wrapped))) this.remove(registration);
|
|
750
|
+
return this;
|
|
751
|
+
}
|
|
752
|
+
listeners(event) {
|
|
753
|
+
if (event === void 0) throw new Error("event name required for wildcard emitter");
|
|
754
|
+
return this.engine.listeners(this.route(event)).map((fn) => this.registrations.get(fn).listener);
|
|
755
|
+
}
|
|
756
|
+
listenersAny() {
|
|
757
|
+
return this.engine.listenersAny().map((fn) => this.registrations.get(fn).listener);
|
|
758
|
+
}
|
|
759
|
+
listenerCount(event) {
|
|
760
|
+
return this.listeners(event).length;
|
|
761
|
+
}
|
|
762
|
+
hasListeners(event) {
|
|
763
|
+
if (event === void 0) return this.registrations.size > 0;
|
|
764
|
+
const name = event instanceof String ? event.valueOf() : event;
|
|
765
|
+
return this.engine.listeners(this.route(name)).length > 0;
|
|
766
|
+
}
|
|
767
|
+
eventNames(nsAsArray = false) {
|
|
768
|
+
const tree = { children: /* @__PURE__ */ new Map() };
|
|
769
|
+
for (const registration of this.registrations.values()) {
|
|
770
|
+
if (registration.any) continue;
|
|
771
|
+
const segments = typeof registration.event === "string" ? registration.event.split(this.delimiter) : typeof registration.event === "symbol" ? [registration.event] : [...registration.event];
|
|
772
|
+
let node = tree;
|
|
773
|
+
for (const segment of segments) {
|
|
774
|
+
let child = node.children.get(segment);
|
|
775
|
+
if (!child) node.children.set(segment, child = { children: /* @__PURE__ */ new Map() });
|
|
776
|
+
node = child;
|
|
777
|
+
}
|
|
778
|
+
node.name = nsAsArray || segments.some((segment) => typeof segment === "symbol") ? segments : segments.join(this.delimiter);
|
|
779
|
+
}
|
|
780
|
+
const names = [];
|
|
781
|
+
const visit = (node) => {
|
|
782
|
+
if (node.name !== void 0) names.push(node.name);
|
|
783
|
+
for (const key of Reflect.ownKeys(Object.fromEntries(node.children)).reverse()) visit(node.children.get(key));
|
|
784
|
+
};
|
|
785
|
+
visit(tree);
|
|
786
|
+
return names;
|
|
787
|
+
}
|
|
788
|
+
setMaxListeners(count) {
|
|
789
|
+
if (typeof count !== "number" || count < 0 || Number.isNaN(count)) throw new TypeError("count must be a non-negative number");
|
|
790
|
+
this.maxListeners = count;
|
|
791
|
+
}
|
|
792
|
+
getMaxListeners() {
|
|
793
|
+
return this.maxListeners;
|
|
794
|
+
}
|
|
795
|
+
emit(event, ...values) {
|
|
796
|
+
this.checkError(event, values);
|
|
797
|
+
if (this.isClosed) return false;
|
|
798
|
+
this.observe(event, values);
|
|
799
|
+
return this.engine.emit(this.route(event), {
|
|
800
|
+
name: this.name(event),
|
|
801
|
+
values
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
emitEffect(event, ...values) {
|
|
805
|
+
return effect.Effect.suspend(() => {
|
|
806
|
+
this.checkError(event, values);
|
|
807
|
+
if (this.isClosed) return effect.Effect.succeed(false);
|
|
808
|
+
this.observe(event, values);
|
|
809
|
+
return this.engine.emitEffect(this.route(event), {
|
|
810
|
+
name: this.name(event),
|
|
811
|
+
values
|
|
812
|
+
});
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
emitAsync(event, ...values) {
|
|
816
|
+
const packet = {
|
|
817
|
+
name: this.name(event),
|
|
818
|
+
values,
|
|
819
|
+
results: []
|
|
820
|
+
};
|
|
821
|
+
return effect.Effect.runPromise(effect.Effect.suspend(() => {
|
|
822
|
+
this.checkError(event, values);
|
|
823
|
+
if (this.isClosed) return effect.Effect.succeed(false);
|
|
824
|
+
this.observe(event, values);
|
|
825
|
+
return this.engine.emitEffect(this.route(event), packet);
|
|
826
|
+
})).then(() => packet.results);
|
|
827
|
+
}
|
|
828
|
+
onScoped(event, listener, options = {}) {
|
|
829
|
+
return effect.Effect.acquireRelease(effect.Effect.gen({ self: this }, function* () {
|
|
830
|
+
const registration = this.makeRegistration(event, listener, options, Infinity, false);
|
|
831
|
+
yield* this.engine.onScoped(registration.route, registration.wrapped, options).pipe(effect.Effect.onExit((exit) => effect.Exit.isFailure(exit) ? effect.Effect.sync(() => this.remove(registration)) : effect.Effect.void));
|
|
832
|
+
if (options.signal?.aborted) this.remove(registration);
|
|
833
|
+
return registration;
|
|
834
|
+
}), (registration) => effect.Effect.sync(() => {
|
|
835
|
+
this.remove(registration);
|
|
836
|
+
})).pipe(effect.Effect.asVoid);
|
|
837
|
+
}
|
|
838
|
+
onAnyScoped(listener, options = {}) {
|
|
839
|
+
return effect.Effect.acquireRelease(effect.Effect.gen({ self: this }, function* () {
|
|
840
|
+
const registration = this.makeRegistration("", listener, options, Infinity, true);
|
|
841
|
+
yield* this.engine.onAnyScoped(registration.wrapped, options).pipe(effect.Effect.onExit((exit) => effect.Exit.isFailure(exit) ? effect.Effect.sync(() => this.remove(registration)) : effect.Effect.void));
|
|
842
|
+
if (options.signal?.aborted) this.remove(registration);
|
|
843
|
+
return registration;
|
|
844
|
+
}), (registration) => effect.Effect.sync(() => {
|
|
845
|
+
this.remove(registration);
|
|
846
|
+
})).pipe(effect.Effect.asVoid);
|
|
847
|
+
}
|
|
848
|
+
waitFor(event, input = {}) {
|
|
849
|
+
const options = typeof input === "number" ? { timeout: input } : typeof input === "function" ? { filter: input } : input;
|
|
850
|
+
const PromiseType = options.Promise ?? Promise;
|
|
851
|
+
let cancel;
|
|
852
|
+
const promise = new PromiseType((resolve, reject) => {
|
|
853
|
+
let settled = false;
|
|
854
|
+
let timer;
|
|
855
|
+
const cleanup = () => {
|
|
856
|
+
this.off(event, listener);
|
|
857
|
+
if (timer) clearTimeout(timer);
|
|
858
|
+
this.pendingWaits.delete(cancel);
|
|
859
|
+
};
|
|
860
|
+
const listener = (...values) => {
|
|
861
|
+
if (options.filter && !options.filter.apply(this, values)) return;
|
|
862
|
+
settled = true;
|
|
863
|
+
cleanup();
|
|
864
|
+
if (options.handleError && values[0]) reject(values[0]);
|
|
865
|
+
else resolve(options.handleError ? values.slice(1) : values);
|
|
866
|
+
};
|
|
867
|
+
cancel = (reason) => {
|
|
868
|
+
if (settled) return void 0;
|
|
869
|
+
settled = true;
|
|
870
|
+
cleanup();
|
|
871
|
+
reject(reason ?? Object.assign(/* @__PURE__ */ new Error("canceled"), { code: "ECANCELED" }));
|
|
872
|
+
};
|
|
873
|
+
this.on(event, listener);
|
|
874
|
+
this.pendingWaits.add(cancel);
|
|
875
|
+
if (options.timeout) timer = setTimeout(() => cancel(Object.assign(/* @__PURE__ */ new Error("timeout"), { code: "ETIMEDOUT" })), options.timeout);
|
|
876
|
+
});
|
|
877
|
+
promise.cancel = cancel;
|
|
878
|
+
return promise;
|
|
879
|
+
}
|
|
880
|
+
listenTo(target, events, options = {}) {
|
|
881
|
+
const on = options.on ?? target.on ?? target.addListener ?? target.addEventListener;
|
|
882
|
+
const off = options.off ?? target.off ?? target.removeListener ?? target.removeEventListener;
|
|
883
|
+
if (!on || !off) throw new TypeError("target must support listener registration and removal");
|
|
884
|
+
const mapping = typeof events === "string" ? Object.fromEntries(events.split(/\s+/).map((event) => [event, event])) : typeof events === "symbol" ? { [events]: events } : Array.isArray(events) ? Object.fromEntries(events.map((event) => [event, event])) : events;
|
|
885
|
+
for (const original of Reflect.ownKeys(mapping)) {
|
|
886
|
+
if ([...this.observers].some((observer) => observer.target === target && observer.event === original)) continue;
|
|
887
|
+
const handler = (...data) => {
|
|
888
|
+
const event = {
|
|
889
|
+
name: mapping[original],
|
|
890
|
+
original,
|
|
891
|
+
data
|
|
892
|
+
};
|
|
893
|
+
if ((typeof options.reducers === "function" ? options.reducers : options.reducers?.[original])?.(event) !== false) this.emit(event.name, ...event.data);
|
|
894
|
+
};
|
|
895
|
+
on.call(target, original, handler);
|
|
896
|
+
this.observers.add({
|
|
897
|
+
target,
|
|
898
|
+
event: original,
|
|
899
|
+
handler,
|
|
900
|
+
off
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
return this;
|
|
904
|
+
}
|
|
905
|
+
stopListeningTo(target, event) {
|
|
906
|
+
let removed = false;
|
|
907
|
+
for (const observer of this.observers) if ((!target || observer.target === target) && (event === void 0 || observer.event === event)) {
|
|
908
|
+
observer.off.call(observer.target, observer.event, observer.handler);
|
|
909
|
+
this.observers.delete(observer);
|
|
910
|
+
removed = true;
|
|
911
|
+
}
|
|
912
|
+
return removed;
|
|
913
|
+
}
|
|
914
|
+
close() {
|
|
915
|
+
return effect.Effect.suspend(() => {
|
|
916
|
+
if (this.closed) return effect.Effect.void;
|
|
917
|
+
this.closed = true;
|
|
918
|
+
this.stopListeningTo();
|
|
919
|
+
for (const cancel of this.pendingWaits) cancel(/* @__PURE__ */ new Error("EventEmitter is closed"));
|
|
920
|
+
for (const registration of this.registrations.values()) registration.cleanup?.();
|
|
921
|
+
this.registrations.clear();
|
|
922
|
+
this.symbolRoutes.clear();
|
|
923
|
+
return this.observations.close().pipe(effect.Effect.andThen(this.engine.close()));
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
register(event, listener, input, prepend = false, times = Infinity, any = false) {
|
|
927
|
+
const options = this.listenerOptions(input);
|
|
928
|
+
const registration = this.makeRegistration(event, listener, options, times, any);
|
|
929
|
+
try {
|
|
930
|
+
if (any) this.engine.onAny(registration.wrapped, {
|
|
931
|
+
...options,
|
|
932
|
+
prepend
|
|
933
|
+
});
|
|
934
|
+
else this.engine.on(registration.route, registration.wrapped, {
|
|
935
|
+
...options,
|
|
936
|
+
prepend
|
|
937
|
+
});
|
|
938
|
+
} catch (error) {
|
|
939
|
+
this.remove(registration);
|
|
940
|
+
throw error;
|
|
941
|
+
}
|
|
942
|
+
if (options.signal?.aborted) this.remove(registration);
|
|
943
|
+
if (options.objectify) {
|
|
944
|
+
const subscription = {
|
|
945
|
+
emitter: this,
|
|
946
|
+
event,
|
|
947
|
+
listener: registration.wrapped,
|
|
948
|
+
off: () => {
|
|
949
|
+
this.remove(registration);
|
|
950
|
+
return subscription;
|
|
951
|
+
}
|
|
952
|
+
};
|
|
953
|
+
return subscription;
|
|
954
|
+
}
|
|
955
|
+
return this;
|
|
956
|
+
}
|
|
957
|
+
makeRegistration(event, listener, options, times, any) {
|
|
958
|
+
if (this.isClosed) throw new Error("EventEmitter is closed");
|
|
959
|
+
if (typeof listener !== "function") throw new TypeError("listener must be a function");
|
|
960
|
+
const registration = {
|
|
961
|
+
event,
|
|
962
|
+
route: this.route(event),
|
|
963
|
+
listener,
|
|
964
|
+
any,
|
|
965
|
+
wrapped: void 0
|
|
966
|
+
};
|
|
967
|
+
let remaining = times;
|
|
968
|
+
const invoke = (packet) => {
|
|
969
|
+
if (remaining === 0 || options.signal?.aborted) return;
|
|
970
|
+
if (--remaining === 0) this.remove(registration);
|
|
971
|
+
this.event = packet.name;
|
|
972
|
+
const values = any ? [packet.name, ...packet.values] : packet.values;
|
|
973
|
+
const call = () => {
|
|
974
|
+
this.event = packet.name;
|
|
975
|
+
return listener.apply(this, values);
|
|
976
|
+
};
|
|
977
|
+
const result = options.async || options.nextTick || options.promisify ? options.promisify ?? listener.constructor.name === "AsyncFunction" ? new Promise((resolve) => options.nextTick ? process.nextTick(resolve) : setImmediate(resolve)).then(call) : options.nextTick ? process.nextTick(call) : setImmediate(call) : call();
|
|
978
|
+
if (!packet.results) return result;
|
|
979
|
+
const index = packet.results.length;
|
|
980
|
+
packet.results.push(void 0);
|
|
981
|
+
if (effect.Effect.isEffect(result)) return result.pipe(effect.Effect.tap((value) => effect.Effect.sync(() => {
|
|
982
|
+
packet.results[index] = value;
|
|
983
|
+
})));
|
|
984
|
+
if (result && typeof result.then === "function") return Promise.resolve(result).then((value) => {
|
|
985
|
+
packet.results[index] = value;
|
|
986
|
+
return value;
|
|
987
|
+
});
|
|
988
|
+
packet.results[index] = result;
|
|
989
|
+
return result;
|
|
990
|
+
};
|
|
991
|
+
registration.wrapped = any ? ((_event, packet) => invoke(packet)) : invoke;
|
|
992
|
+
if (this.options.newListener) this.emit("newListener", event, listener);
|
|
993
|
+
this.registrations.set(registration.wrapped, registration);
|
|
994
|
+
if (options.signal) {
|
|
995
|
+
const abort = () => this.remove(registration);
|
|
996
|
+
options.signal.addEventListener("abort", abort, { once: true });
|
|
997
|
+
registration.cleanup = () => options.signal.removeEventListener("abort", abort);
|
|
998
|
+
}
|
|
999
|
+
return registration;
|
|
1000
|
+
}
|
|
1001
|
+
remove(registration) {
|
|
1002
|
+
if (!this.registrations.delete(registration.wrapped)) return;
|
|
1003
|
+
registration.cleanup?.();
|
|
1004
|
+
if (registration.any) this.engine.offAny(registration.wrapped);
|
|
1005
|
+
else this.engine.off(registration.route, registration.wrapped);
|
|
1006
|
+
if (this.options.removeListener) this.emit(registration.any ? "removeListenerAny" : "removeListener", registration.event, registration.listener);
|
|
1007
|
+
}
|
|
1008
|
+
listenerOptions(input) {
|
|
1009
|
+
return input === true ? { promisify: true } : input === false ? { async: true } : input ?? {};
|
|
1010
|
+
}
|
|
1011
|
+
observe(event, values) {
|
|
1012
|
+
if (!this.observations.enabled) return;
|
|
1013
|
+
const name = this.name(event);
|
|
1014
|
+
this.observations.publish(Object.freeze({
|
|
1015
|
+
event: Array.isArray(name) ? Object.freeze(name.slice()) : name,
|
|
1016
|
+
args: Object.freeze(values.slice())
|
|
1017
|
+
}));
|
|
1018
|
+
}
|
|
1019
|
+
checkError(event, values) {
|
|
1020
|
+
if (!this.ignoreErrors && event === "error" && !this.hasListeners(event) && !this.listenersAny().length) throw values[0] instanceof Error ? values[0] : /* @__PURE__ */ new Error("Uncaught, unspecified 'error' event.");
|
|
1021
|
+
}
|
|
1022
|
+
name(event) {
|
|
1023
|
+
return Array.isArray(event) && !event.some((segment) => typeof segment === "symbol") ? event.join(this.delimiter) : event;
|
|
1024
|
+
}
|
|
1025
|
+
route(event) {
|
|
1026
|
+
if (typeof event === "string" && !event.includes("\0")) return event;
|
|
1027
|
+
const encode = (segment) => {
|
|
1028
|
+
if (typeof segment === "string") return segment.replace(/\u0000/g, "\0s");
|
|
1029
|
+
let key = this.symbolRoutes.get(segment);
|
|
1030
|
+
if (!key) this.symbolRoutes.set(segment, key = `\u0000${this.symbolRoutes.size}`);
|
|
1031
|
+
return key;
|
|
1032
|
+
};
|
|
1033
|
+
if (typeof event === "string") return encode(event);
|
|
1034
|
+
return (typeof event === "symbol" ? [event] : event).map(encode).join(this.delimiter);
|
|
1035
|
+
}
|
|
1036
|
+
};
|
|
1037
|
+
//#endregion
|
|
1038
|
+
exports.EventEmitter = EventEmitter;
|
|
397
1039
|
exports.HyperEmitter = HyperEmitter;
|