@blixis-io/events 0.1.2 → 0.2.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/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +57 -3
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -22,6 +22,12 @@ export declare function defineEventsModule<Events extends Record<string, unknown
|
|
|
22
22
|
forRoot(options?: EventsForRootOptions): DynamicModule;
|
|
23
23
|
};
|
|
24
24
|
EVENT_BUS: InjectionToken<EventBus<Events>>;
|
|
25
|
+
/**
|
|
26
|
+
* Subscribes the decorated method to `type`. The compiler checks the method accepts that event's
|
|
27
|
+
* payload. Works on any singleton provider (or controller) in the application; the handlers are
|
|
28
|
+
* attached once the app has booted, so an event emitted from `onModuleInit` is not seen yet.
|
|
29
|
+
*/
|
|
30
|
+
OnEvent: <K extends keyof Events & string>(type: K) => <T extends (payload: Events[K]) => void | Promise<void>>(target: object, method: string | symbol, descriptor: TypedPropertyDescriptor<T>) => void;
|
|
25
31
|
};
|
|
26
32
|
//#endregion
|
|
27
33
|
export type { EventBus, EventHandler, EventsForRootOptions };
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/module.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/module.ts"],"mappings":";;;KASY,aAAa,YAAY,SAAS,mBAAmB;UAEhD,SAAS,eAAe;EACvC,KAAK,gBAAgB,iBAAiB,MAAM,GAAG,SAAS,OAAO,KAAK;;EAEpE,GAAG,gBAAgB,iBAAiB,MAAM,GAAG,SAAS,aAAa,OAAO;;UAG3D;;EAEf;;;;;;;;wBA4Dc,mBAAmB,eAAe;EAChD;IAAgB,QAAQ,UAAU,uBAAuB;;EACzD,WAAW,eAAe,SAAS;;;;;;EAMnC,UAAU,gBAAgB,iBACxB,MAAM,OACF,WAAW,SAAS,OAAO,cAAc,eAC7C,gBACA,yBACA,YAAY,wBAAwB"}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Module } from "@blixis-io/core";
|
|
2
|
-
import { Injectable, InjectionToken } from "@blixis-io/di";
|
|
2
|
+
import { Inject, Injectable, InjectionToken, defineMetadata, getOwnMetadata } from "@blixis-io/di";
|
|
3
3
|
//#region \0@oxc-project+runtime@0.151.0/helpers/esm/decorate.js
|
|
4
4
|
function __decorate(decorators, target, key, desc) {
|
|
5
5
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
@@ -8,6 +8,18 @@ function __decorate(decorators, target, key, desc) {
|
|
|
8
8
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
9
9
|
}
|
|
10
10
|
//#endregion
|
|
11
|
+
//#region \0@oxc-project+runtime@0.151.0/helpers/esm/decorateMetadata.js
|
|
12
|
+
function __decorateMetadata(k, v) {
|
|
13
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region \0@oxc-project+runtime@0.151.0/helpers/esm/decorateParam.js
|
|
17
|
+
function __decorateParam(paramIndex, decorator) {
|
|
18
|
+
return function(target, key) {
|
|
19
|
+
decorator(target, key, paramIndex);
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
//#endregion
|
|
11
23
|
//#region src/module.ts
|
|
12
24
|
/**
|
|
13
25
|
* Runs every handler for an event concurrently and in-process — no
|
|
@@ -48,6 +60,47 @@ InProcessEventBus = __decorate([Injectable()], InProcessEventBus);
|
|
|
48
60
|
function defineEventsModule() {
|
|
49
61
|
var _EventsModule;
|
|
50
62
|
const EVENT_BUS = new InjectionToken("blixis.events.bus");
|
|
63
|
+
const HANDLERS = Symbol("blixis.events.handlers");
|
|
64
|
+
function OnEvent(type) {
|
|
65
|
+
return (target, method, _descriptor) => {
|
|
66
|
+
const own = getOwnMetadata(HANDLERS, target) ?? [];
|
|
67
|
+
defineMetadata(HANDLERS, [...own, {
|
|
68
|
+
type,
|
|
69
|
+
method
|
|
70
|
+
}], target);
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** Every `@OnEvent` handler declared on `instance`'s class or any of its base classes. */
|
|
74
|
+
function handlersOf(instance) {
|
|
75
|
+
const records = [];
|
|
76
|
+
for (let proto = Object.getPrototypeOf(instance); typeof proto === "object" && proto !== null; proto = Object.getPrototypeOf(proto)) records.push(...getOwnMetadata(HANDLERS, proto) ?? []);
|
|
77
|
+
return records;
|
|
78
|
+
}
|
|
79
|
+
/** Finds the `@OnEvent` methods across the whole application after boot and subscribes them. */
|
|
80
|
+
let EventSubscriber = class EventSubscriber {
|
|
81
|
+
#unsubscribe = [];
|
|
82
|
+
constructor(bus) {
|
|
83
|
+
this.bus = bus;
|
|
84
|
+
}
|
|
85
|
+
onApplicationBootstrap(app) {
|
|
86
|
+
for (const [, instance] of app.resolved()) {
|
|
87
|
+
if (typeof instance !== "object" || instance === null) continue;
|
|
88
|
+
for (const { type, method } of handlersOf(instance)) {
|
|
89
|
+
const handle = Reflect.get(instance, method);
|
|
90
|
+
if (typeof handle !== "function") throw new TypeError(`${instance.constructor.name}.${String(method)} is decorated with @OnEvent("${type}") but is not a method.`);
|
|
91
|
+
this.#unsubscribe.push(this.bus.on(type, (payload) => Reflect.apply(handle, instance, [payload])));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
onApplicationShutdown() {
|
|
96
|
+
for (const off of this.#unsubscribe.splice(0)) off();
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
EventSubscriber = __decorate([
|
|
100
|
+
Injectable(),
|
|
101
|
+
__decorateParam(0, Inject(EVENT_BUS)),
|
|
102
|
+
__decorateMetadata("design:paramtypes", [Object])
|
|
103
|
+
], EventSubscriber);
|
|
51
104
|
let EventsModule = _EventsModule = class EventsModule {
|
|
52
105
|
static forRoot(options = {}) {
|
|
53
106
|
return {
|
|
@@ -55,7 +108,7 @@ function defineEventsModule() {
|
|
|
55
108
|
providers: [{
|
|
56
109
|
provide: EVENT_BUS,
|
|
57
110
|
useClass: InProcessEventBus
|
|
58
|
-
}],
|
|
111
|
+
}, EventSubscriber],
|
|
59
112
|
exports: [EVENT_BUS],
|
|
60
113
|
global: options.global ?? false
|
|
61
114
|
};
|
|
@@ -64,7 +117,8 @@ function defineEventsModule() {
|
|
|
64
117
|
EventsModule = _EventsModule = __decorate([Module()], EventsModule);
|
|
65
118
|
return {
|
|
66
119
|
EventsModule,
|
|
67
|
-
EVENT_BUS
|
|
120
|
+
EVENT_BUS,
|
|
121
|
+
OnEvent
|
|
68
122
|
};
|
|
69
123
|
}
|
|
70
124
|
//#endregion
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/module.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/module.ts"],"sourcesContent":["import {\n Module,\n type BootstrapContext,\n type DynamicModule,\n type OnApplicationBootstrap,\n type OnApplicationShutdown,\n} from \"@blixis-io/core\";\nimport { defineMetadata, getOwnMetadata, Inject, Injectable, InjectionToken } from \"@blixis-io/di\";\n\nexport type EventHandler<Payload> = (payload: Payload) => void | Promise<void>;\n\nexport interface EventBus<Events extends Record<string, unknown>> {\n emit<K extends keyof Events & string>(type: K, payload: Events[K]): Promise<void>;\n /** Registers `handler` for `type`, returning a function that unsubscribes just this handler. */\n on<K extends keyof Events & string>(type: K, handler: EventHandler<Events[K]>): () => void;\n}\n\nexport interface EventsForRootOptions {\n /** Makes `EVENT_BUS` visible to every module without each one importing this one directly. Defaults to `false`. */\n global?: boolean;\n}\n\n/**\n * Runs every handler for an event concurrently and in-process — no\n * persistence, no delivery guarantee across a crash. Deliberately the only\n * implementation for now; see `concepts/events.md` for why a transactional\n * outbox was deferred rather than built ahead of a real consumer.\n */\n@Injectable()\nclass InProcessEventBus<Events extends Record<string, unknown>> implements EventBus<Events> {\n readonly #handlers = new Map<string, Set<EventHandler<never>>>();\n\n on<K extends keyof Events & string>(type: K, handler: EventHandler<Events[K]>): () => void {\n let handlers = this.#handlers.get(type);\n if (!handlers) {\n handlers = new Set();\n this.#handlers.set(type, handlers);\n }\n handlers.add(handler);\n return () => handlers.delete(handler);\n }\n\n async emit<K extends keyof Events & string>(type: K, payload: Events[K]): Promise<void> {\n const handlers = this.#handlers.get(type);\n if (!handlers || handlers.size === 0) {\n return;\n }\n\n await Promise.all(\n [...handlers].map(async (handler) => {\n try {\n // Handlers for every event type share one Set<EventHandler<never>>\n // collection (indexed by the string `type`, not a type-level key),\n // so there's no way for TS to correlate a specific handler back to\n // the K it was registered with — this cast is the one place that\n // trusts `type` actually matches, same as `on()`'s own erasure.\n await handler(payload as never);\n } catch (error) {\n // A handler's own failure never blocks sibling handlers or the\n // caller — same self-contained fallback @blixis-io/logging's own\n // transport-failure handling already uses.\n console.error(`event handler for \"${type}\" failed:`, error);\n }\n }),\n );\n }\n}\n\ninterface HandlerRecord {\n type: string;\n method: string | symbol;\n}\n\n/**\n * Builds an `EVENT_BUS` token typed to one app's event map. Same\n * factory-closure shape as `defineConfigModule`/`defineAuthModule` — the\n * event-name-to-payload map is app-specific, so it's a generic parameter\n * fixed once per app, not baked into the package.\n */\nexport function defineEventsModule<Events extends Record<string, unknown>>(): {\n EventsModule: { forRoot(options?: EventsForRootOptions): DynamicModule };\n EVENT_BUS: InjectionToken<EventBus<Events>>;\n /**\n * Subscribes the decorated method to `type`. The compiler checks the method accepts that event's\n * payload. Works on any singleton provider (or controller) in the application; the handlers are\n * attached once the app has booted, so an event emitted from `onModuleInit` is not seen yet.\n */\n OnEvent: <K extends keyof Events & string>(\n type: K,\n ) => <T extends (payload: Events[K]) => void | Promise<void>>(\n target: object,\n method: string | symbol,\n descriptor: TypedPropertyDescriptor<T>,\n ) => void;\n} {\n const EVENT_BUS = new InjectionToken<EventBus<Events>>(\"blixis.events.bus\");\n // One metadata key per factory, so two event maps in one app never pick up each other's handlers.\n const HANDLERS = Symbol(\"blixis.events.handlers\");\n\n function OnEvent<K extends keyof Events & string>(type: K) {\n return <T extends (payload: Events[K]) => void | Promise<void>>(\n target: object,\n method: string | symbol,\n _descriptor: TypedPropertyDescriptor<T>,\n ): void => {\n const own = getOwnMetadata<HandlerRecord[]>(HANDLERS, target) ?? [];\n defineMetadata(HANDLERS, [...own, { type, method }], target);\n };\n }\n\n /** Every `@OnEvent` handler declared on `instance`'s class or any of its base classes. */\n function handlersOf(instance: object): HandlerRecord[] {\n const records: HandlerRecord[] = [];\n for (let proto: unknown = Object.getPrototypeOf(instance); typeof proto === \"object\" && proto !== null; proto = Object.getPrototypeOf(proto)) {\n records.push(...(getOwnMetadata<HandlerRecord[]>(HANDLERS, proto) ?? []));\n }\n return records;\n }\n\n /** Finds the `@OnEvent` methods across the whole application after boot and subscribes them. */\n @Injectable()\n class EventSubscriber implements OnApplicationBootstrap, OnApplicationShutdown {\n readonly #unsubscribe: (() => void)[] = [];\n\n constructor(@Inject(EVENT_BUS) private readonly bus: EventBus<Events>) {}\n\n onApplicationBootstrap(app: BootstrapContext): void {\n for (const [, instance] of app.resolved()) {\n if (typeof instance !== \"object\" || instance === null) {\n continue;\n }\n for (const { type, method } of handlersOf(instance)) {\n const handle: unknown = Reflect.get(instance, method);\n if (typeof handle !== \"function\") {\n throw new TypeError(`${instance.constructor.name}.${String(method)} is decorated with @OnEvent(\"${type}\") but is not a method.`);\n }\n this.#unsubscribe.push(this.bus.on(type, (payload) => Reflect.apply(handle, instance, [payload]) as void | Promise<void>));\n }\n }\n }\n\n onApplicationShutdown(): void {\n for (const off of this.#unsubscribe.splice(0)) {\n off();\n }\n }\n }\n\n @Module()\n class EventsModule {\n static forRoot(options: EventsForRootOptions = {}): DynamicModule {\n return {\n module: EventsModule,\n providers: [{ provide: EVENT_BUS, useClass: InProcessEventBus }, EventSubscriber],\n exports: [EVENT_BUS],\n global: options.global ?? false,\n };\n }\n }\n\n return { EventsModule, EVENT_BUS, OnEvent };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IACM,oBADN,MACM,kBAAsF;CAC1F,4BAAqB,IAAI,IAAsC;CAE/D,GAAoC,MAAS,SAA8C;EACzF,IAAI,WAAW,KAAK,UAAU,IAAI,IAAI;EACtC,IAAI,CAAC,UAAU;GACb,2BAAW,IAAI,IAAI;GACnB,KAAK,UAAU,IAAI,MAAM,QAAQ;EACnC;EACA,SAAS,IAAI,OAAO;EACpB,aAAa,SAAS,OAAO,OAAO;CACtC;CAEA,MAAM,KAAsC,MAAS,SAAmC;EACtF,MAAM,WAAW,KAAK,UAAU,IAAI,IAAI;EACxC,IAAI,CAAC,YAAY,SAAS,SAAS,GACjC;EAGF,MAAM,QAAQ,IACZ,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,OAAO,YAAY;GACnC,IAAI;IAMF,MAAM,QAAQ,OAAgB;GAChC,SAAS,OAAO;IAId,QAAQ,MAAM,sBAAsB,KAAK,YAAY,KAAK;GAC5D;EACF,CAAC,CACH;CACF;AACF;AAtCC,oBAAA,WAAA,CAAA,WAAW,CAAA,GAAA,iBAAA;;;;;;;AAmDZ,SAAgB,qBAed;;CACA,MAAM,YAAY,IAAI,eAAiC,mBAAmB;CAE1E,MAAM,WAAW,OAAO,wBAAwB;CAEhD,SAAS,QAAyC,MAAS;EACzD,QACE,QACA,QACA,gBACS;GACT,MAAM,MAAM,eAAgC,UAAU,MAAM,KAAK,CAAC;GAClE,eAAe,UAAU,CAAC,GAAG,KAAK;IAAE;IAAM;GAAO,CAAC,GAAG,MAAM;EAC7D;CACF;;CAGA,SAAS,WAAW,UAAmC;EACrD,MAAM,UAA2B,CAAC;EAClC,KAAK,IAAI,QAAiB,OAAO,eAAe,QAAQ,GAAG,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
"name": "@blixis-io/events",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "An in-process domain event bus (defineEventsModule, EventBus.emit/on). Depends only on @blixis-io/core — usable in any app, HTTP or not.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Michael Voeten <michael@voeten.online>",
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
}
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@blixis-io/core": "0.
|
|
38
|
-
"@blixis-io/di": "0.1.
|
|
37
|
+
"@blixis-io/core": "0.3.1",
|
|
38
|
+
"@blixis-io/di": "0.1.2"
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|
|
41
41
|
"typecheck": "tsc -p tsconfig.json",
|