@startling/emitter 1.0.3

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.

Potentially problematic release.


This version of @startling/emitter might be problematic. Click here for more details.

package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nicholas Hutchind / Startling Development, LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,218 @@
1
+ # startling-emitter
2
+
3
+ A tiny, fully-typed event emitter with exact keys, namespace wildcards, and Promise-based event waiting.
4
+
5
+ ✨ ~1 kB gzipped
6
+ 🚫 Zero dependencies
7
+ 📦 ESM-first
8
+
9
+ ---
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install @startling/emitter
15
+ ```
16
+
17
+ ---
18
+
19
+ ## Why startling-emitter?
20
+
21
+ - Strongly typed event maps
22
+ - Exact-key subscriptions
23
+ - Namespace wildcards (`user.*`, `user:*`)
24
+ - Global wildcard (`*`)
25
+ - Promise-based `waitFor`
26
+ - AbortSignal + timeout support
27
+ - Safe against listener mutation during emit
28
+ - Zero dependencies
29
+
30
+ ---
31
+
32
+ ## Quick Start (TypeScript)
33
+
34
+ ```ts
35
+ import { createEmitter } from '@startling/emitter';
36
+
37
+ type Events = {
38
+ connected: { id: string };
39
+ message: { from: string; text: string };
40
+ closed: void;
41
+ };
42
+
43
+ const emitter = createEmitter<Events>();
44
+
45
+ const unsubscribe = emitter.on('message', (payload) => {
46
+ console.log(payload.from, payload.text);
47
+ });
48
+
49
+ emitter.emit('message', { from: 'system', text: 'hello' });
50
+ unsubscribe();
51
+ ```
52
+
53
+ Events typed as `void` must be emitted without a payload:
54
+
55
+ ```ts
56
+ emitter.emit('closed'); // ✅
57
+ ```
58
+
59
+ ---
60
+
61
+ ## Quick Start (JavaScript)
62
+
63
+ ```js
64
+ import { createEmitter } from '@startling/emitter';
65
+
66
+ const emitter = createEmitter();
67
+
68
+ emitter.on('message', (payload) => {
69
+ console.log(payload);
70
+ });
71
+
72
+ emitter.emit('message', { from: 'system', text: 'hello' });
73
+ ```
74
+
75
+ Type declarations are included for editor IntelliSense.
76
+
77
+ ---
78
+
79
+ # Wildcards
80
+
81
+ ### Global wildcard
82
+
83
+ ```ts
84
+ emitter.on('*', (event, payload) => {
85
+ console.log('event:', event, 'payload:', payload);
86
+ });
87
+ ```
88
+
89
+ Matches all emitted events.
90
+
91
+ ---
92
+
93
+ ### Namespace wildcards
94
+
95
+ Supports both dot (`.`) and colon (`:`) separators.
96
+
97
+ ```ts
98
+ emitter.on('user.*', (payload) => {
99
+ console.log('dot namespace:', payload);
100
+ });
101
+
102
+ emitter.on('user:*', (payload) => {
103
+ console.log('colon namespace:', payload);
104
+ });
105
+ ```
106
+
107
+ Examples:
108
+
109
+ ```ts
110
+ emitter.emit('user.created', { id: '1' }); // matches "user.*"
111
+ emitter.emit('user:login', { id: '1' }); // matches "user:*"
112
+ ```
113
+
114
+ Namespace matching is prefix-based and evaluated at emit time.
115
+
116
+ ---
117
+
118
+ # waitFor
119
+
120
+ Wait for the next matching event.
121
+
122
+ ```ts
123
+ const payload = await emitter.waitFor('message');
124
+
125
+ emitter.emit('message', { from: 'ops', text: 'ready' });
126
+ ```
127
+
128
+ ### With filtering
129
+
130
+ ```ts
131
+ const adminMessage = await emitter.waitFor('message', {
132
+ filter: (p) => p.from === 'admin'
133
+ });
134
+ ```
135
+
136
+ ### With timeout and AbortSignal
137
+
138
+ ```ts
139
+ const controller = new AbortController();
140
+
141
+ await emitter.waitFor('message', {
142
+ timeoutMs: 1000,
143
+ signal: controller.signal
144
+ });
145
+ ```
146
+
147
+ Rejects with:
148
+
149
+ - `Error('Timed out')`
150
+ - `Error('Aborted')`
151
+
152
+ ---
153
+
154
+ # once
155
+
156
+ Registers a handler that runs at most once:
157
+
158
+ ```ts
159
+ emitter.once('connected', (payload) => {
160
+ console.log('connected:', payload.id);
161
+ });
162
+ ```
163
+
164
+ Works with exact keys and wildcards.
165
+
166
+ ---
167
+
168
+ # Introspection
169
+
170
+ ```ts
171
+ emitter.on('connected', () => {});
172
+ emitter.on('closed', () => {});
173
+
174
+ console.log(emitter.listenerCount('connected')); // 1
175
+ console.log(emitter.eventNames()); // ['connected', 'closed']
176
+
177
+ emitter.clear();
178
+ console.log(emitter.eventNames()); // []
179
+ ```
180
+
181
+ - `listenerCount(event)` — number of listeners attached
182
+ - `eventNames()` — exact event keys currently registered
183
+ - `clear()` — removes all listeners
184
+
185
+ Wildcard registrations are not included in `eventNames()`.
186
+
187
+ ---
188
+
189
+ # API Summary
190
+
191
+ | Method | Description |
192
+ |--------|------------|
193
+ | `on(event, handler)` | Register a listener. Returns unsubscribe function. |
194
+ | `off(event, handler)` | Remove a specific listener. |
195
+ | `once(event, handler)` | Register a listener that auto-unregisters. |
196
+ | `emit(event, payload?)` | Emit an event. |
197
+ | `waitFor(event, options?)` | Resolve when event fires. |
198
+ | `listenerCount(event)` | Number of listeners for a key. |
199
+ | `eventNames()` | List of exact event keys. |
200
+ | `clear()` | Remove all listeners. |
201
+
202
+ ---
203
+
204
+ # Design Notes
205
+
206
+ - Listener sets are snapshotted during `emit`, allowing safe mutation during iteration.
207
+ - Namespace wildcards are prefix-based and support both `.` and `:` separators.
208
+ - All APIs are strongly typed when using a typed event map.
209
+
210
+ ---
211
+
212
+ # Development
213
+
214
+ ```bash
215
+ npm test
216
+ npm run typecheck
217
+ npm run build
218
+ ```
@@ -0,0 +1,5 @@
1
+ import type { Emitter, EventMap } from './types';
2
+ /**
3
+ * Creates a typed emitter with exact-key and wildcard subscriptions.
4
+ */
5
+ export declare function createEmitter<Events extends EventMap>(): Emitter<Events>;
@@ -0,0 +1,2 @@
1
+ export { createEmitter } from './createEmitter';
2
+ export type { Emitter, EventMap, Handler } from './types';
@@ -0,0 +1,137 @@
1
+ function m(i) {
2
+ return i.endsWith(".*") || i.endsWith(":*");
3
+ }
4
+ function p(i) {
5
+ return i.slice(0, -1);
6
+ }
7
+ function b(i) {
8
+ const u = [];
9
+ for (let s = 0; s < i.length; s += 1) {
10
+ const a = i[s];
11
+ (a === "." || a === ":") && u.push(i.slice(0, s + 1));
12
+ }
13
+ return u;
14
+ }
15
+ function F() {
16
+ const i = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Set();
17
+ function a(t, r) {
18
+ let e = t.get(r);
19
+ return e || (e = /* @__PURE__ */ new Set(), t.set(r, e)), e;
20
+ }
21
+ function l(t, r, e) {
22
+ const o = t.get(r);
23
+ o && (o.delete(e), o.size === 0 && t.delete(r));
24
+ }
25
+ function w(t, r) {
26
+ if (t === "*")
27
+ return s.add(r), () => s.delete(r);
28
+ if (typeof t == "string" && m(t)) {
29
+ const e = p(t);
30
+ return a(u, e).add(r), () => l(u, e, r);
31
+ }
32
+ return a(i, t).add(r), () => l(i, t, r);
33
+ }
34
+ function x(t, r) {
35
+ if (t === "*") {
36
+ s.delete(r);
37
+ return;
38
+ }
39
+ if (typeof t == "string" && m(t)) {
40
+ const e = p(t);
41
+ l(u, e, r);
42
+ return;
43
+ }
44
+ l(i, t, r);
45
+ }
46
+ function y(t, r) {
47
+ if (t === "*") {
48
+ const o = (f, n) => {
49
+ s.delete(o), r(f, n);
50
+ };
51
+ s.add(o);
52
+ return;
53
+ }
54
+ if (typeof t == "string" && m(t)) {
55
+ const o = p(t), f = ((n) => {
56
+ l(u, o, f), r(n);
57
+ });
58
+ a(u, o).add(f);
59
+ return;
60
+ }
61
+ const e = (o) => {
62
+ l(i, t, e), r(o);
63
+ };
64
+ a(i, t).add(e);
65
+ }
66
+ function A(t) {
67
+ if (t === "*") return s.size;
68
+ if (typeof t == "string" && m(t)) {
69
+ const r = p(t);
70
+ return u.get(r)?.size ?? 0;
71
+ }
72
+ return i.get(t)?.size ?? 0;
73
+ }
74
+ return {
75
+ on: w,
76
+ off: x,
77
+ listenerCount: A,
78
+ eventNames: () => Array.from(i.keys()),
79
+ clear: () => {
80
+ i.clear(), u.clear(), s.clear();
81
+ },
82
+ emit: (...t) => {
83
+ const r = t[0], e = t.length === 2, o = e ? t[1] : void 0, f = i.get(r);
84
+ if (f)
85
+ for (const n of Array.from(f))
86
+ e ? n(o) : n();
87
+ if (typeof r == "string") {
88
+ const n = b(r);
89
+ for (const g of n) {
90
+ const c = u.get(g);
91
+ if (c)
92
+ for (const d of Array.from(c))
93
+ e ? d(o) : d();
94
+ }
95
+ }
96
+ if (s.size)
97
+ for (const n of Array.from(s))
98
+ e ? n(r, o) : n(r);
99
+ },
100
+ once: y,
101
+ waitFor: (t, r) => new Promise((e, o) => {
102
+ const f = [];
103
+ let n = () => {
104
+ for (let c = f.length - 1; c >= 0; c -= 1) f[c]();
105
+ f.length = 0, n = () => {
106
+ };
107
+ };
108
+ const g = ((c) => {
109
+ try {
110
+ if (r?.filter && !r.filter(c)) return;
111
+ n(), e(c);
112
+ } catch (d) {
113
+ n(), o(d);
114
+ }
115
+ });
116
+ if (f.push(w(t, g)), r?.timeoutMs !== void 0) {
117
+ const c = setTimeout(() => {
118
+ n(), o(new Error("Timed out"));
119
+ }, r.timeoutMs);
120
+ f.push(() => clearTimeout(c));
121
+ }
122
+ if (r?.signal) {
123
+ if (r.signal.aborted) {
124
+ n(), o(new Error("Aborted"));
125
+ return;
126
+ }
127
+ const c = () => {
128
+ n(), o(new Error("Aborted"));
129
+ };
130
+ r.signal.addEventListener("abort", c), f.push(() => r.signal?.removeEventListener("abort", c));
131
+ }
132
+ })
133
+ };
134
+ }
135
+ export {
136
+ F as createEmitter
137
+ };
@@ -0,0 +1,27 @@
1
+ export type EventMap = Record<PropertyKey, any>;
2
+ export type Handler<T = unknown> = T extends void ? () => void : (payload: T) => void;
3
+ export type EmitArgs<Events extends EventMap, K extends keyof Events> = Events[K] extends void ? [event: K] : [event: K, payload: Events[K]];
4
+ export type WildcardKey = '*' | `${string}.*` | `${string}:*`;
5
+ export type AnyEventHandler<Events extends EventMap> = (event: keyof Events, payload?: Events[keyof Events]) => void;
6
+ export type NamespaceWildcardHandler<Events extends EventMap> = Handler<Events[keyof Events]> | (() => void);
7
+ export interface Emitter<Events extends EventMap> {
8
+ on<K extends keyof Events>(event: K, handler: Handler<Events[K]>): () => void;
9
+ on(event: '*', handler: AnyEventHandler<Events>): () => void;
10
+ on(event: `${string}.*` | `${string}:*`, handler: NamespaceWildcardHandler<Events>): () => void;
11
+ off<K extends keyof Events>(event: K, handler: Handler<Events[K]>): void;
12
+ off(event: '*', handler: AnyEventHandler<Events>): void;
13
+ off(event: `${string}.*` | `${string}:*`, handler: NamespaceWildcardHandler<Events>): void;
14
+ listenerCount<K extends keyof Events>(event: K): number;
15
+ listenerCount(event: WildcardKey): number;
16
+ eventNames(): Array<keyof Events>;
17
+ clear(): void;
18
+ emit<K extends keyof Events>(...args: EmitArgs<Events, K>): void;
19
+ once<K extends keyof Events>(event: K, handler: Handler<Events[K]>): void;
20
+ once(event: '*', handler: AnyEventHandler<Events>): void;
21
+ once(event: `${string}.*` | `${string}:*`, handler: NamespaceWildcardHandler<Events>): void;
22
+ waitFor<K extends keyof Events>(event: K, options?: {
23
+ signal?: AbortSignal;
24
+ timeoutMs?: number;
25
+ filter?: (payload: Events[K]) => boolean;
26
+ }): Promise<Events[K]>;
27
+ }
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@startling/emitter",
3
+ "version": "1.0.3",
4
+ "description": "A tiny, fully-typed event emitter for modern TypeScript and JavaScript projects — with wildcard support, Promise-based `waitFor`, and AbortSignal integration.",
5
+ "author": "Nicholas Hutchind",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/StartlingDev/startling-emitter#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/StartlingDev/startling-emitter.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/StartlingDev/startling-emitter/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/startling-emitter.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/startling-emitter.js",
22
+ "default": "./dist/startling-emitter.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "engines": {
32
+ "node": ">=18"
33
+ },
34
+ "scripts": {
35
+ "dev": "vite",
36
+ "build": "rm -rf dist && vite build && tsc -p tsconfig.build.json",
37
+ "prepublishOnly": "npm run build",
38
+ "test": "vitest run",
39
+ "typecheck": "tsc -p tsconfig.json --noEmit",
40
+ "check:clean": "git diff --quiet && git diff --cached --quiet && npm run test && npm run typecheck",
41
+ "release": "npm publish",
42
+ "release:patch": "npm run check:clean && npm version patch && git push --follow-tags && npm run release",
43
+ "release:minor": "npm run check:clean && npm version minor && git push --follow-tags && npm run release",
44
+ "release:major": "npm run check:clean && npm version major && git push --follow-tags && npm run release"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^25.3.0",
48
+ "typescript": "^5.9.0",
49
+ "vite": "^7.0.0",
50
+ "vitest": "^4.0.18"
51
+ }
52
+ }