@zudojs/messaging 1.0.0 → 1.0.2

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
@@ -2,6 +2,12 @@
2
2
 
3
3
  In-process message bus infrastructure with handlers, middleware, and publish/subscribe patterns.
4
4
 
5
+ <!-- zudo-docs:start -->
6
+
7
+ **Documentation:** [zudojs.oyinlola.site/docs/packages-messaging](https://zudojs.oyinlola.site/docs/packages-messaging) · **For AI agents:** [Markdown version](https://zudojs.oyinlola.site/docs/packages-messaging.md), [llms.txt](https://zudojs.oyinlola.site/llms.txt)
8
+
9
+ <!-- zudo-docs:end -->
10
+
5
11
  ## Installation
6
12
 
7
13
  ```bash
@@ -79,6 +85,12 @@ const bus = createMessageBus({ allowMultipleHandlers: false });
79
85
  `DispatchResult.handlerResults` records every handler that ran, including the
80
86
  one that failed, with its real duration.
81
87
 
88
+ Handlers receive the dispatch context as their second argument: the
89
+ `headers`, `state` and correlation/causation overrides passed through
90
+ `DispatchOptions.context`, plus anything a middleware stored in
91
+ `context.state`. A dispatch cancelled through its `AbortSignal` between
92
+ handlers fails with `MessageDispatchAbortedError`.
93
+
82
94
  ## Timeouts
83
95
 
84
96
  `timeout` is honoured by the dispatcher itself, so it applies whether you hold
@@ -33,7 +33,7 @@ export class DefaultDispatcher {
33
33
  this.validateNotDisposed(message);
34
34
  const timeout = options.timeout ?? 0;
35
35
  const controller = new AbortController();
36
- const signal = this.resolveSignal(options.signal, controller);
36
+ const { signal, release } = this.resolveSignal(options.signal, controller);
37
37
  const context = createMessageContext(message, {
38
38
  ...options.context,
39
39
  signal,
@@ -52,11 +52,17 @@ export class DefaultDispatcher {
52
52
  const handlerResults = [];
53
53
  let timer;
54
54
  try {
55
- const run = runMessagePipeline(allMiddleware, async (msg, mwCtx) => this.executeHandlers(msg, handlers, handlerResults, mwCtx.signal), message, {
55
+ const run = runMessagePipeline(allMiddleware,
56
+ // Handlers receive the same context the middleware saw: the one
57
+ // built from `DispatchOptions.context` (headers, state, correlation
58
+ // overrides) plus anything a middleware put into `state`. A fresh
59
+ // context per handler used to drop all of that on the floor.
60
+ async (msg, mwCtx) => this.executeHandlers(msg, handlers, handlerResults, mwCtx.context), message, {
56
61
  signal: context.signal,
57
- metadata: options.context?.headers,
58
- state: options.context?.state,
62
+ metadata: context.headers,
63
+ state: context.state,
59
64
  middlewareIds,
65
+ context,
60
66
  });
61
67
  // `DispatchOptions.timeout` was documented on the dispatcher but only
62
68
  // ever honoured by the bus wrapper, so anyone holding a dispatcher
@@ -92,6 +98,9 @@ export class DefaultDispatcher {
92
98
  finally {
93
99
  if (timer !== undefined)
94
100
  clearTimeout(timer);
101
+ // Detach from the caller's signal, otherwise a long-lived signal
102
+ // shared across dispatches accumulates one listener per dispatch.
103
+ release();
95
104
  }
96
105
  }
97
106
  /** A promise that rejects with {@link MessageTimeoutError} and aborts. */
@@ -133,19 +142,30 @@ export class DefaultDispatcher {
133
142
  resolveSignal(signal, controller) {
134
143
  if (signal?.aborted)
135
144
  throw new MessageDispatchAbortedError();
136
- if (signal) {
137
- signal.addEventListener("abort", () => controller.abort(signal.reason), {
138
- once: true,
139
- });
145
+ if (!signal) {
146
+ return { signal: controller.signal, release: () => { } };
140
147
  }
141
- return controller.signal;
148
+ const onAbort = () => controller.abort(signal.reason);
149
+ signal.addEventListener("abort", onAbort, { once: true });
150
+ return {
151
+ signal: controller.signal,
152
+ release: () => signal.removeEventListener("abort", onAbort),
153
+ };
142
154
  }
143
- async executeHandlers(message, handlers, handlerResults, signal) {
155
+ async executeHandlers(message, handlers, handlerResults, context) {
144
156
  const results = [];
145
157
  for (const handler of handlers) {
158
+ // A dispatch cancelled between handlers is reported as an abort, not
159
+ // as a failure of the handler that never got to run.
160
+ if (context.signal.aborted) {
161
+ throw new MessageDispatchAbortedError(undefined, {
162
+ messageType: message.type,
163
+ messageId: message.id,
164
+ });
165
+ }
146
166
  const start = performance.now();
147
167
  try {
148
- const result = await this.executeHandler(handler, message, signal);
168
+ const result = await this.executeHandler(handler, message, context);
149
169
  results.push(result);
150
170
  handlerResults.push({
151
171
  handlerId: handler.id,
@@ -168,11 +188,8 @@ export class DefaultDispatcher {
168
188
  }
169
189
  return results.length === 1 ? results[0] : results;
170
190
  }
171
- async executeHandler(handler, message, signal) {
191
+ async executeHandler(handler, message, context) {
172
192
  try {
173
- if (signal.aborted)
174
- throw new MessageDispatchAbortedError();
175
- const context = createMessageContext(message, { signal });
176
193
  return await handler.handler(message, context);
177
194
  }
178
195
  catch (error) {
@@ -20,7 +20,19 @@ export class HandlerRegistryStore {
20
20
  }
21
21
  register(handler) {
22
22
  this.validateNotDuplicate(handler.id);
23
- this.validateSingleHandlerPerType(handler);
23
+ // Replacing a handler id must drop the old entry from the type index
24
+ // first, or the replacement keeps receiving the old handler's types.
25
+ const previous = this.handlers.get(handler.id);
26
+ if (previous !== undefined)
27
+ this.removeHandlerFromTypeIndex(previous);
28
+ try {
29
+ this.validateSingleHandlerPerType(handler);
30
+ }
31
+ catch (error) {
32
+ if (previous !== undefined)
33
+ this.indexHandlerTypes(previous.handler);
34
+ throw error;
35
+ }
24
36
  const entry = {
25
37
  handler,
26
38
  registeredAt: new Date(),
@@ -13,6 +13,6 @@ export function resolveMessageHandler(handler) {
13
13
  if (typeof handler === "function") {
14
14
  return handler;
15
15
  }
16
- return handler.handle;
16
+ return handler.handle.bind(handler);
17
17
  }
18
18
  //# sourceMappingURL=messageHandlerType.type.js.map
@@ -3,32 +3,7 @@
3
3
  *
4
4
  * @module messageMiddleware/messageMiddlewarePipeline
5
5
  */
6
- /**
7
- * Compose an array of middleware into a single function.
8
- *
9
- * The returned function executes middleware in order.
10
- * If no middleware is provided, the handler is called directly.
11
- */
12
- function compose(middlewareList, handler) {
13
- if (middlewareList.length === 0) {
14
- return handler;
15
- }
16
- return async (context) => {
17
- let index = -1;
18
- async function dispatch(i) {
19
- if (i <= index) {
20
- throw new Error("next() called multiple times");
21
- }
22
- index = i;
23
- if (i < middlewareList.length) {
24
- const mw = middlewareList[i];
25
- return mw(context, () => dispatch(i + 1));
26
- }
27
- return handler(context);
28
- }
29
- return dispatch(0);
30
- };
31
- }
6
+ import { compose } from "@zudojs/middleware";
32
7
  /**
33
8
  * Resolves a MessageMiddlewareLike to a plain MessageMiddleware function.
34
9
  */
@@ -36,7 +11,7 @@ function resolveMiddlewareLike(mw) {
36
11
  if (typeof mw === "function") {
37
12
  return mw;
38
13
  }
39
- return mw.handle;
14
+ return mw.handle.bind(mw);
40
15
  }
41
16
  /**
42
17
  * Runs a handler through a middleware pipeline and returns the
@@ -78,10 +53,11 @@ export async function runMessagePipeline(middlewareList, handler, message, optio
78
53
  };
79
54
  });
80
55
  const pipelineStart = performance.now();
81
- const composed = compose(resolvedMiddleware, async (ctx) => handler(message, ctx));
56
+ // Unbounded depth: the list length is fixed by the registered middleware.
57
+ const composed = compose(resolvedMiddleware, async (ctx) => handler(message, ctx), { maxDepth: Number.POSITIVE_INFINITY });
82
58
  const context = {
83
59
  message,
84
- context: {
60
+ context: options.context ?? {
85
61
  message,
86
62
  correlationId: message.correlationId ??
87
63
  message.id,
@@ -98,5 +98,10 @@ export interface MessageMiddlewarePipelineOptions {
98
98
  * records. Positions without an id fall back to a synthesised one.
99
99
  */
100
100
  readonly middlewareIds?: readonly string[];
101
+ /**
102
+ * Message context to expose as `MessageMiddlewareContext.context`.
103
+ * When omitted one is derived from the message and the options above.
104
+ */
105
+ readonly context?: MessageContext;
101
106
  }
102
107
  //# sourceMappingURL=messageMiddlewareType.type.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zudojs/messaging",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "In-process message bus infrastructure with handlers, middleware, and publish/subscribe patterns.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -19,8 +19,9 @@
19
19
  "!dist/.tsbuildinfo"
20
20
  ],
21
21
  "dependencies": {
22
- "@zudojs/errors": "1.0.0",
23
- "@zudojs/constants": "1.0.0"
22
+ "@zudojs/constants": "1.1.0",
23
+ "@zudojs/errors": "1.1.0",
24
+ "@zudojs/middleware": "1.0.2"
24
25
  },
25
26
  "engines": {
26
27
  "node": ">=24.0.0"
@@ -30,6 +31,10 @@
30
31
  "vitest": "^4.1.11"
31
32
  },
32
33
  "license": "MIT",
34
+ "author": {
35
+ "name": "Oluwayemi Oyinlola",
36
+ "url": "https://github.com/oyinlola-tech"
37
+ },
33
38
  "publishConfig": {
34
39
  "access": "public"
35
40
  },