amqp-extension 4.0.0-beta.3 → 5.0.0

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.
Files changed (46) hide show
  1. package/README.MD +284 -40
  2. package/dist/index.d.mts +287 -0
  3. package/dist/index.mjs +502 -0
  4. package/dist/index.mjs.map +1 -0
  5. package/package.json +54 -41
  6. package/.editorconfig +0 -13
  7. package/.eslintrc +0 -27
  8. package/.husky/commit-msg +0 -4
  9. package/CHANGELOG.md +0 -125
  10. package/commitlint.config.js +0 -10
  11. package/dist/config/index.d.ts +0 -3
  12. package/dist/config/index.js +0 -25
  13. package/dist/config/module.d.ts +0 -2
  14. package/dist/config/module.js +0 -24
  15. package/dist/config/type.d.ts +0 -13
  16. package/dist/config/type.js +0 -8
  17. package/dist/consume/constants.d.ts +0 -1
  18. package/dist/consume/constants.js +0 -10
  19. package/dist/consume/index.d.ts +0 -3
  20. package/dist/consume/index.js +0 -25
  21. package/dist/consume/type.d.ts +0 -24
  22. package/dist/consume/type.js +0 -8
  23. package/dist/consume/utils.d.ts +0 -2
  24. package/dist/consume/utils.js +0 -17
  25. package/dist/exchange/constants.d.ts +0 -6
  26. package/dist/exchange/constants.js +0 -10
  27. package/dist/exchange/index.d.ts +0 -3
  28. package/dist/exchange/index.js +0 -19
  29. package/dist/exchange/type.d.ts +0 -8
  30. package/dist/exchange/type.js +0 -2
  31. package/dist/exchange/utils.d.ts +0 -4
  32. package/dist/exchange/utils.js +0 -14
  33. package/dist/index.d.ts +0 -6
  34. package/dist/index.js +0 -28
  35. package/dist/module.d.ts +0 -18
  36. package/dist/module.js +0 -187
  37. package/dist/publish/index.d.ts +0 -1
  38. package/dist/publish/index.js +0 -23
  39. package/dist/publish/type.d.ts +0 -7
  40. package/dist/publish/type.js +0 -8
  41. package/dist/type.d.ts +0 -14
  42. package/dist/type.js +0 -2
  43. package/dist/utils.d.ts +0 -2
  44. package/dist/utils.js +0 -23
  45. package/release.config.js +0 -3
  46. package/tsconfig.eslint.json +0 -12
package/README.MD CHANGED
@@ -1,82 +1,326 @@
1
- # AMQP Extension 🏰
1
+ <p align="center">
2
+ <img src="./.github/assets/logo.svg" alt="amqp-extension" width="128" height="128" />
3
+ </p>
2
4
 
3
- [![npm version](https://badge.fury.io/js/amqp-extension.svg)](https://badge.fury.io/js/amqp-extension)
4
- [![codecov](https://codecov.io/gh/Tada5hi/amqp-extension/branch/master/graph/badge.svg?token=6YELWNP9HG)](https://codecov.io/gh/Tada5hi/amqp-extension)
5
- [![Master Workflow](https://github.com/tada5hi/amqp-extension/actions/workflows/main.yml/badge.svg)](https://github.com/Tada5hi/amqp-extension)
6
- [![Known Vulnerabilities](https://snyk.io/test/github/Tada5hi/amqp-extension/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Tada5hi/amqp-extension?targetFile=package.json)
7
- [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
5
+ <h1 align="center">amqp-extension</h1>
8
6
 
9
- This is a library on top of the [amqplib](https://www.npmjs.com/package/amqplib) library and is meant to simplify the process of consuming & publishing queue messages.
7
+ <p align="center">
8
+ <b>Publish and consume RabbitMQ messages without the amqplib boilerplate.</b><br>
9
+ One <code>Client</code> takes care of reconnecting, declaring exchanges and queues, serializing payloads,<br>
10
+ routing messages to handlers and acknowledging them, so you write a call per operation and nothing else.
11
+ </p>
10
12
 
11
- **Table of Contents**
13
+ <p align="center">
14
+ <a href="https://npmjs.com/package/amqp-extension"><img src="https://badge.fury.io/js/amqp-extension.svg" alt="npm version" /></a>
15
+ <a href="https://github.com/Tada5hi/amqp-extension/actions/workflows/main.yml"><img src="https://github.com/Tada5hi/amqp-extension/actions/workflows/main.yml/badge.svg" alt="CI" /></a>
16
+ <a href="https://codecov.io/gh/Tada5hi/amqp-extension"><img src="https://codecov.io/gh/Tada5hi/amqp-extension/branch/master/graph/badge.svg?token=6YELWNP9HG" alt="codecov" /></a>
17
+ <a href="https://snyk.io/test/github/Tada5hi/amqp-extension?targetFile=package.json"><img src="https://snyk.io/test/github/Tada5hi/amqp-extension/badge.svg?targetFile=package.json" alt="Known Vulnerabilities" /></a>
18
+ <a href="https://conventionalcommits.org"><img src="https://img.shields.io/badge/Conventional%20Commits-1.0.0-%23FE5196?logo=conventionalcommits&logoColor=white" alt="Conventional Commits" /></a>
19
+ </p>
20
+
21
+ <p align="center">
22
+ <a href="#installation"><b>Installation</b></a>
23
+ ·
24
+ <a href="#usage">Usage</a>
25
+ ·
26
+ <a href="#options">Options</a>
27
+ ·
28
+ <a href="#api">API</a>
29
+ ·
30
+ <a href="#notes">Notes</a>
31
+ </p>
32
+
33
+ ---
34
+
35
+ ## Why amqp-extension?
36
+
37
+ [amqplib](https://www.npmjs.com/package/amqplib) is a faithful, low-level AMQP 0-9-1 client. It gives you a connection and channels and leaves the rest to you. In practice, every service ends up rewriting the same layer on top: open a channel, assert the exchange, create and bind a queue, `JSON.stringify` the payload, `JSON.parse` it back, choose a handler, `ack` on success, `nack` on failure, and redo all of that after the broker restarts.
38
+
39
+ `amqp-extension` is that layer, written once:
40
+
41
+ | Concern | Plain amqplib | amqp-extension |
42
+ |---|---|---|
43
+ | **Reconnects** | A dropped connection stays dropped. You rebuild the connection, channels and topology yourself | Built on [amqp-connection-manager](https://www.npmjs.com/package/amqp-connection-manager): reconnects automatically and **replays exchange/queue setup** on every reconnect |
44
+ | **Topology** | `assertExchange`, `assertQueue` and `bindQueue` before every publish/consume | Asserted for you. Named exchanges get an exclusive, auto-deleted queue bound to your routing key, or a durable named one. The default exchange gets a durable queue |
45
+ | **Payloads** | `Buffer` in, `Buffer` out | Objects are sent as JSON, strings as UTF-8, and `Buffer`s pass through unchanged |
46
+ | **Dispatch** | One callback receives every message | A handler per message `type`, plus an `$any` fallback |
47
+ | **Acknowledgement** | Call `ack`/`nack` manually on every path, including errors | `ack` after the handler resolves, `nack` when it throws or nothing matches, with an optional requeue |
48
+ | **Defaults** | Pass the same options at every call site | Client-wide publish/consume defaults, deep-merged with per-call options |
49
+ | **Several exchanges** | A separate setup for each | `client.of(exchange)` reuses one connection |
12
50
 
51
+ The same consumer, side by side:
52
+
53
+ ```typescript
54
+ // amqplib
55
+ const connection = await amqplib.connect(url);
56
+ const channel = await connection.createChannel();
57
+ await channel.assertExchange('events', 'topic');
58
+ const { queue } = await channel.assertQueue('', { exclusive: true, autoDelete: true });
59
+ await channel.bindQueue(queue, 'events', 'user.*');
60
+ await channel.consume(queue, async (message) => {
61
+ if (!message) return;
62
+ try {
63
+ const payload = JSON.parse(message.content.toString('utf-8'));
64
+ if (message.properties.type === 'userCreated') await onUserCreated(payload);
65
+ channel.ack(message);
66
+ } catch (e) {
67
+ channel.nack(message, false, false);
68
+ }
69
+ });
70
+ // ...and none of this survives a broker restart
71
+
72
+ // amqp-extension
73
+ const client = new Client({ connectionOptions: url, exchange: { name: 'events', type: 'topic' } });
74
+ await client.consume('user.*', {
75
+ userCreated: async (message) => onUserCreated(JSON.parse(message.content.toString('utf-8'))),
76
+ });
77
+ ```
78
+
79
+ **Table of Contents**
13
80
  - [Installation](#installation)
14
81
  - [Usage](#usage)
82
+ - [Client](#client)
15
83
  - [Publish](#publish)
16
84
  - [Consume](#consume)
85
+ - [Multiple exchanges](#multiple-exchanges)
86
+ - [Errors](#errors)
87
+ - [Options](#options)
88
+ - [Queue options](#queue-options)
89
+ - [API](#api)
90
+ - [Notes](#notes)
17
91
  - [License](#license)
18
92
 
19
-
20
93
  ## Installation
21
94
 
22
95
  ```bash
23
96
  npm install amqp-extension --save
24
97
  ```
25
98
 
99
+ The package is ESM-only and requires Node.js `>=22`.
100
+
26
101
  ## Usage
27
102
 
28
- ### Publish
103
+ ### Client
29
104
 
30
- The `publish` method allows you to send messages quickly.
105
+ A `Client` owns one connection and is bound to one exchange. Leave out `exchange` to use the **default exchange**, which routes each message straight to the queue named in the call.
31
106
 
32
107
  ```typescript
33
- import { Client } from "amqp-extension";
108
+ import { Client } from 'amqp-extension';
34
109
 
35
110
  const client = new Client({
36
111
  connectionOptions: 'amqp://<user>:<password>@<host>',
37
112
  exchange: {
38
- name: '<name>',
39
- type: 'topic'
40
- }
113
+ name: 'events',
114
+ type: 'topic',
115
+ },
41
116
  });
117
+ ```
118
+
119
+ You can pass an existing [amqp-connection-manager](https://www.npmjs.com/package/amqp-connection-manager) connection as `connection` instead of `connectionOptions`.
120
+ `connectionManagerOptions` is passed to amqp-connection-manager's `connect()`, e.g. to change the delay between reconnect attempts (default: 5 s):
42
121
 
43
- (async () => {
44
- await client.publish('<routing-key>', {
45
- foo: 'bar'
46
- });
47
- })();
122
+ ```typescript
123
+ const client = new Client({
124
+ connectionOptions: 'amqp://<user>:<password>@<host>',
125
+ connectionManagerOptions: { reconnectTimeInSeconds: 1 },
126
+ });
127
+ ```
128
+
129
+ ### Publish
130
+
131
+ `publish(to, data, options?)` sends `data` with `to` as the routing key, or as the queue name on the default exchange. It resolves to `true` once the message is handed to the broker.
132
+
133
+ ```typescript
134
+ await client.publish('user.created', { id: 1, name: 'admin' }, {
135
+ type: 'userCreated',
136
+ persistent: true,
137
+ });
48
138
  ```
49
139
 
50
140
  ### Consume
51
141
 
52
- To consume a queue use the `consume` function.
142
+ `consume(from, options?, handlers)` subscribes to messages matching `from` and routes each one to the handler named after its `type` property. A message with no matching handler goes to `$any`.
143
+
144
+ ```typescript
145
+ import type { ConsumeMessage } from 'amqp-extension';
146
+
147
+ await client.consume('user.*', {
148
+ userCreated: async (message: ConsumeMessage) => {
149
+ const payload = JSON.parse(message.content.toString('utf-8'));
150
+ // { id: 1, name: 'admin' }
151
+ },
152
+ $any: async (message: ConsumeMessage) => {
153
+ // every other type
154
+ },
155
+ });
156
+ ```
157
+
158
+ A handler that resolves acknowledges the message. A handler that throws, or a message with no matching handler, gets a `nack`. Pass `onError` to see these failures: it is called after the `nack` with the handler's error, or with a `ClientError` (`HANDLER_MISSING`) when no handler matched. Its own errors are swallowed.
159
+
160
+ ```typescript
161
+ await client.consume('user.*', {
162
+ onError: (error, message) => logger.error(error, { type: message.properties.type }),
163
+ }, {
164
+ userCreated: async (message) => { /* ... */ },
165
+ });
166
+ ```
167
+
168
+ `consume()` resolves a `Consumer` once the subscription is in place. `cancel()` stops new deliveries, waits for the handlers still running (their messages are acked or nacked as usual), then closes the consumer's channel. It never rejects, and the consumer is not re-registered after a reconnect. `await using` cancels it when the scope ends:
169
+
170
+ ```typescript
171
+ const consumer = await client.consume('user.*', { $any: async (message) => { /* ... */ } });
172
+ // ...
173
+ await consumer.cancel();
174
+
175
+ {
176
+ await using scoped = await client.consume('jobs', { $any: async (message) => { /* ... */ } });
177
+ // ...
178
+ } // cancelled here
179
+ ```
180
+
181
+ Both methods also accept a single context object: `client.publish({ to, data, options })`, `client.consume({ from, options, handlers })`.
182
+
183
+ ### Multiple exchanges
184
+
185
+ `of(exchange)` returns a client bound to another exchange. It shares the same connection and default options.
186
+
53
187
  ```typescript
54
- import {
55
- Client,
56
- ConsumeMessage,
57
- ConsumeOptions,
58
- } from "amqp-extension";
188
+ const notifications = client.of({ name: 'notifications', type: 'fanout' });
189
+
190
+ // fanout ignores the routing key, but publish still requires a non-empty one
191
+ await notifications.publish('deploy', { message: 'deploy finished' });
192
+ ```
193
+
194
+ By default, `consume` on a named exchange binds an exclusive, temporary queue that lives only as long as the consumer. Pass `queue` to bind a durable, named queue instead: once a `consume` has declared it, it keeps the messages published while no consumer runs, and consumers sharing it split the messages between them. `publish` declares only the exchange, so messages published before the first `consume` are dropped. Queue options apply to it too.
195
+
196
+ ```typescript
197
+ const events = client.of({ name: 'events', type: 'topic' });
198
+
199
+ await events.consume('user.*', { queue: 'audit', queueType: 'quorum' }, {
200
+ $any: async (message) => { /* ... */ },
201
+ });
202
+ ```
203
+
204
+ The binding stays on the broker: consuming the same `queue` with another `from` adds a binding, it does not replace the old one. On the default exchange, `queue` is ignored, because `from` already is the queue name.
205
+
206
+ Pass `queue` per call rather than in the client's `consumeOptions`: a default applies to every `consume` of the client and its `of()` siblings, binding one queue to all of them. Consumers sharing a `queue` should register the same handlers, because a message reaches only one of them, and one without a matching handler nacks it (and drops it, unless `requeueOnFailure`).
207
+
208
+ ### Errors
209
+
210
+ `publish()` and `consume()` reject only with subclasses of `AmqpExtensionError` (built on [`@ebec/core`](https://www.npmjs.com/package/@ebec/core)). Check the category with `instanceof` and the specific failure with `code`:
211
+
212
+ | Class | `code` |
213
+ |---|---|
214
+ | `TopologyError` | `QUEUE_NAME_EMPTY`, `EXCHANGE_NAME_MISSING`, `DESTINATION_MISSING` |
215
+ | `ClientError` | `CLIENT_CLOSED`, `CHANNEL_CLOSED`, `PUBLISH_TIMEOUT`, `HANDLER_MISSING` (passed to `onError` only) |
216
+ | `BrokerError` | `BROKER_REJECTED`, with the AMQP reply code as `replyCode` |
217
+ | `SerializationError` | `SERIALIZATION_FAILED` |
218
+
219
+ ```typescript
220
+ import { BrokerError, ClientError, ErrorCode } from 'amqp-extension';
221
+
222
+ try {
223
+ await client.publish('jobs', payload, { timeout: 5_000 });
224
+ } catch (e) {
225
+ if (e instanceof BrokerError && e.replyCode === 406) {
226
+ // queue re-declared with different arguments
227
+ } else if (e instanceof ClientError && e.code === ErrorCode.PUBLISH_TIMEOUT) {
228
+ // broker unreachable
229
+ }
230
+ }
231
+ ```
232
+
233
+ The original amqplib / amqp-connection-manager error is available as `cause`.
234
+ `instanceof` also matches errors from a duplicate copy of the library (e.g. two versions in `node_modules`). Errors that crossed a process boundary as JSON (`toJSON()`) are recognized by the guards `isAmqpExtensionError`, `isTopologyError`, `isClientError`, `isBrokerError` and `isSerializationError`.
235
+ A failure the library does not recognize surfaces as the base `AmqpExtensionError` with code `AMQP_EXTENSION_ERROR`, and the original error as `cause`.
236
+
237
+ Earlier releases rejected invalid input with a plain `SyntaxError` or `Error`. Replace `instanceof SyntaxError` checks with `instanceof TopologyError`; the messages are unchanged.
238
+
239
+ ## Options
240
+
241
+ Client-wide defaults go into the constructor. Per-call options are deep-merged on top of them, and the per-call value wins.
59
242
 
243
+ ```typescript
60
244
  const client = new Client({
61
245
  connectionOptions: 'amqp://<user>:<password>@<host>',
62
- exchange: {
63
- name: '<name>',
64
- type: 'topic'
65
- }
246
+ publishOptions: { persistent: true },
247
+ consumeOptions: { prefetchCount: 10, requeueOnFailure: true },
248
+ });
249
+ ```
250
+
251
+ `publishOptions` and `consumeOptions` accept every amqplib `Options.Publish` / `Options.Consume` field, plus:
252
+
253
+ | Option | Applies to | Default | Purpose |
254
+ |---|---|---|---|
255
+ | `requeueOnFailure` | consume | `false` | Requeue messages that are `nack`ed because a handler threw or none matched |
256
+ | `queue` | consume | none | Named exchanges only: consume through this durable, named queue instead of a temporary one (see [Multiple exchanges](#multiple-exchanges)) |
257
+ | `prefetchCount` | consume | none | Maximum number of unacknowledged messages per consumer (`channel.prefetch`) |
258
+ | `noAck` | consume | `false` | amqplib option. When `true`, no `ack`/`nack` is sent at all |
259
+ | `onError` | consume | none | `(error, message) => void \| Promise<void>`, called when a handler threw or none matched (also with `noAck`). A call-site `onError` replaces the client default |
260
+ | Queue options | both | none | `queueType`, `deliveryLimit`, `deadLetterExchange`, `deadLetterRoutingKey`, `messageTtl`, `maxLength`, `singleActiveConsumer` (see below) |
261
+ | `timeout` | publish | none | Milliseconds to wait for the broker to take the message before rejecting with a `ClientError` (`PUBLISH_TIMEOUT`), e.g. while it is unreachable. Without it the call waits for the reconnect |
262
+
263
+ ### Queue options
264
+
265
+ On the default exchange, `consume` and `publish` assert a named, durable queue. Queue options are set flat on the publish/consume options and map to queue arguments. They also apply to the named queue of a `consume` with `queue` on a named exchange; otherwise named exchanges ignore them.
266
+
267
+ | Option | Queue argument | Purpose |
268
+ |---|---|---|
269
+ | `queueType` | `x-queue-type` | `'classic'` or `'quorum'` |
270
+ | `deliveryLimit` | `x-delivery-limit` | Drop or dead-letter a message after this many failed deliveries (quorum queues only). Counts only requeued messages: needs `requeueOnFailure: true`, otherwise a failed message is dropped or dead-lettered on its first failure |
271
+ | `deadLetterExchange` | `x-dead-letter-exchange` | Exchange that rejected or expired messages are republished to |
272
+ | `deadLetterRoutingKey` | `x-dead-letter-routing-key` | Routing key for dead-lettered messages |
273
+ | `messageTtl` | `x-message-ttl` | Expire messages after this many milliseconds in the queue |
274
+ | `maxLength` | `x-max-length` | Maximum number of ready messages, the oldest are dropped or dead-lettered beyond it |
275
+ | `singleActiveConsumer` | `x-single-active-consumer` | Deliver to one consumer at a time, in publish order, and fail over to another when it goes away |
276
+
277
+ They are not validated client-side: the broker rejects an invalid combination with a `BrokerError`. It also rejects re-declaring a queue with different arguments, so publisher and consumer must pass the same options.
278
+
279
+ Await the first `consume` (or `publish`) of a new quorum queue before running publisher and consumer concurrently: RabbitMQ 3.13 can crash the channel when a quorum queue is consumed while another channel is still creating it, which drops the connection until it reconnects. Concurrent first publishes to it can also be rejected (`message nacked`) and need a retry.
280
+
281
+ ```typescript
282
+ import { Client } from 'amqp-extension';
283
+
284
+ // no exchange: the default exchange routes to the queue named in each call
285
+ const client = new Client({
286
+ connectionOptions: 'amqp://<user>:<password>@<host>',
287
+ });
288
+
289
+ const queueOptions = { queueType: 'quorum', singleActiveConsumer: true } as const;
290
+
291
+ await client.consume('<queue>', { ...queueOptions, prefetchCount: 1 }, {
292
+ $any: async (message) => { /* ... */ },
66
293
  });
67
294
 
68
- (async () => {
69
- await client.consume('<routing-key>', {
70
- $any: async (message: ConsumeMessage) => {
71
- const content = message.content.toString('utf-8');
72
- const payload = JSON.parse(content);
73
- console.log(payload);
74
- // { type: 'resourceCreated', name: 'foo' }
75
- }
76
- });
77
- })();
295
+ await client.publish('<queue>', { foo: 'bar' }, queueOptions);
78
296
  ```
79
297
 
298
+ ## API
299
+
300
+ | Export | Kind | Purpose |
301
+ |---|---|---|
302
+ | `Client` | class | `publish()`, `consume()`, `of()`, `close()`, `[Symbol.asyncDispose]()`, plus the underlying `connection` |
303
+ | `ClientContext` | type | Constructor input: `connection` / `connectionOptions`, `connectionManagerOptions`, `exchange`, `publishOptions`, `consumeOptions` |
304
+ | `ExchangeType` | enum | `direct` (default exchange), `topic`, `fanout`, `headers` |
305
+ | `ConsumeHandlers` | type | Map from message `type` to handler, with the `$any` fallback key |
306
+ | `Consumer` | type | Resolved by `consume()`: `cancel()` and `[Symbol.asyncDispose]()` |
307
+ | `ConsumeOptions` / `PublishOptions` | type | amqplib options plus the extensions listed above |
308
+ | `QueueOptions` | type | Queue arguments (`queueType`, `deliveryLimit`, `deadLetterExchange`, `deadLetterRoutingKey`, `messageTtl`, `maxLength`, `singleActiveConsumer`), part of both `ConsumeOptions` and `PublishOptions` |
309
+ | `ConsumeMessage` | type | Re-export of amqplib's message type |
310
+ | `AmqpExtensionError`, `TopologyError`, `ClientError`, `BrokerError`, `SerializationError` | class | Error tree, see [Errors](#errors) |
311
+ | `ErrorCode` | enum | Stable error codes |
312
+ | `isAmqpExtensionError`, `isTopologyError`, `isClientError`, `isBrokerError`, `isSerializationError` | function | Error guards that also match duplicate library copies and JSON round-trips |
313
+
314
+ ## Notes
315
+
316
+ - **Close the client when you are done:** `await client.close()`. It closes the shared connection, so every `of()` sibling stops too. Nothing is closed automatically on `SIGINT`; hook it into your app's shutdown, e.g. `process.once('SIGTERM', () => client.close())`. For scoped code (scripts, jobs, tests) use `await using client = new Client(...)`: the client closes when the scope ends, also on a throw. Disposal runs at scope exit, not on a signal, and like `close()` it closes the shared connection, so use it on the root client rather than on `of()` siblings.
317
+ - **Broker errors reject the call.** If the broker rejects the setup, e.g. `PRECONDITION_FAILED` for a queue re-declared with different queue options or `ACCESS_REFUSED` for a queue that is already consumed exclusively, `publish()` / `consume()` reject with a `BrokerError` (the amqplib error is its `cause`). Only that channel closes; the connection stays up. A connection that merely drops during the call is not an error: the call completes after the reconnect (`publish` is bounded by its `timeout` option).
318
+ - **Calls after `close()` reject** with a `ClientError` (`CLIENT_CLOSED`), also on `of()` siblings.
319
+ - **A consumer cancelled by the broker stays cancelled**, e.g. when its queue is deleted. Call `consume()` again after re-creating the queue.
320
+ - **Invalid input rejects before anything touches the broker:** an empty queue name on the default exchange, a named exchange type without a `name`, or an empty routing key when publishing to a named exchange, with a `TopologyError`.
321
+ - **Unconsumed fanout/topic messages are dropped**, unless `consume` passes `queue` and has declared it at least once. Without it, named exchanges bind an exclusive, auto-deleted queue per `consume` call, which lives only as long as that consumer.
322
+ - **Handler errors are not rethrown.** They are passed to the `onError` consume option, if set.
323
+
80
324
  ## License
81
325
 
82
326
  Made with 💚
@@ -0,0 +1,287 @@
1
+ import { BaseError, ErrorInput } from "@ebec/core";
2
+ import { AmqpConnectionManagerOptions, connect } from "amqp-connection-manager";
3
+ import { Channel, ConsumeMessage, Options } from "amqplib";
4
+ //#region src/consume/constants.d.ts
5
+ export declare const ConsumeHandlerAnyKey = "$any";
6
+ //#endregion
7
+ //#region src/queue/types.d.ts
8
+ /**
9
+ * Options of a named, durable queue, accepted flat on both ConsumeOptions and PublishOptions.
10
+ * They map to queue arguments (x-*) and are not validated client-side:
11
+ * the broker rejects an invalid combination with a BrokerError.
12
+ * Publisher and consumer must pass the same options: a broker rejects
13
+ * re-declaring a queue with different arguments.
14
+ */
15
+ export type QueueOptions = {
16
+ /**
17
+ * Queue type (x-queue-type).
18
+ *
19
+ * Default: the broker's default (classic)
20
+ */
21
+ queueType?: 'classic' | 'quorum';
22
+ /**
23
+ * Drop or dead-letter a message after this many failed deliveries
24
+ * (x-delivery-limit). Quorum queues only. Counts requeued deliveries, so it needs
25
+ * requeueOnFailure: true (or a redelivery after a disconnect).
26
+ */
27
+ deliveryLimit?: number;
28
+ /**
29
+ * Exchange that rejected or expired messages are republished to (x-dead-letter-exchange).
30
+ */
31
+ deadLetterExchange?: string;
32
+ /**
33
+ * Routing key for dead-lettered messages, instead of their original one
34
+ * (x-dead-letter-routing-key).
35
+ */
36
+ deadLetterRoutingKey?: string;
37
+ /**
38
+ * Expire messages after this many milliseconds in the queue (x-message-ttl).
39
+ */
40
+ messageTtl?: number;
41
+ /**
42
+ * Maximum number of ready messages; the oldest are dropped or dead-lettered
43
+ * beyond it (x-max-length).
44
+ */
45
+ maxLength?: number;
46
+ /**
47
+ * Deliver to one consumer at a time, in publish order, failing over to
48
+ * another consumer when it goes away (x-single-active-consumer).
49
+ *
50
+ * Default: false
51
+ */
52
+ singleActiveConsumer?: boolean;
53
+ };
54
+ //#endregion
55
+ //#region src/consume/types.d.ts
56
+ export type ConsumeMessageHandler = (message: ConsumeMessage, channel: Channel) => Promise<void> | void;
57
+ export type ConsumeHandlers = {
58
+ [ConsumeHandlerAnyKey]?: ConsumeMessageHandler;
59
+ } & {
60
+ [key: string]: ConsumeMessageHandler;
61
+ };
62
+ export type ConsumeOptions = Options.Consume & QueueOptions & {
63
+ /**
64
+ * Default: false
65
+ */
66
+ requeueOnFailure?: boolean;
67
+ /**
68
+ * Default: undefined
69
+ */
70
+ prefetchCount?: number;
71
+ /**
72
+ * Named exchanges only: consume through this durable, named queue instead of
73
+ * an exclusive, temporary one. Once declared by a consume, it keeps messages while
74
+ * no consumer runs, and consumers sharing it split the messages. An empty name
75
+ * throws. Ignored on the default exchange.
76
+ *
77
+ * Default: undefined
78
+ */
79
+ queue?: string;
80
+ /**
81
+ * Called after a message was nacked (or not settled, with noAck) because its handler threw
82
+ * (with that error) or no handler matched (with a ClientError, code HANDLER_MISSING).
83
+ * Its own errors are swallowed.
84
+ */
85
+ onError?: (error: unknown, message: ConsumeMessage) => Promise<void> | void;
86
+ };
87
+ /**
88
+ * Resolved by consume(). `await using consumer = await client.consume(...)` cancels it when the scope ends.
89
+ */
90
+ export type Consumer = {
91
+ /**
92
+ * Stop receiving messages, wait for the handlers still running (their messages are settled),
93
+ * then close the channel. Never rejects; calling it again returns the same promise.
94
+ */
95
+ cancel(): Promise<void>;
96
+ [Symbol.asyncDispose](): Promise<void>;
97
+ };
98
+ export type ConsumeContext = {
99
+ from: string;
100
+ options?: ConsumeOptions;
101
+ handlers: ConsumeHandlers;
102
+ };
103
+ //#endregion
104
+ //#region src/errors/base.d.ts
105
+ /**
106
+ * Root of every error thrown by amqp-extension.
107
+ *
108
+ * instanceof is duck-typed through @ebec/core's marker chain, so it also matches errors
109
+ * from a duplicate copy of the library. Every subclass overrides Symbol.hasInstance with
110
+ * its own marker, otherwise it would inherit this one and match every library error.
111
+ */
112
+ export declare class AmqpExtensionError extends BaseError {
113
+ static [Symbol.hasInstance](input: unknown): boolean;
114
+ constructor(input?: ErrorInput);
115
+ }
116
+ //#endregion
117
+ //#region src/errors/types.d.ts
118
+ export type BrokerReply = {
119
+ replyCode: number;
120
+ classId?: number;
121
+ methodId?: number;
122
+ };
123
+ /**
124
+ * An amqplib error for a broker rejection (code = AMQP reply code).
125
+ */
126
+ export type AmqpReplyError = Error & {
127
+ code: number;
128
+ classId?: number;
129
+ methodId?: number;
130
+ };
131
+ //#endregion
132
+ //#region src/errors/broker.d.ts
133
+ /**
134
+ * The broker rejected an operation, e.g. 406 PRECONDITION_FAILED or 403 ACCESS_REFUSED.
135
+ */
136
+ export declare class BrokerError extends AmqpExtensionError {
137
+ static [Symbol.hasInstance](input: unknown): boolean;
138
+ readonly replyCode: number;
139
+ readonly classId?: number;
140
+ readonly methodId?: number;
141
+ constructor(input: ErrorInput, reply: BrokerReply);
142
+ toJSON(): {
143
+ replyCode: number;
144
+ classId: number | undefined;
145
+ methodId: number | undefined;
146
+ name: string;
147
+ message: string;
148
+ code: string;
149
+ cause?: unknown;
150
+ errors?: unknown[];
151
+ issues?: readonly import("@ebec/core").Issue[];
152
+ "@instanceof": string[];
153
+ };
154
+ static fromAmqp(err: AmqpReplyError): BrokerError;
155
+ }
156
+ //#endregion
157
+ //#region src/errors/client.d.ts
158
+ export declare class ClientError extends AmqpExtensionError {
159
+ static [Symbol.hasInstance](input: unknown): boolean;
160
+ constructor(input?: ErrorInput);
161
+ static closed(): ClientError;
162
+ static channelClosed(cause?: unknown): ClientError;
163
+ static handlerMissing(type?: string): ClientError;
164
+ static timeout(cause?: unknown): ClientError;
165
+ }
166
+ //#endregion
167
+ //#region src/errors/serialization.d.ts
168
+ export declare class SerializationError extends AmqpExtensionError {
169
+ static [Symbol.hasInstance](input: unknown): boolean;
170
+ constructor(input?: ErrorInput);
171
+ static payload(cause?: unknown): SerializationError;
172
+ }
173
+ //#endregion
174
+ //#region src/errors/topology.d.ts
175
+ export declare class TopologyError extends AmqpExtensionError {
176
+ static [Symbol.hasInstance](input: unknown): boolean;
177
+ constructor(input?: ErrorInput);
178
+ static queueNameEmpty(): TopologyError;
179
+ static exchangeNameMissing(): TopologyError;
180
+ static destinationMissing(): TopologyError;
181
+ }
182
+ //#endregion
183
+ //#region src/errors/check.d.ts
184
+ export declare function isAmqpExtensionError(input: unknown): input is AmqpExtensionError;
185
+ export declare function isTopologyError(input: unknown): input is TopologyError;
186
+ export declare function isClientError(input: unknown): input is ClientError;
187
+ export declare function isBrokerError(input: unknown): input is BrokerError;
188
+ export declare function isSerializationError(input: unknown): input is SerializationError;
189
+ //#endregion
190
+ //#region src/errors/constants.d.ts
191
+ export declare enum ErrorCode {
192
+ QUEUE_NAME_EMPTY = "QUEUE_NAME_EMPTY",
193
+ EXCHANGE_NAME_MISSING = "EXCHANGE_NAME_MISSING",
194
+ DESTINATION_MISSING = "DESTINATION_MISSING",
195
+ CLIENT_CLOSED = "CLIENT_CLOSED",
196
+ CHANNEL_CLOSED = "CHANNEL_CLOSED",
197
+ PUBLISH_TIMEOUT = "PUBLISH_TIMEOUT",
198
+ HANDLER_MISSING = "HANDLER_MISSING",
199
+ BROKER_REJECTED = "BROKER_REJECTED",
200
+ SERIALIZATION_FAILED = "SERIALIZATION_FAILED"
201
+ }
202
+ export declare const AMQP_EXTENSION_ERROR_MARKER: unique symbol;
203
+ export declare const TOPOLOGY_ERROR_MARKER: unique symbol;
204
+ export declare const CLIENT_ERROR_MARKER: unique symbol;
205
+ export declare const BROKER_ERROR_MARKER: unique symbol;
206
+ export declare const SERIALIZATION_ERROR_MARKER: unique symbol;
207
+ //#endregion
208
+ //#region src/exchange/constants.d.ts
209
+ export declare enum ExchangeType {
210
+ FANOUT = "fanout",
211
+ DIRECT = "direct",
212
+ TOPIC = "topic",
213
+ HEADERS = "headers"
214
+ }
215
+ //#endregion
216
+ //#region src/exchange/types.d.ts
217
+ export type ExchangeOptions = Options.AssertExchange;
218
+ export type Exchange = {
219
+ type: `${ExchangeType}`;
220
+ name?: string;
221
+ options?: ExchangeOptions;
222
+ };
223
+ //#endregion
224
+ //#region src/exchange/utils.d.ts
225
+ export declare function isDefaultExchange(input?: `${ExchangeType}`): input is ExchangeType.DIRECT;
226
+ //#endregion
227
+ //#region src/publish/types.d.ts
228
+ export type PublishOptions = Options.Publish & QueueOptions & {
229
+ /**
230
+ * Reject with ClientError (PUBLISH_TIMEOUT) when the message is not
231
+ * handed to the broker within this many milliseconds, e.g. while the
232
+ * broker is unreachable and the connection manager is reconnecting.
233
+ *
234
+ * Default: undefined (wait for the reconnect)
235
+ */
236
+ timeout?: number;
237
+ };
238
+ export type PublishContext = {
239
+ to: string;
240
+ data: any;
241
+ options?: PublishOptions;
242
+ };
243
+ //#endregion
244
+ //#region src/types.d.ts
245
+ export type Connection = ReturnType<typeof connect>;
246
+ export type ConnectionOptions = Options.Connect | string;
247
+ export type ClientContext = {
248
+ connection?: Connection;
249
+ connectionOptions?: ConnectionOptions;
250
+ /**
251
+ * Passed to amqp-connection-manager's connect(), e.g. reconnectTimeInSeconds.
252
+ * Ignored when a connection is given.
253
+ */
254
+ connectionManagerOptions?: AmqpConnectionManagerOptions;
255
+ exchange?: Exchange;
256
+ publishOptions?: PublishOptions;
257
+ consumeOptions?: ConsumeOptions;
258
+ };
259
+ //#endregion
260
+ //#region src/module.d.ts
261
+ export declare class Client {
262
+ readonly connection: Connection;
263
+ protected publishOptions: PublishOptions;
264
+ protected consumeOptions: ConsumeOptions;
265
+ protected exchange: Exchange;
266
+ constructor(ctx: ClientContext);
267
+ of(exchange: Exchange): Client;
268
+ /**
269
+ * Close the (shared) connection and all its channels.
270
+ */
271
+ close(): Promise<void>;
272
+ /**
273
+ * `await using client = new Client(...)` closes the client when the scope ends.
274
+ * Like close(), it closes the shared connection, so use it on the root client, not on of() siblings.
275
+ */
276
+ [Symbol.asyncDispose](): Promise<void>;
277
+ protected assertOpen(): void;
278
+ consume(ctx: ConsumeContext): Promise<Consumer>;
279
+ consume(from: string, handlers: ConsumeHandlers): Promise<Consumer>;
280
+ consume(from: string, options: ConsumeOptions, handlers: ConsumeHandlers): Promise<Consumer>;
281
+ publish(ctx: PublishContext): Promise<boolean>;
282
+ publish(to: string, data: any): Promise<boolean>;
283
+ publish(to: string, data: any, options: PublishOptions): Promise<boolean>;
284
+ }
285
+ //#endregion
286
+ export type { ConsumeMessage };
287
+ //# sourceMappingURL=index.d.mts.map