@babelqueue/azure-service-bus 1.0.0 → 1.1.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.
- package/README.md +18 -0
- package/dist/index.cjs +32 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +36 -5
- package/dist/index.d.ts +36 -5
- package/dist/index.js +31 -3
- package/dist/index.js.map +1 -1
- package/package.json +14 -4
package/README.md
CHANGED
|
@@ -66,6 +66,24 @@ Service Bus is purely additive.
|
|
|
66
66
|
The sender/receiver are injected, so the unit tests use fakes — no Azure, no broker. Dual
|
|
67
67
|
ESM + CJS.
|
|
68
68
|
|
|
69
|
+
## OpenTelemetry tracing (ADR-0028)
|
|
70
|
+
|
|
71
|
+
Cross-hop **span** linkage rides on the out-of-band `HeaderCarrier` from
|
|
72
|
+
[`@babelqueue/core@^1.4.0`](https://www.npmjs.com/package/@babelqueue/core). Pass the carrier produced by
|
|
73
|
+
`@babelqueue/core/otel`'s `publish` to this adapter's `publish({ headers })`; it is carried on
|
|
74
|
+
native `applicationProperties`, beside the contract `bq-*` properties (the contract wins a key collision). On consume, the consumer surfaces a delivered message's headers to the handler's third argument (and a `headersOf(...)` extractor reads them back),
|
|
75
|
+
so the core's `otel` `wrapHandler` starts the consumer span as a true **child** of the producer span.
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { trace } from "@opentelemetry/api";
|
|
79
|
+
import { publish as tracedPublish } from "@babelqueue/core/otel";
|
|
80
|
+
import type { HeaderCarrier } from "@babelqueue/core";
|
|
81
|
+
|
|
82
|
+
const headers: HeaderCarrier = {};
|
|
83
|
+
await tracedPublish(trace.getTracer("orders"), urn, data,
|
|
84
|
+
() => adapterPublish(urn, data, { headers }), { headers });
|
|
85
|
+
```
|
|
86
|
+
|
|
69
87
|
## License
|
|
70
88
|
|
|
71
89
|
MIT
|
package/dist/index.cjs
CHANGED
|
@@ -22,12 +22,28 @@ var index_exports = {};
|
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
AsbConsumer: () => AsbConsumer,
|
|
24
24
|
AsbPublisher: () => AsbPublisher,
|
|
25
|
+
headersOf: () => headersOf,
|
|
25
26
|
toServiceBusMessage: () => toServiceBusMessage
|
|
26
27
|
});
|
|
27
28
|
module.exports = __toCommonJS(index_exports);
|
|
28
29
|
var import_core = require("@babelqueue/core");
|
|
29
|
-
|
|
30
|
+
|
|
31
|
+
// src/headers.ts
|
|
32
|
+
function sanitizeHeaders(headers) {
|
|
33
|
+
const out = {};
|
|
34
|
+
if (!headers) return out;
|
|
35
|
+
for (const key of Object.keys(headers)) {
|
|
36
|
+
const value = headers[key];
|
|
37
|
+
if (key === "" || value == null || value === "") continue;
|
|
38
|
+
out[key] = value;
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// src/index.ts
|
|
44
|
+
function toServiceBusMessage(envelope, extra) {
|
|
30
45
|
const applicationProperties = {};
|
|
46
|
+
for (const [key, value] of Object.entries(sanitizeHeaders(extra))) applicationProperties[key] = value;
|
|
31
47
|
if (envelope.meta.schema_version != null) {
|
|
32
48
|
applicationProperties["bq-schema-version"] = envelope.meta.schema_version;
|
|
33
49
|
}
|
|
@@ -47,6 +63,18 @@ function toServiceBusMessage(envelope) {
|
|
|
47
63
|
}
|
|
48
64
|
return message;
|
|
49
65
|
}
|
|
66
|
+
function headersOf(message) {
|
|
67
|
+
const props = message.applicationProperties;
|
|
68
|
+
const out = {};
|
|
69
|
+
if (!props) return out;
|
|
70
|
+
for (const key of Object.keys(props)) {
|
|
71
|
+
const value = props[key];
|
|
72
|
+
if (value == null) continue;
|
|
73
|
+
const s = String(value);
|
|
74
|
+
if (s !== "") out[key] = s;
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
50
78
|
var AsbPublisher = class {
|
|
51
79
|
constructor(sender) {
|
|
52
80
|
this.sender = sender;
|
|
@@ -62,7 +90,7 @@ var AsbPublisher = class {
|
|
|
62
90
|
queue: this.sender.entityPath,
|
|
63
91
|
traceId: options.traceId
|
|
64
92
|
});
|
|
65
|
-
const message = toServiceBusMessage(envelope);
|
|
93
|
+
const message = toServiceBusMessage(envelope, options.headers);
|
|
66
94
|
if (options.delayMs != null && options.delayMs > 0) {
|
|
67
95
|
message.applicationProperties = { ...message.applicationProperties, "bq-delay": options.delayMs };
|
|
68
96
|
await this.sender.scheduleMessages(message, new Date(Date.now() + options.delayMs));
|
|
@@ -129,7 +157,7 @@ var AsbConsumer = class {
|
|
|
129
157
|
return;
|
|
130
158
|
}
|
|
131
159
|
try {
|
|
132
|
-
await handler(envelope, message);
|
|
160
|
+
await handler(envelope, message, headersOf(message));
|
|
133
161
|
await this.receiver.completeMessage(message);
|
|
134
162
|
} catch (error) {
|
|
135
163
|
this.options.onError?.(error, envelope, message);
|
|
@@ -141,6 +169,7 @@ var AsbConsumer = class {
|
|
|
141
169
|
0 && (module.exports = {
|
|
142
170
|
AsbConsumer,
|
|
143
171
|
AsbPublisher,
|
|
172
|
+
headersOf,
|
|
144
173
|
toServiceBusMessage
|
|
145
174
|
});
|
|
146
175
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Azure Service Bus adapter for BabelQueue.\n *\n * A canonical-envelope **publisher** and a URN-routed **consumer** over Azure Service\n * Bus, so an ASB-based Node service speaks the same contract (envelope shape, URN\n * identity, trace propagation) as the .NET, Java, Python and Go SDKs.\n *\n * import { ServiceBusClient } from \"@azure/service-bus\";\n * import { AsbPublisher, AsbConsumer } from \"@babelqueue/azure-service-bus\";\n *\n * const client = new ServiceBusClient(connectionString);\n * await new AsbPublisher(client.createSender(\"orders\"))\n * .publish(\"urn:babel:orders:created\", { order_id: 1042 });\n *\n * const consumer = new AsbConsumer(client.createReceiver(\"orders\"), {\n * \"urn:babel:orders:created\": async (env) => { ... },\n * });\n * await consumer.run();\n *\n * This implements §4 of the broker-bindings contract: the canonical envelope is the\n * message body, projected onto native Service Bus fields (`subject` = URN,\n * `correlationId` = trace_id, `messageId` = meta.id, plus the `bq-` application\n * properties). The envelope is unchanged (`schema_version` stays 1); ASB is purely\n * additive. Retry is broker-native — a failed handler `abandon`s the message, so it is\n * redelivered and `deliveryCount` is incremented; the authoritative attempt count is the\n * native `deliveryCount`, surfaced to handlers as `attempts = deliveryCount − 1`.\n */\n\nimport { BabelQueueError, EnvelopeCodec, UnknownUrnError } from \"@babelqueue/core\";\nimport type { Envelope, IncomingEnvelope } from \"@babelqueue/core\";\n\n// --- Minimal Service Bus shapes (a structural subset of @azure/service-bus) -----\n\n/** A message to send (structural subset of @azure/service-bus `ServiceBusMessage`). */\nexport interface AsbMessage {\n body: unknown;\n subject?: string;\n correlationId?: string;\n messageId?: string;\n contentType?: string;\n applicationProperties?: { [key: string]: number | boolean | string | Date | null };\n scheduledEnqueueTimeUtc?: Date;\n}\n\n/** A received message (structural subset of @azure/service-bus `ServiceBusReceivedMessage`). */\nexport interface AsbReceivedMessage {\n body: unknown;\n subject?: string;\n correlationId?: string;\n messageId?: string;\n deliveryCount?: number;\n applicationProperties?: { [key: string]: unknown };\n}\n\n/**\n * The subset of the Service Bus sender this adapter calls. A `ServiceBusSender` from\n * `@azure/service-bus` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface AsbSender {\n entityPath: string;\n sendMessages(message: AsbMessage): Promise<void>;\n scheduleMessages(message: AsbMessage, scheduledEnqueueTimeUtc: Date): Promise<bigint[]>;\n}\n\n/**\n * The subset of the Service Bus receiver this adapter calls. A `ServiceBusReceiver`\n * from `@azure/service-bus` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface AsbReceiver {\n receiveMessages(maxMessageCount: number, options?: { maxWaitTimeInMs?: number }): Promise<AsbReceivedMessage[]>;\n completeMessage(message: AsbReceivedMessage): Promise<void>;\n abandonMessage(message: AsbReceivedMessage): Promise<void>;\n}\n\n// --- Native projection (contract §4.2–§4.3) ------------------------------------\n\n/**\n * Project the envelope's contract fields onto a native Service Bus message — `subject`\n * = URN, `correlationId` = trace_id, `messageId` = meta.id, plus the `bq-` application\n * properties. The body stays authoritative.\n */\nexport function toServiceBusMessage(envelope: Envelope): AsbMessage {\n const applicationProperties: { [key: string]: number | boolean | string } = {};\n if (envelope.meta.schema_version != null) {\n applicationProperties[\"bq-schema-version\"] = envelope.meta.schema_version;\n }\n if (envelope.meta.lang) applicationProperties[\"bq-source-lang\"] = envelope.meta.lang;\n if (envelope.meta.created_at != null) {\n applicationProperties[\"bq-created-at\"] = envelope.meta.created_at;\n }\n\n const message: AsbMessage = {\n body: EnvelopeCodec.encode(envelope),\n contentType: \"application/json\",\n };\n if (envelope.job) message.subject = envelope.job;\n if (envelope.trace_id) message.correlationId = envelope.trace_id;\n if (envelope.meta.id) message.messageId = envelope.meta.id;\n if (Object.keys(applicationProperties).length > 0) {\n message.applicationProperties = applicationProperties;\n }\n return message;\n}\n\n// --- Publisher -----------------------------------------------------------------\n\n/** Options for {@link AsbPublisher.publish}. */\nexport interface PublishOptions {\n /** Reuse an existing trace id (trace continuation). */\n traceId?: string;\n /** Schedule native delayed delivery this many milliseconds from now (`scheduledEnqueueTimeUtc`). */\n delayMs?: number;\n}\n\n/** Sends canonical-envelope messages to one Service Bus entity with the §4 native projection. */\nexport class AsbPublisher {\n constructor(private readonly sender: AsbSender) {}\n\n /**\n * Build the canonical envelope for `(urn, data)`, send it with the native projection,\n * and return the message id (`meta.id`). A positive `delayMs` schedules native delayed\n * delivery.\n */\n async publish(\n urn: string,\n data: Record<string, unknown>,\n options: PublishOptions = {},\n ): Promise<string> {\n const envelope = EnvelopeCodec.make(urn, data, {\n queue: this.sender.entityPath,\n traceId: options.traceId,\n });\n const message = toServiceBusMessage(envelope);\n\n if (options.delayMs != null && options.delayMs > 0) {\n message.applicationProperties = { ...message.applicationProperties, \"bq-delay\": options.delayMs };\n await this.sender.scheduleMessages(message, new Date(Date.now() + options.delayMs));\n } else {\n await this.sender.sendMessages(message);\n }\n return envelope.meta.id;\n }\n}\n\n// --- Consumer ------------------------------------------------------------------\n\n/** A URN handler. Receives the validated envelope and the raw Service Bus message. */\nexport type BabelHandler = (envelope: Envelope, message: AsbReceivedMessage) => unknown | Promise<unknown>;\n\n/** A map of URN → handler. */\nexport type BabelHandlers = Record<string, BabelHandler>;\n\n/** Options for {@link AsbConsumer}. */\nexport interface AsbConsumerOptions {\n /** Called instead of erroring when a message's URN has no handler (then the message is completed). */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: AsbReceivedMessage) => unknown | Promise<unknown>;\n /** Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), or a throwing handler. The loop never stops. */\n onError?: (error: unknown, envelope: IncomingEnvelope, message: AsbReceivedMessage) => void;\n /** Max messages per receive (default 10). */\n maxMessages?: number;\n /** Max time to wait for a batch, in ms. */\n maxWaitTimeInMs?: number;\n}\n\n/**\n * Receives from a Service Bus entity (PeekLock), decodes + validates each message, routes\n * it to the handler for its URN, and completes it on success. A throwing handler abandons\n * the message — the broker redelivers it and increments `deliveryCount` (at-least-once);\n * `attempts` is reconciled to `deliveryCount − 1` for the handler.\n */\nexport class AsbConsumer {\n constructor(\n private readonly receiver: AsbReceiver,\n private readonly handlers: BabelHandlers,\n private readonly options: AsbConsumerOptions = {},\n ) {}\n\n /** Receive one batch, route each message, settle each. Returns the batch size. */\n async poll(): Promise<number> {\n const messages = await this.receiver.receiveMessages(\n this.options.maxMessages ?? 10,\n this.options.maxWaitTimeInMs != null ? { maxWaitTimeInMs: this.options.maxWaitTimeInMs } : undefined,\n );\n for (const message of messages) {\n await this.handle(message);\n }\n return messages.length;\n }\n\n /** Poll until `signal` aborts. */\n async run(signal?: AbortSignal): Promise<void> {\n while (signal?.aborted !== true) {\n await this.poll();\n }\n }\n\n private async handle(message: AsbReceivedMessage): Promise<void> {\n const raw = typeof message.body === \"string\" ? message.body : String(message.body ?? \"\");\n const envelope = EnvelopeCodec.decode(raw);\n\n // attempts = max(current, deliveryCount − 1): deliveryCount (1-based) is the native\n // redelivery floor; the max never lowers a higher body count republished from another SDK.\n const deliveryCount = typeof message.deliveryCount === \"number\" ? message.deliveryCount : 0;\n const native = deliveryCount - 1;\n const current = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n if (native > current) {\n envelope.attempts = native;\n }\n\n if (!EnvelopeCodec.accepts(envelope)) {\n this.options.onError?.(\n new BabelQueueError(\"Rejected a non-conformant BabelQueue envelope from Azure Service Bus.\"),\n envelope,\n message,\n );\n await this.receiver.abandonMessage(message);\n return;\n }\n\n const urn = EnvelopeCodec.urn(envelope);\n const handler = this.handlers[urn];\n if (!handler) {\n if (this.options.onUnknownUrn) {\n await this.options.onUnknownUrn(envelope, message);\n await this.receiver.completeMessage(message);\n } else {\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n await this.receiver.abandonMessage(message);\n }\n return;\n }\n\n try {\n await handler(envelope, message);\n await this.receiver.completeMessage(message);\n } catch (error) {\n // Abandon releases the lock — the broker redelivers and increments deliveryCount.\n this.options.onError?.(error, envelope, message);\n await this.receiver.abandonMessage(message);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4BA,kBAAgE;AAqDzD,SAAS,oBAAoB,UAAgC;AAClE,QAAM,wBAAsE,CAAC;AAC7E,MAAI,SAAS,KAAK,kBAAkB,MAAM;AACxC,0BAAsB,mBAAmB,IAAI,SAAS,KAAK;AAAA,EAC7D;AACA,MAAI,SAAS,KAAK,KAAM,uBAAsB,gBAAgB,IAAI,SAAS,KAAK;AAChF,MAAI,SAAS,KAAK,cAAc,MAAM;AACpC,0BAAsB,eAAe,IAAI,SAAS,KAAK;AAAA,EACzD;AAEA,QAAM,UAAsB;AAAA,IAC1B,MAAM,0BAAc,OAAO,QAAQ;AAAA,IACnC,aAAa;AAAA,EACf;AACA,MAAI,SAAS,I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C,YAAM,KAAK,SAAS,eAAe,OAAO;AAAA,IAC5C;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/headers.ts"],"sourcesContent":["/**\n * Azure Service Bus adapter for BabelQueue.\n *\n * A canonical-envelope **publisher** and a URN-routed **consumer** over Azure Service\n * Bus, so an ASB-based Node service speaks the same contract (envelope shape, URN\n * identity, trace propagation) as the .NET, Java, Python and Go SDKs.\n *\n * import { ServiceBusClient } from \"@azure/service-bus\";\n * import { AsbPublisher, AsbConsumer } from \"@babelqueue/azure-service-bus\";\n *\n * const client = new ServiceBusClient(connectionString);\n * await new AsbPublisher(client.createSender(\"orders\"))\n * .publish(\"urn:babel:orders:created\", { order_id: 1042 });\n *\n * const consumer = new AsbConsumer(client.createReceiver(\"orders\"), {\n * \"urn:babel:orders:created\": async (env) => { ... },\n * });\n * await consumer.run();\n *\n * This implements §4 of the broker-bindings contract: the canonical envelope is the\n * message body, projected onto native Service Bus fields (`subject` = URN,\n * `correlationId` = trace_id, `messageId` = meta.id, plus the `bq-` application\n * properties). The envelope is unchanged (`schema_version` stays 1); ASB is purely\n * additive. Retry is broker-native — a failed handler `abandon`s the message, so it is\n * redelivered and `deliveryCount` is incremented; the authoritative attempt count is the\n * native `deliveryCount`, surfaced to handlers as `attempts = deliveryCount − 1`.\n *\n * **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop\n * span linkage) rides as additional native `applicationProperties` beside the contract `bq-*`\n * properties — the contract properties win a key collision (merge-not-clobber), blanks dropped. On\n * consume the inbound `applicationProperties` are surfaced as a `Record<string,string>` so the\n * core's `otel` extract sees the `traceparent` and links the consumer span as a child. A\n * header-less publish is byte-identical. GR-1: the wire envelope body is never touched.\n */\n\nimport { BabelQueueError, EnvelopeCodec, UnknownUrnError } from \"@babelqueue/core\";\nimport type { Envelope, HeaderCarrier, IncomingEnvelope } from \"@babelqueue/core\";\n\nimport { sanitizeHeaders } from \"./headers.js\";\n\n// --- Minimal Service Bus shapes (a structural subset of @azure/service-bus) -----\n\n/** A message to send (structural subset of @azure/service-bus `ServiceBusMessage`). */\nexport interface AsbMessage {\n body: unknown;\n subject?: string;\n correlationId?: string;\n messageId?: string;\n contentType?: string;\n applicationProperties?: { [key: string]: number | boolean | string | Date | null };\n scheduledEnqueueTimeUtc?: Date;\n}\n\n/** A received message (structural subset of @azure/service-bus `ServiceBusReceivedMessage`). */\nexport interface AsbReceivedMessage {\n body: unknown;\n subject?: string;\n correlationId?: string;\n messageId?: string;\n deliveryCount?: number;\n applicationProperties?: { [key: string]: unknown };\n}\n\n/**\n * The subset of the Service Bus sender this adapter calls. A `ServiceBusSender` from\n * `@azure/service-bus` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface AsbSender {\n entityPath: string;\n sendMessages(message: AsbMessage): Promise<void>;\n scheduleMessages(message: AsbMessage, scheduledEnqueueTimeUtc: Date): Promise<bigint[]>;\n}\n\n/**\n * The subset of the Service Bus receiver this adapter calls. A `ServiceBusReceiver`\n * from `@azure/service-bus` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface AsbReceiver {\n receiveMessages(maxMessageCount: number, options?: { maxWaitTimeInMs?: number }): Promise<AsbReceivedMessage[]>;\n completeMessage(message: AsbReceivedMessage): Promise<void>;\n abandonMessage(message: AsbReceivedMessage): Promise<void>;\n}\n\n// --- Native projection (contract §4.2–§4.3) ------------------------------------\n\n/**\n * Project the envelope's contract fields onto a native Service Bus message — `subject`\n * = URN, `correlationId` = trace_id, `messageId` = meta.id, plus the `bq-` application\n * properties. The body stays authoritative.\n *\n * When `extra` is given, those out-of-band headers (e.g. a W3C `traceparent`, ADR-0028) are merged\n * into `applicationProperties` **first**, then the contract `bq-*` properties are written so they\n * always win a key collision (merge-not-clobber); blank keys/values are dropped. GR-1: the wire\n * envelope body is never touched.\n */\nexport function toServiceBusMessage(envelope: Envelope, extra?: HeaderCarrier | null): AsbMessage {\n const applicationProperties: { [key: string]: number | boolean | string } = {};\n // Out-of-band riders go in first so the contract bq-* properties below win any key collision.\n for (const [key, value] of Object.entries(sanitizeHeaders(extra))) applicationProperties[key] = value;\n if (envelope.meta.schema_version != null) {\n applicationProperties[\"bq-schema-version\"] = envelope.meta.schema_version;\n }\n if (envelope.meta.lang) applicationProperties[\"bq-source-lang\"] = envelope.meta.lang;\n if (envelope.meta.created_at != null) {\n applicationProperties[\"bq-created-at\"] = envelope.meta.created_at;\n }\n\n const message: AsbMessage = {\n body: EnvelopeCodec.encode(envelope),\n contentType: \"application/json\",\n };\n if (envelope.job) message.subject = envelope.job;\n if (envelope.trace_id) message.correlationId = envelope.trace_id;\n if (envelope.meta.id) message.messageId = envelope.meta.id;\n if (Object.keys(applicationProperties).length > 0) {\n message.applicationProperties = applicationProperties;\n }\n return message;\n}\n\n/**\n * Read a received message's `applicationProperties` back into a flat {@link HeaderCarrier},\n * stringifying values defensively. Returns an empty object when there are none. Both the contract\n * `bq-*` properties and any out-of-band rider (e.g. `traceparent`) surface — the core's `otel`\n * extract reads only the keys it knows.\n */\nexport function headersOf(message: AsbReceivedMessage): HeaderCarrier {\n const props = message.applicationProperties;\n const out: HeaderCarrier = {};\n if (!props) return out;\n for (const key of Object.keys(props)) {\n const value = props[key];\n if (value == null) continue;\n const s = String(value);\n if (s !== \"\") out[key] = s;\n }\n return out;\n}\n\n// --- Publisher -----------------------------------------------------------------\n\n/** Options for {@link AsbPublisher.publish}. */\nexport interface PublishOptions {\n /** Reuse an existing trace id (trace continuation). */\n traceId?: string;\n /** Schedule native delayed delivery this many milliseconds from now (`scheduledEnqueueTimeUtc`). */\n delayMs?: number;\n /**\n * Out-of-band transport headers carried as native `applicationProperties` beside the contract\n * `bq-*` properties (ADR-0028) — e.g. a W3C `traceparent` written by `@babelqueue/core/otel`'s\n * `publish`. The contract properties win a key collision; an empty/omitted carrier leaves the\n * message unchanged.\n */\n headers?: HeaderCarrier;\n}\n\n/** Sends canonical-envelope messages to one Service Bus entity with the §4 native projection. */\nexport class AsbPublisher {\n constructor(private readonly sender: AsbSender) {}\n\n /**\n * Build the canonical envelope for `(urn, data)`, send it with the native projection,\n * and return the message id (`meta.id`). A positive `delayMs` schedules native delayed\n * delivery.\n */\n async publish(\n urn: string,\n data: Record<string, unknown>,\n options: PublishOptions = {},\n ): Promise<string> {\n const envelope = EnvelopeCodec.make(urn, data, {\n queue: this.sender.entityPath,\n traceId: options.traceId,\n });\n const message = toServiceBusMessage(envelope, options.headers);\n\n if (options.delayMs != null && options.delayMs > 0) {\n message.applicationProperties = { ...message.applicationProperties, \"bq-delay\": options.delayMs };\n await this.sender.scheduleMessages(message, new Date(Date.now() + options.delayMs));\n } else {\n await this.sender.sendMessages(message);\n }\n return envelope.meta.id;\n }\n}\n\n// --- Consumer ------------------------------------------------------------------\n\n/**\n * A URN handler. Receives the validated envelope, the raw Service Bus message, and the out-of-band\n * {@link HeaderCarrier} read from the message's `applicationProperties` (empty when there are none).\n * Pass `headers` to `@babelqueue/core/otel`'s `wrapHandler` to link the consumer span as a child of\n * the producer span (ADR-0028).\n */\nexport type BabelHandler = (envelope: Envelope, message: AsbReceivedMessage, headers: HeaderCarrier) => unknown | Promise<unknown>;\n\n/** A map of URN → handler. */\nexport type BabelHandlers = Record<string, BabelHandler>;\n\n/** Options for {@link AsbConsumer}. */\nexport interface AsbConsumerOptions {\n /** Called instead of erroring when a message's URN has no handler (then the message is completed). */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: AsbReceivedMessage) => unknown | Promise<unknown>;\n /** Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), or a throwing handler. The loop never stops. */\n onError?: (error: unknown, envelope: IncomingEnvelope, message: AsbReceivedMessage) => void;\n /** Max messages per receive (default 10). */\n maxMessages?: number;\n /** Max time to wait for a batch, in ms. */\n maxWaitTimeInMs?: number;\n}\n\n/**\n * Receives from a Service Bus entity (PeekLock), decodes + validates each message, routes\n * it to the handler for its URN, and completes it on success. A throwing handler abandons\n * the message — the broker redelivers it and increments `deliveryCount` (at-least-once);\n * `attempts` is reconciled to `deliveryCount − 1` for the handler.\n */\nexport class AsbConsumer {\n constructor(\n private readonly receiver: AsbReceiver,\n private readonly handlers: BabelHandlers,\n private readonly options: AsbConsumerOptions = {},\n ) {}\n\n /** Receive one batch, route each message, settle each. Returns the batch size. */\n async poll(): Promise<number> {\n const messages = await this.receiver.receiveMessages(\n this.options.maxMessages ?? 10,\n this.options.maxWaitTimeInMs != null ? { maxWaitTimeInMs: this.options.maxWaitTimeInMs } : undefined,\n );\n for (const message of messages) {\n await this.handle(message);\n }\n return messages.length;\n }\n\n /** Poll until `signal` aborts. */\n async run(signal?: AbortSignal): Promise<void> {\n while (signal?.aborted !== true) {\n await this.poll();\n }\n }\n\n private async handle(message: AsbReceivedMessage): Promise<void> {\n const raw = typeof message.body === \"string\" ? message.body : String(message.body ?? \"\");\n const envelope = EnvelopeCodec.decode(raw);\n\n // attempts = max(current, deliveryCount − 1): deliveryCount (1-based) is the native\n // redelivery floor; the max never lowers a higher body count republished from another SDK.\n const deliveryCount = typeof message.deliveryCount === \"number\" ? message.deliveryCount : 0;\n const native = deliveryCount - 1;\n const current = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n if (native > current) {\n envelope.attempts = native;\n }\n\n if (!EnvelopeCodec.accepts(envelope)) {\n this.options.onError?.(\n new BabelQueueError(\"Rejected a non-conformant BabelQueue envelope from Azure Service Bus.\"),\n envelope,\n message,\n );\n await this.receiver.abandonMessage(message);\n return;\n }\n\n const urn = EnvelopeCodec.urn(envelope);\n const handler = this.handlers[urn];\n if (!handler) {\n if (this.options.onUnknownUrn) {\n await this.options.onUnknownUrn(envelope, message);\n await this.receiver.completeMessage(message);\n } else {\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n await this.receiver.abandonMessage(message);\n }\n return;\n }\n\n try {\n await handler(envelope, message, headersOf(message));\n await this.receiver.completeMessage(message);\n } catch (error) {\n // Abandon releases the lock — the broker redelivers and increments deliveryCount.\n this.options.onError?.(error, envelope, message);\n await this.receiver.abandonMessage(message);\n }\n }\n}\n","/**\n * Pure, dependency-free helpers for the out-of-band transport-header seam (ADR-0028) — the Node\n * adapter mirror of Go's `sanitizeHeaders` and PHP's `Support\\Headers`. They fold an injected\n * {@link HeaderCarrier} (e.g. a W3C `traceparent`) onto a transport's metadata channel **without\n * clobbering** the contract headers it already carries.\n *\n * Headers ride beside the frozen wire envelope (GR-1), never inside it.\n */\n\nimport type { HeaderCarrier } from \"@babelqueue/core\";\n\n/**\n * Copy `headers`, dropping blank keys and blank values. Returns an empty object when nothing\n * survives. A nullish input yields an empty object.\n */\nexport function sanitizeHeaders(headers: HeaderCarrier | null | undefined): HeaderCarrier {\n const out: HeaderCarrier = {};\n if (!headers) return out;\n for (const key of Object.keys(headers)) {\n const value = headers[key];\n if (key === \"\" || value == null || value === \"\") continue;\n out[key] = value;\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmCA,kBAAgE;;;ACpBzD,SAAS,gBAAgB,SAA0D;AACxF,QAAM,MAAqB,CAAC;AAC5B,MAAI,CAAC,QAAS,QAAO;AACrB,aAAW,OAAO,OAAO,KAAK,OAAO,GAAG;AACtC,UAAM,QAAQ,QAAQ,GAAG;AACzB,QAAI,QAAQ,MAAM,SAAS,QAAQ,UAAU,GAAI;AACjD,QAAI,GAAG,IAAI;AAAA,EACb;AACA,SAAO;AACT;;;ADuEO,SAAS,oBAAoB,UAAoB,OAA0C;AAChG,QAAM,wBAAsE,CAAC;AAE7E,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,gBAAgB,KAAK,CAAC,EAAG,uBAAsB,GAAG,IAAI;AAChG,MAAI,SAAS,KAAK,kBAAkB,MAAM;AACxC,0BAAsB,mBAAmB,IAAI,SAAS,KAAK;AAAA,EAC7D;AACA,MAAI,SAAS,KAAK,KAAM,uBAAsB,gBAAgB,IAAI,SAAS,KAAK;AAChF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AAM,MAAM,0BAAc,IAAI,QAAQ;AACtC,UAAM,UAAU,KAAK,SAAS,GAAG;AACjC,QAAI,CAAC,SAAS;AACZ,UAAI,KAAK,QAAQ,cAAc;AAC7B,cAAM,KAAK,QAAQ,aAAa,UAAU,OAAO;AACjD,cAAM,KAAK,SAAS,gBAAgB,OAAO;AAAA,MAC7C,OAAO;AACL,aAAK,QAAQ,UAAU,IAAI,4BAAgB,GAAG,GAAG,UAAU,OAAO;AAClE,cAAM,KAAK,SAAS,eAAe,OAAO;AAAA,MAC5C;AACA;AAAA,IACF;AAEA,QAAI;AACF,YAAM,QAAQ,UAAU,SAAS,UAAU,OAAO,CAAC;AACnD,YAAM,KAAK,SAAS,gBAAgB,OAAO;AAAA,IAC7C,SAAS,OAAO;AAEd,WAAK,QAAQ,UAAU,OAAO,UAAU,OAAO;AAC/C,YAAM,KAAK,SAAS,eAAe,OAAO;AAAA,IAC5C;AAAA,EACF;AACF;","names":[]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Envelope, IncomingEnvelope } from '@babelqueue/core';
|
|
1
|
+
import { Envelope, HeaderCarrier, IncomingEnvelope } from '@babelqueue/core';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Azure Service Bus adapter for BabelQueue.
|
|
@@ -26,6 +26,13 @@ import { Envelope, IncomingEnvelope } from '@babelqueue/core';
|
|
|
26
26
|
* additive. Retry is broker-native — a failed handler `abandon`s the message, so it is
|
|
27
27
|
* redelivered and `deliveryCount` is incremented; the authoritative attempt count is the
|
|
28
28
|
* native `deliveryCount`, surfaced to handlers as `attempts = deliveryCount − 1`.
|
|
29
|
+
*
|
|
30
|
+
* **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop
|
|
31
|
+
* span linkage) rides as additional native `applicationProperties` beside the contract `bq-*`
|
|
32
|
+
* properties — the contract properties win a key collision (merge-not-clobber), blanks dropped. On
|
|
33
|
+
* consume the inbound `applicationProperties` are surfaced as a `Record<string,string>` so the
|
|
34
|
+
* core's `otel` extract sees the `traceparent` and links the consumer span as a child. A
|
|
35
|
+
* header-less publish is byte-identical. GR-1: the wire envelope body is never touched.
|
|
29
36
|
*/
|
|
30
37
|
|
|
31
38
|
/** A message to send (structural subset of @azure/service-bus `ServiceBusMessage`). */
|
|
@@ -75,14 +82,33 @@ interface AsbReceiver {
|
|
|
75
82
|
* Project the envelope's contract fields onto a native Service Bus message — `subject`
|
|
76
83
|
* = URN, `correlationId` = trace_id, `messageId` = meta.id, plus the `bq-` application
|
|
77
84
|
* properties. The body stays authoritative.
|
|
85
|
+
*
|
|
86
|
+
* When `extra` is given, those out-of-band headers (e.g. a W3C `traceparent`, ADR-0028) are merged
|
|
87
|
+
* into `applicationProperties` **first**, then the contract `bq-*` properties are written so they
|
|
88
|
+
* always win a key collision (merge-not-clobber); blank keys/values are dropped. GR-1: the wire
|
|
89
|
+
* envelope body is never touched.
|
|
90
|
+
*/
|
|
91
|
+
declare function toServiceBusMessage(envelope: Envelope, extra?: HeaderCarrier | null): AsbMessage;
|
|
92
|
+
/**
|
|
93
|
+
* Read a received message's `applicationProperties` back into a flat {@link HeaderCarrier},
|
|
94
|
+
* stringifying values defensively. Returns an empty object when there are none. Both the contract
|
|
95
|
+
* `bq-*` properties and any out-of-band rider (e.g. `traceparent`) surface — the core's `otel`
|
|
96
|
+
* extract reads only the keys it knows.
|
|
78
97
|
*/
|
|
79
|
-
declare function
|
|
98
|
+
declare function headersOf(message: AsbReceivedMessage): HeaderCarrier;
|
|
80
99
|
/** Options for {@link AsbPublisher.publish}. */
|
|
81
100
|
interface PublishOptions {
|
|
82
101
|
/** Reuse an existing trace id (trace continuation). */
|
|
83
102
|
traceId?: string;
|
|
84
103
|
/** Schedule native delayed delivery this many milliseconds from now (`scheduledEnqueueTimeUtc`). */
|
|
85
104
|
delayMs?: number;
|
|
105
|
+
/**
|
|
106
|
+
* Out-of-band transport headers carried as native `applicationProperties` beside the contract
|
|
107
|
+
* `bq-*` properties (ADR-0028) — e.g. a W3C `traceparent` written by `@babelqueue/core/otel`'s
|
|
108
|
+
* `publish`. The contract properties win a key collision; an empty/omitted carrier leaves the
|
|
109
|
+
* message unchanged.
|
|
110
|
+
*/
|
|
111
|
+
headers?: HeaderCarrier;
|
|
86
112
|
}
|
|
87
113
|
/** Sends canonical-envelope messages to one Service Bus entity with the §4 native projection. */
|
|
88
114
|
declare class AsbPublisher {
|
|
@@ -95,8 +121,13 @@ declare class AsbPublisher {
|
|
|
95
121
|
*/
|
|
96
122
|
publish(urn: string, data: Record<string, unknown>, options?: PublishOptions): Promise<string>;
|
|
97
123
|
}
|
|
98
|
-
/**
|
|
99
|
-
|
|
124
|
+
/**
|
|
125
|
+
* A URN handler. Receives the validated envelope, the raw Service Bus message, and the out-of-band
|
|
126
|
+
* {@link HeaderCarrier} read from the message's `applicationProperties` (empty when there are none).
|
|
127
|
+
* Pass `headers` to `@babelqueue/core/otel`'s `wrapHandler` to link the consumer span as a child of
|
|
128
|
+
* the producer span (ADR-0028).
|
|
129
|
+
*/
|
|
130
|
+
type BabelHandler = (envelope: Envelope, message: AsbReceivedMessage, headers: HeaderCarrier) => unknown | Promise<unknown>;
|
|
100
131
|
/** A map of URN → handler. */
|
|
101
132
|
type BabelHandlers = Record<string, BabelHandler>;
|
|
102
133
|
/** Options for {@link AsbConsumer}. */
|
|
@@ -128,4 +159,4 @@ declare class AsbConsumer {
|
|
|
128
159
|
private handle;
|
|
129
160
|
}
|
|
130
161
|
|
|
131
|
-
export { AsbConsumer, type AsbConsumerOptions, type AsbMessage, AsbPublisher, type AsbReceivedMessage, type AsbReceiver, type AsbSender, type BabelHandler, type BabelHandlers, type PublishOptions, toServiceBusMessage };
|
|
162
|
+
export { AsbConsumer, type AsbConsumerOptions, type AsbMessage, AsbPublisher, type AsbReceivedMessage, type AsbReceiver, type AsbSender, type BabelHandler, type BabelHandlers, type PublishOptions, headersOf, toServiceBusMessage };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Envelope, IncomingEnvelope } from '@babelqueue/core';
|
|
1
|
+
import { Envelope, HeaderCarrier, IncomingEnvelope } from '@babelqueue/core';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Azure Service Bus adapter for BabelQueue.
|
|
@@ -26,6 +26,13 @@ import { Envelope, IncomingEnvelope } from '@babelqueue/core';
|
|
|
26
26
|
* additive. Retry is broker-native — a failed handler `abandon`s the message, so it is
|
|
27
27
|
* redelivered and `deliveryCount` is incremented; the authoritative attempt count is the
|
|
28
28
|
* native `deliveryCount`, surfaced to handlers as `attempts = deliveryCount − 1`.
|
|
29
|
+
*
|
|
30
|
+
* **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop
|
|
31
|
+
* span linkage) rides as additional native `applicationProperties` beside the contract `bq-*`
|
|
32
|
+
* properties — the contract properties win a key collision (merge-not-clobber), blanks dropped. On
|
|
33
|
+
* consume the inbound `applicationProperties` are surfaced as a `Record<string,string>` so the
|
|
34
|
+
* core's `otel` extract sees the `traceparent` and links the consumer span as a child. A
|
|
35
|
+
* header-less publish is byte-identical. GR-1: the wire envelope body is never touched.
|
|
29
36
|
*/
|
|
30
37
|
|
|
31
38
|
/** A message to send (structural subset of @azure/service-bus `ServiceBusMessage`). */
|
|
@@ -75,14 +82,33 @@ interface AsbReceiver {
|
|
|
75
82
|
* Project the envelope's contract fields onto a native Service Bus message — `subject`
|
|
76
83
|
* = URN, `correlationId` = trace_id, `messageId` = meta.id, plus the `bq-` application
|
|
77
84
|
* properties. The body stays authoritative.
|
|
85
|
+
*
|
|
86
|
+
* When `extra` is given, those out-of-band headers (e.g. a W3C `traceparent`, ADR-0028) are merged
|
|
87
|
+
* into `applicationProperties` **first**, then the contract `bq-*` properties are written so they
|
|
88
|
+
* always win a key collision (merge-not-clobber); blank keys/values are dropped. GR-1: the wire
|
|
89
|
+
* envelope body is never touched.
|
|
90
|
+
*/
|
|
91
|
+
declare function toServiceBusMessage(envelope: Envelope, extra?: HeaderCarrier | null): AsbMessage;
|
|
92
|
+
/**
|
|
93
|
+
* Read a received message's `applicationProperties` back into a flat {@link HeaderCarrier},
|
|
94
|
+
* stringifying values defensively. Returns an empty object when there are none. Both the contract
|
|
95
|
+
* `bq-*` properties and any out-of-band rider (e.g. `traceparent`) surface — the core's `otel`
|
|
96
|
+
* extract reads only the keys it knows.
|
|
78
97
|
*/
|
|
79
|
-
declare function
|
|
98
|
+
declare function headersOf(message: AsbReceivedMessage): HeaderCarrier;
|
|
80
99
|
/** Options for {@link AsbPublisher.publish}. */
|
|
81
100
|
interface PublishOptions {
|
|
82
101
|
/** Reuse an existing trace id (trace continuation). */
|
|
83
102
|
traceId?: string;
|
|
84
103
|
/** Schedule native delayed delivery this many milliseconds from now (`scheduledEnqueueTimeUtc`). */
|
|
85
104
|
delayMs?: number;
|
|
105
|
+
/**
|
|
106
|
+
* Out-of-band transport headers carried as native `applicationProperties` beside the contract
|
|
107
|
+
* `bq-*` properties (ADR-0028) — e.g. a W3C `traceparent` written by `@babelqueue/core/otel`'s
|
|
108
|
+
* `publish`. The contract properties win a key collision; an empty/omitted carrier leaves the
|
|
109
|
+
* message unchanged.
|
|
110
|
+
*/
|
|
111
|
+
headers?: HeaderCarrier;
|
|
86
112
|
}
|
|
87
113
|
/** Sends canonical-envelope messages to one Service Bus entity with the §4 native projection. */
|
|
88
114
|
declare class AsbPublisher {
|
|
@@ -95,8 +121,13 @@ declare class AsbPublisher {
|
|
|
95
121
|
*/
|
|
96
122
|
publish(urn: string, data: Record<string, unknown>, options?: PublishOptions): Promise<string>;
|
|
97
123
|
}
|
|
98
|
-
/**
|
|
99
|
-
|
|
124
|
+
/**
|
|
125
|
+
* A URN handler. Receives the validated envelope, the raw Service Bus message, and the out-of-band
|
|
126
|
+
* {@link HeaderCarrier} read from the message's `applicationProperties` (empty when there are none).
|
|
127
|
+
* Pass `headers` to `@babelqueue/core/otel`'s `wrapHandler` to link the consumer span as a child of
|
|
128
|
+
* the producer span (ADR-0028).
|
|
129
|
+
*/
|
|
130
|
+
type BabelHandler = (envelope: Envelope, message: AsbReceivedMessage, headers: HeaderCarrier) => unknown | Promise<unknown>;
|
|
100
131
|
/** A map of URN → handler. */
|
|
101
132
|
type BabelHandlers = Record<string, BabelHandler>;
|
|
102
133
|
/** Options for {@link AsbConsumer}. */
|
|
@@ -128,4 +159,4 @@ declare class AsbConsumer {
|
|
|
128
159
|
private handle;
|
|
129
160
|
}
|
|
130
161
|
|
|
131
|
-
export { AsbConsumer, type AsbConsumerOptions, type AsbMessage, AsbPublisher, type AsbReceivedMessage, type AsbReceiver, type AsbSender, type BabelHandler, type BabelHandlers, type PublishOptions, toServiceBusMessage };
|
|
162
|
+
export { AsbConsumer, type AsbConsumerOptions, type AsbMessage, AsbPublisher, type AsbReceivedMessage, type AsbReceiver, type AsbSender, type BabelHandler, type BabelHandlers, type PublishOptions, headersOf, toServiceBusMessage };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,22 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
2
|
import { BabelQueueError, EnvelopeCodec, UnknownUrnError } from "@babelqueue/core";
|
|
3
|
-
|
|
3
|
+
|
|
4
|
+
// src/headers.ts
|
|
5
|
+
function sanitizeHeaders(headers) {
|
|
6
|
+
const out = {};
|
|
7
|
+
if (!headers) return out;
|
|
8
|
+
for (const key of Object.keys(headers)) {
|
|
9
|
+
const value = headers[key];
|
|
10
|
+
if (key === "" || value == null || value === "") continue;
|
|
11
|
+
out[key] = value;
|
|
12
|
+
}
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// src/index.ts
|
|
17
|
+
function toServiceBusMessage(envelope, extra) {
|
|
4
18
|
const applicationProperties = {};
|
|
19
|
+
for (const [key, value] of Object.entries(sanitizeHeaders(extra))) applicationProperties[key] = value;
|
|
5
20
|
if (envelope.meta.schema_version != null) {
|
|
6
21
|
applicationProperties["bq-schema-version"] = envelope.meta.schema_version;
|
|
7
22
|
}
|
|
@@ -21,6 +36,18 @@ function toServiceBusMessage(envelope) {
|
|
|
21
36
|
}
|
|
22
37
|
return message;
|
|
23
38
|
}
|
|
39
|
+
function headersOf(message) {
|
|
40
|
+
const props = message.applicationProperties;
|
|
41
|
+
const out = {};
|
|
42
|
+
if (!props) return out;
|
|
43
|
+
for (const key of Object.keys(props)) {
|
|
44
|
+
const value = props[key];
|
|
45
|
+
if (value == null) continue;
|
|
46
|
+
const s = String(value);
|
|
47
|
+
if (s !== "") out[key] = s;
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
24
51
|
var AsbPublisher = class {
|
|
25
52
|
constructor(sender) {
|
|
26
53
|
this.sender = sender;
|
|
@@ -36,7 +63,7 @@ var AsbPublisher = class {
|
|
|
36
63
|
queue: this.sender.entityPath,
|
|
37
64
|
traceId: options.traceId
|
|
38
65
|
});
|
|
39
|
-
const message = toServiceBusMessage(envelope);
|
|
66
|
+
const message = toServiceBusMessage(envelope, options.headers);
|
|
40
67
|
if (options.delayMs != null && options.delayMs > 0) {
|
|
41
68
|
message.applicationProperties = { ...message.applicationProperties, "bq-delay": options.delayMs };
|
|
42
69
|
await this.sender.scheduleMessages(message, new Date(Date.now() + options.delayMs));
|
|
@@ -103,7 +130,7 @@ var AsbConsumer = class {
|
|
|
103
130
|
return;
|
|
104
131
|
}
|
|
105
132
|
try {
|
|
106
|
-
await handler(envelope, message);
|
|
133
|
+
await handler(envelope, message, headersOf(message));
|
|
107
134
|
await this.receiver.completeMessage(message);
|
|
108
135
|
} catch (error) {
|
|
109
136
|
this.options.onError?.(error, envelope, message);
|
|
@@ -114,6 +141,7 @@ var AsbConsumer = class {
|
|
|
114
141
|
export {
|
|
115
142
|
AsbConsumer,
|
|
116
143
|
AsbPublisher,
|
|
144
|
+
headersOf,
|
|
117
145
|
toServiceBusMessage
|
|
118
146
|
};
|
|
119
147
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Azure Service Bus adapter for BabelQueue.\n *\n * A canonical-envelope **publisher** and a URN-routed **consumer** over Azure Service\n * Bus, so an ASB-based Node service speaks the same contract (envelope shape, URN\n * identity, trace propagation) as the .NET, Java, Python and Go SDKs.\n *\n * import { ServiceBusClient } from \"@azure/service-bus\";\n * import { AsbPublisher, AsbConsumer } from \"@babelqueue/azure-service-bus\";\n *\n * const client = new ServiceBusClient(connectionString);\n * await new AsbPublisher(client.createSender(\"orders\"))\n * .publish(\"urn:babel:orders:created\", { order_id: 1042 });\n *\n * const consumer = new AsbConsumer(client.createReceiver(\"orders\"), {\n * \"urn:babel:orders:created\": async (env) => { ... },\n * });\n * await consumer.run();\n *\n * This implements §4 of the broker-bindings contract: the canonical envelope is the\n * message body, projected onto native Service Bus fields (`subject` = URN,\n * `correlationId` = trace_id, `messageId` = meta.id, plus the `bq-` application\n * properties). The envelope is unchanged (`schema_version` stays 1); ASB is purely\n * additive. Retry is broker-native — a failed handler `abandon`s the message, so it is\n * redelivered and `deliveryCount` is incremented; the authoritative attempt count is the\n * native `deliveryCount`, surfaced to handlers as `attempts = deliveryCount − 1`.\n */\n\nimport { BabelQueueError, EnvelopeCodec, UnknownUrnError } from \"@babelqueue/core\";\nimport type { Envelope, IncomingEnvelope } from \"@babelqueue/core\";\n\n// --- Minimal Service Bus shapes (a structural subset of @azure/service-bus) -----\n\n/** A message to send (structural subset of @azure/service-bus `ServiceBusMessage`). */\nexport interface AsbMessage {\n body: unknown;\n subject?: string;\n correlationId?: string;\n messageId?: string;\n contentType?: string;\n applicationProperties?: { [key: string]: number | boolean | string | Date | null };\n scheduledEnqueueTimeUtc?: Date;\n}\n\n/** A received message (structural subset of @azure/service-bus `ServiceBusReceivedMessage`). */\nexport interface AsbReceivedMessage {\n body: unknown;\n subject?: string;\n correlationId?: string;\n messageId?: string;\n deliveryCount?: number;\n applicationProperties?: { [key: string]: unknown };\n}\n\n/**\n * The subset of the Service Bus sender this adapter calls. A `ServiceBusSender` from\n * `@azure/service-bus` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface AsbSender {\n entityPath: string;\n sendMessages(message: AsbMessage): Promise<void>;\n scheduleMessages(message: AsbMessage, scheduledEnqueueTimeUtc: Date): Promise<bigint[]>;\n}\n\n/**\n * The subset of the Service Bus receiver this adapter calls. A `ServiceBusReceiver`\n * from `@azure/service-bus` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface AsbReceiver {\n receiveMessages(maxMessageCount: number, options?: { maxWaitTimeInMs?: number }): Promise<AsbReceivedMessage[]>;\n completeMessage(message: AsbReceivedMessage): Promise<void>;\n abandonMessage(message: AsbReceivedMessage): Promise<void>;\n}\n\n// --- Native projection (contract §4.2–§4.3) ------------------------------------\n\n/**\n * Project the envelope's contract fields onto a native Service Bus message — `subject`\n * = URN, `correlationId` = trace_id, `messageId` = meta.id, plus the `bq-` application\n * properties. The body stays authoritative.\n */\nexport function toServiceBusMessage(envelope: Envelope): AsbMessage {\n const applicationProperties: { [key: string]: number | boolean | string } = {};\n if (envelope.meta.schema_version != null) {\n applicationProperties[\"bq-schema-version\"] = envelope.meta.schema_version;\n }\n if (envelope.meta.lang) applicationProperties[\"bq-source-lang\"] = envelope.meta.lang;\n if (envelope.meta.created_at != null) {\n applicationProperties[\"bq-created-at\"] = envelope.meta.created_at;\n }\n\n const message: AsbMessage = {\n body: EnvelopeCodec.encode(envelope),\n contentType: \"application/json\",\n };\n if (envelope.job) message.subject = envelope.job;\n if (envelope.trace_id) message.correlationId = envelope.trace_id;\n if (envelope.meta.id) message.messageId = envelope.meta.id;\n if (Object.keys(applicationProperties).length > 0) {\n message.applicationProperties = applicationProperties;\n }\n return message;\n}\n\n// --- Publisher -----------------------------------------------------------------\n\n/** Options for {@link AsbPublisher.publish}. */\nexport interface PublishOptions {\n /** Reuse an existing trace id (trace continuation). */\n traceId?: string;\n /** Schedule native delayed delivery this many milliseconds from now (`scheduledEnqueueTimeUtc`). */\n delayMs?: number;\n}\n\n/** Sends canonical-envelope messages to one Service Bus entity with the §4 native projection. */\nexport class AsbPublisher {\n constructor(private readonly sender: AsbSender) {}\n\n /**\n * Build the canonical envelope for `(urn, data)`, send it with the native projection,\n * and return the message id (`meta.id`). A positive `delayMs` schedules native delayed\n * delivery.\n */\n async publish(\n urn: string,\n data: Record<string, unknown>,\n options: PublishOptions = {},\n ): Promise<string> {\n const envelope = EnvelopeCodec.make(urn, data, {\n queue: this.sender.entityPath,\n traceId: options.traceId,\n });\n const message = toServiceBusMessage(envelope);\n\n if (options.delayMs != null && options.delayMs > 0) {\n message.applicationProperties = { ...message.applicationProperties, \"bq-delay\": options.delayMs };\n await this.sender.scheduleMessages(message, new Date(Date.now() + options.delayMs));\n } else {\n await this.sender.sendMessages(message);\n }\n return envelope.meta.id;\n }\n}\n\n// --- Consumer ------------------------------------------------------------------\n\n/** A URN handler. Receives the validated envelope and the raw Service Bus message. */\nexport type BabelHandler = (envelope: Envelope, message: AsbReceivedMessage) => unknown | Promise<unknown>;\n\n/** A map of URN → handler. */\nexport type BabelHandlers = Record<string, BabelHandler>;\n\n/** Options for {@link AsbConsumer}. */\nexport interface AsbConsumerOptions {\n /** Called instead of erroring when a message's URN has no handler (then the message is completed). */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: AsbReceivedMessage) => unknown | Promise<unknown>;\n /** Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), or a throwing handler. The loop never stops. */\n onError?: (error: unknown, envelope: IncomingEnvelope, message: AsbReceivedMessage) => void;\n /** Max messages per receive (default 10). */\n maxMessages?: number;\n /** Max time to wait for a batch, in ms. */\n maxWaitTimeInMs?: number;\n}\n\n/**\n * Receives from a Service Bus entity (PeekLock), decodes + validates each message, routes\n * it to the handler for its URN, and completes it on success. A throwing handler abandons\n * the message — the broker redelivers it and increments `deliveryCount` (at-least-once);\n * `attempts` is reconciled to `deliveryCount − 1` for the handler.\n */\nexport class AsbConsumer {\n constructor(\n private readonly receiver: AsbReceiver,\n private readonly handlers: BabelHandlers,\n private readonly options: AsbConsumerOptions = {},\n ) {}\n\n /** Receive one batch, route each message, settle each. Returns the batch size. */\n async poll(): Promise<number> {\n const messages = await this.receiver.receiveMessages(\n this.options.maxMessages ?? 10,\n this.options.maxWaitTimeInMs != null ? { maxWaitTimeInMs: this.options.maxWaitTimeInMs } : undefined,\n );\n for (const message of messages) {\n await this.handle(message);\n }\n return messages.length;\n }\n\n /** Poll until `signal` aborts. */\n async run(signal?: AbortSignal): Promise<void> {\n while (signal?.aborted !== true) {\n await this.poll();\n }\n }\n\n private async handle(message: AsbReceivedMessage): Promise<void> {\n const raw = typeof message.body === \"string\" ? message.body : String(message.body ?? \"\");\n const envelope = EnvelopeCodec.decode(raw);\n\n // attempts = max(current, deliveryCount − 1): deliveryCount (1-based) is the native\n // redelivery floor; the max never lowers a higher body count republished from another SDK.\n const deliveryCount = typeof message.deliveryCount === \"number\" ? message.deliveryCount : 0;\n const native = deliveryCount - 1;\n const current = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n if (native > current) {\n envelope.attempts = native;\n }\n\n if (!EnvelopeCodec.accepts(envelope)) {\n this.options.onError?.(\n new BabelQueueError(\"Rejected a non-conformant BabelQueue envelope from Azure Service Bus.\"),\n envelope,\n message,\n );\n await this.receiver.abandonMessage(message);\n return;\n }\n\n const urn = EnvelopeCodec.urn(envelope);\n const handler = this.handlers[urn];\n if (!handler) {\n if (this.options.onUnknownUrn) {\n await this.options.onUnknownUrn(envelope, message);\n await this.receiver.completeMessage(message);\n } else {\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n await this.receiver.abandonMessage(message);\n }\n return;\n }\n\n try {\n await handler(envelope, message);\n await this.receiver.completeMessage(message);\n } catch (error) {\n // Abandon releases the lock — the broker redelivers and increments deliveryCount.\n this.options.onError?.(error, envelope, message);\n await this.receiver.abandonMessage(message);\n }\n }\n}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S,GAAG;AACjC,QAAI,CAAC,SAAS;AACZ,UAAI,KAAK,QAAQ,cAAc;AAC7B,cAAM,KAAK,QAAQ,aAAa,UAAU,OAAO;AACjD,cAAM,KAAK,SAAS,gBAAgB,OAAO;AAAA,MAC7C,OAAO;AACL,aAAK,QAAQ,UAAU,IAAI,gBAAgB,GAAG,GAAG,UAAU,OAAO;AAClE,cAAM,KAAK,SAAS,eAAe,OAAO;AAAA,MAC5C;AACA;AAAA,IACF;AAEA,QAAI;AACF,YAAM,QAAQ,UAAU,OAAO;AAC/B,YAAM,KAAK,SAAS,gBAAgB,OAAO;AAAA,IAC7C,SAAS,OAAO;AAEd,WAAK,QAAQ,UAAU,OAAO,UAAU,OAAO;AAC/C,YAAM,KAAK,SAAS,eAAe,OAAO;AAAA,IAC5C;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/headers.ts"],"sourcesContent":["/**\n * Azure Service Bus adapter for BabelQueue.\n *\n * A canonical-envelope **publisher** and a URN-routed **consumer** over Azure Service\n * Bus, so an ASB-based Node service speaks the same contract (envelope shape, URN\n * identity, trace propagation) as the .NET, Java, Python and Go SDKs.\n *\n * import { ServiceBusClient } from \"@azure/service-bus\";\n * import { AsbPublisher, AsbConsumer } from \"@babelqueue/azure-service-bus\";\n *\n * const client = new ServiceBusClient(connectionString);\n * await new AsbPublisher(client.createSender(\"orders\"))\n * .publish(\"urn:babel:orders:created\", { order_id: 1042 });\n *\n * const consumer = new AsbConsumer(client.createReceiver(\"orders\"), {\n * \"urn:babel:orders:created\": async (env) => { ... },\n * });\n * await consumer.run();\n *\n * This implements §4 of the broker-bindings contract: the canonical envelope is the\n * message body, projected onto native Service Bus fields (`subject` = URN,\n * `correlationId` = trace_id, `messageId` = meta.id, plus the `bq-` application\n * properties). The envelope is unchanged (`schema_version` stays 1); ASB is purely\n * additive. Retry is broker-native — a failed handler `abandon`s the message, so it is\n * redelivered and `deliveryCount` is incremented; the authoritative attempt count is the\n * native `deliveryCount`, surfaced to handlers as `attempts = deliveryCount − 1`.\n *\n * **Out-of-band headers (ADR-0028).** A `headers` carrier (e.g. a W3C `traceparent` for cross-hop\n * span linkage) rides as additional native `applicationProperties` beside the contract `bq-*`\n * properties — the contract properties win a key collision (merge-not-clobber), blanks dropped. On\n * consume the inbound `applicationProperties` are surfaced as a `Record<string,string>` so the\n * core's `otel` extract sees the `traceparent` and links the consumer span as a child. A\n * header-less publish is byte-identical. GR-1: the wire envelope body is never touched.\n */\n\nimport { BabelQueueError, EnvelopeCodec, UnknownUrnError } from \"@babelqueue/core\";\nimport type { Envelope, HeaderCarrier, IncomingEnvelope } from \"@babelqueue/core\";\n\nimport { sanitizeHeaders } from \"./headers.js\";\n\n// --- Minimal Service Bus shapes (a structural subset of @azure/service-bus) -----\n\n/** A message to send (structural subset of @azure/service-bus `ServiceBusMessage`). */\nexport interface AsbMessage {\n body: unknown;\n subject?: string;\n correlationId?: string;\n messageId?: string;\n contentType?: string;\n applicationProperties?: { [key: string]: number | boolean | string | Date | null };\n scheduledEnqueueTimeUtc?: Date;\n}\n\n/** A received message (structural subset of @azure/service-bus `ServiceBusReceivedMessage`). */\nexport interface AsbReceivedMessage {\n body: unknown;\n subject?: string;\n correlationId?: string;\n messageId?: string;\n deliveryCount?: number;\n applicationProperties?: { [key: string]: unknown };\n}\n\n/**\n * The subset of the Service Bus sender this adapter calls. A `ServiceBusSender` from\n * `@azure/service-bus` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface AsbSender {\n entityPath: string;\n sendMessages(message: AsbMessage): Promise<void>;\n scheduleMessages(message: AsbMessage, scheduledEnqueueTimeUtc: Date): Promise<bigint[]>;\n}\n\n/**\n * The subset of the Service Bus receiver this adapter calls. A `ServiceBusReceiver`\n * from `@azure/service-bus` satisfies it structurally; a fake satisfies it in tests.\n */\nexport interface AsbReceiver {\n receiveMessages(maxMessageCount: number, options?: { maxWaitTimeInMs?: number }): Promise<AsbReceivedMessage[]>;\n completeMessage(message: AsbReceivedMessage): Promise<void>;\n abandonMessage(message: AsbReceivedMessage): Promise<void>;\n}\n\n// --- Native projection (contract §4.2–§4.3) ------------------------------------\n\n/**\n * Project the envelope's contract fields onto a native Service Bus message — `subject`\n * = URN, `correlationId` = trace_id, `messageId` = meta.id, plus the `bq-` application\n * properties. The body stays authoritative.\n *\n * When `extra` is given, those out-of-band headers (e.g. a W3C `traceparent`, ADR-0028) are merged\n * into `applicationProperties` **first**, then the contract `bq-*` properties are written so they\n * always win a key collision (merge-not-clobber); blank keys/values are dropped. GR-1: the wire\n * envelope body is never touched.\n */\nexport function toServiceBusMessage(envelope: Envelope, extra?: HeaderCarrier | null): AsbMessage {\n const applicationProperties: { [key: string]: number | boolean | string } = {};\n // Out-of-band riders go in first so the contract bq-* properties below win any key collision.\n for (const [key, value] of Object.entries(sanitizeHeaders(extra))) applicationProperties[key] = value;\n if (envelope.meta.schema_version != null) {\n applicationProperties[\"bq-schema-version\"] = envelope.meta.schema_version;\n }\n if (envelope.meta.lang) applicationProperties[\"bq-source-lang\"] = envelope.meta.lang;\n if (envelope.meta.created_at != null) {\n applicationProperties[\"bq-created-at\"] = envelope.meta.created_at;\n }\n\n const message: AsbMessage = {\n body: EnvelopeCodec.encode(envelope),\n contentType: \"application/json\",\n };\n if (envelope.job) message.subject = envelope.job;\n if (envelope.trace_id) message.correlationId = envelope.trace_id;\n if (envelope.meta.id) message.messageId = envelope.meta.id;\n if (Object.keys(applicationProperties).length > 0) {\n message.applicationProperties = applicationProperties;\n }\n return message;\n}\n\n/**\n * Read a received message's `applicationProperties` back into a flat {@link HeaderCarrier},\n * stringifying values defensively. Returns an empty object when there are none. Both the contract\n * `bq-*` properties and any out-of-band rider (e.g. `traceparent`) surface — the core's `otel`\n * extract reads only the keys it knows.\n */\nexport function headersOf(message: AsbReceivedMessage): HeaderCarrier {\n const props = message.applicationProperties;\n const out: HeaderCarrier = {};\n if (!props) return out;\n for (const key of Object.keys(props)) {\n const value = props[key];\n if (value == null) continue;\n const s = String(value);\n if (s !== \"\") out[key] = s;\n }\n return out;\n}\n\n// --- Publisher -----------------------------------------------------------------\n\n/** Options for {@link AsbPublisher.publish}. */\nexport interface PublishOptions {\n /** Reuse an existing trace id (trace continuation). */\n traceId?: string;\n /** Schedule native delayed delivery this many milliseconds from now (`scheduledEnqueueTimeUtc`). */\n delayMs?: number;\n /**\n * Out-of-band transport headers carried as native `applicationProperties` beside the contract\n * `bq-*` properties (ADR-0028) — e.g. a W3C `traceparent` written by `@babelqueue/core/otel`'s\n * `publish`. The contract properties win a key collision; an empty/omitted carrier leaves the\n * message unchanged.\n */\n headers?: HeaderCarrier;\n}\n\n/** Sends canonical-envelope messages to one Service Bus entity with the §4 native projection. */\nexport class AsbPublisher {\n constructor(private readonly sender: AsbSender) {}\n\n /**\n * Build the canonical envelope for `(urn, data)`, send it with the native projection,\n * and return the message id (`meta.id`). A positive `delayMs` schedules native delayed\n * delivery.\n */\n async publish(\n urn: string,\n data: Record<string, unknown>,\n options: PublishOptions = {},\n ): Promise<string> {\n const envelope = EnvelopeCodec.make(urn, data, {\n queue: this.sender.entityPath,\n traceId: options.traceId,\n });\n const message = toServiceBusMessage(envelope, options.headers);\n\n if (options.delayMs != null && options.delayMs > 0) {\n message.applicationProperties = { ...message.applicationProperties, \"bq-delay\": options.delayMs };\n await this.sender.scheduleMessages(message, new Date(Date.now() + options.delayMs));\n } else {\n await this.sender.sendMessages(message);\n }\n return envelope.meta.id;\n }\n}\n\n// --- Consumer ------------------------------------------------------------------\n\n/**\n * A URN handler. Receives the validated envelope, the raw Service Bus message, and the out-of-band\n * {@link HeaderCarrier} read from the message's `applicationProperties` (empty when there are none).\n * Pass `headers` to `@babelqueue/core/otel`'s `wrapHandler` to link the consumer span as a child of\n * the producer span (ADR-0028).\n */\nexport type BabelHandler = (envelope: Envelope, message: AsbReceivedMessage, headers: HeaderCarrier) => unknown | Promise<unknown>;\n\n/** A map of URN → handler. */\nexport type BabelHandlers = Record<string, BabelHandler>;\n\n/** Options for {@link AsbConsumer}. */\nexport interface AsbConsumerOptions {\n /** Called instead of erroring when a message's URN has no handler (then the message is completed). */\n onUnknownUrn?: (envelope: IncomingEnvelope, message: AsbReceivedMessage) => unknown | Promise<unknown>;\n /** Called for a non-conformant envelope, an unmapped URN (no `onUnknownUrn`), or a throwing handler. The loop never stops. */\n onError?: (error: unknown, envelope: IncomingEnvelope, message: AsbReceivedMessage) => void;\n /** Max messages per receive (default 10). */\n maxMessages?: number;\n /** Max time to wait for a batch, in ms. */\n maxWaitTimeInMs?: number;\n}\n\n/**\n * Receives from a Service Bus entity (PeekLock), decodes + validates each message, routes\n * it to the handler for its URN, and completes it on success. A throwing handler abandons\n * the message — the broker redelivers it and increments `deliveryCount` (at-least-once);\n * `attempts` is reconciled to `deliveryCount − 1` for the handler.\n */\nexport class AsbConsumer {\n constructor(\n private readonly receiver: AsbReceiver,\n private readonly handlers: BabelHandlers,\n private readonly options: AsbConsumerOptions = {},\n ) {}\n\n /** Receive one batch, route each message, settle each. Returns the batch size. */\n async poll(): Promise<number> {\n const messages = await this.receiver.receiveMessages(\n this.options.maxMessages ?? 10,\n this.options.maxWaitTimeInMs != null ? { maxWaitTimeInMs: this.options.maxWaitTimeInMs } : undefined,\n );\n for (const message of messages) {\n await this.handle(message);\n }\n return messages.length;\n }\n\n /** Poll until `signal` aborts. */\n async run(signal?: AbortSignal): Promise<void> {\n while (signal?.aborted !== true) {\n await this.poll();\n }\n }\n\n private async handle(message: AsbReceivedMessage): Promise<void> {\n const raw = typeof message.body === \"string\" ? message.body : String(message.body ?? \"\");\n const envelope = EnvelopeCodec.decode(raw);\n\n // attempts = max(current, deliveryCount − 1): deliveryCount (1-based) is the native\n // redelivery floor; the max never lowers a higher body count republished from another SDK.\n const deliveryCount = typeof message.deliveryCount === \"number\" ? message.deliveryCount : 0;\n const native = deliveryCount - 1;\n const current = typeof envelope.attempts === \"number\" ? envelope.attempts : 0;\n if (native > current) {\n envelope.attempts = native;\n }\n\n if (!EnvelopeCodec.accepts(envelope)) {\n this.options.onError?.(\n new BabelQueueError(\"Rejected a non-conformant BabelQueue envelope from Azure Service Bus.\"),\n envelope,\n message,\n );\n await this.receiver.abandonMessage(message);\n return;\n }\n\n const urn = EnvelopeCodec.urn(envelope);\n const handler = this.handlers[urn];\n if (!handler) {\n if (this.options.onUnknownUrn) {\n await this.options.onUnknownUrn(envelope, message);\n await this.receiver.completeMessage(message);\n } else {\n this.options.onError?.(new UnknownUrnError(urn), envelope, message);\n await this.receiver.abandonMessage(message);\n }\n return;\n }\n\n try {\n await handler(envelope, message, headersOf(message));\n await this.receiver.completeMessage(message);\n } catch (error) {\n // Abandon releases the lock — the broker redelivers and increments deliveryCount.\n this.options.onError?.(error, envelope, message);\n await this.receiver.abandonMessage(message);\n }\n }\n}\n","/**\n * Pure, dependency-free helpers for the out-of-band transport-header seam (ADR-0028) — the Node\n * adapter mirror of Go's `sanitizeHeaders` and PHP's `Support\\Headers`. They fold an injected\n * {@link HeaderCarrier} (e.g. a W3C `traceparent`) onto a transport's metadata channel **without\n * clobbering** the contract headers it already carries.\n *\n * Headers ride beside the frozen wire envelope (GR-1), never inside it.\n */\n\nimport type { HeaderCarrier } from \"@babelqueue/core\";\n\n/**\n * Copy `headers`, dropping blank keys and blank values. Returns an empty object when nothing\n * survives. A nullish input yields an empty object.\n */\nexport function sanitizeHeaders(headers: HeaderCarrier | null | undefined): HeaderCarrier {\n const out: HeaderCarrier = {};\n if (!headers) return out;\n for (const key of Object.keys(headers)) {\n const value = headers[key];\n if (key === \"\" || value == null || value === \"\") continue;\n out[key] = value;\n }\n return out;\n}\n"],"mappings":";AAmCA,SAAS,iBAAiB,eAAe,uBAAuB;;;ACpBzD,SAAS,gBAAgB,SAA0D;AACxF,QAAM,MAAqB,CAAC;AAC5B,MAAI,CAAC,QAAS,QAAO;AACrB,aAAW,OAAO,OAAO,KAAK,OAAO,GAAG;AACtC,UAAM,QAAQ,QAAQ,GAAG;AACzB,QAAI,QAAQ,MAAM,S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IzC,UAAM,gBAAgB,OAAO,QAAQ,kBAAkB,WAAW,QAAQ,gBAAgB;AAC1F,UAAM,SAAS,gBAAgB;AAC/B,UAAM,UAAU,OAAO,SAAS,aAAa,WAAW,SAAS,WAAW;AAC5E,QAAI,SAAS,SAAS;AACpB,eAAS,WAAW;AAAA,IACtB;AAEA,QAAI,CAAC,cAAc,QAAQ,QAAQ,GAAG;AACpC,WAAK,QAAQ;AAAA,QACX,IAAI,gBAAgB,uEAAuE;AAAA,QAC3F;AAAA,QACA;AAAA,MACF;AACA,YAAM,KAAK,SAAS,eAAe,OAAO;AAC1C;AAAA,IACF;AAEA,UAAM,MAAM,cAAc,IAAI,QAAQ;AACtC,UAAM,UAAU,KAAK,SAAS,GAAG;AACjC,QAAI,CAAC,SAAS;AACZ,UAAI,KAAK,QAAQ,cAAc;AAC7B,cAAM,KAAK,QAAQ,aAAa,UAAU,OAAO;AACjD,cAAM,KAAK,SAAS,gBAAgB,OAAO;AAAA,MAC7C,OAAO;AACL,aAAK,QAAQ,UAAU,IAAI,gBAAgB,GAAG,GAAG,UAAU,OAAO;AAClE,cAAM,KAAK,SAAS,eAAe,OAAO;AAAA,MAC5C;AACA;AAAA,IACF;AAEA,QAAI;AACF,YAAM,QAAQ,UAAU,SAAS,UAAU,OAAO,CAAC;AACnD,YAAM,KAAK,SAAS,gBAAgB,OAAO;AAAA,IAC7C,SAAS,OAAO;AAEd,WAAK,QAAQ,UAAU,OAAO,UAAU,OAAO;AAC/C,YAAM,KAAK,SAAS,eAAe,OAAO;AAAA,IAC5C;AAAA,EACF;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,8 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@babelqueue/azure-service-bus",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Azure Service Bus adapter for BabelQueue — canonical-envelope publisher and a URN-routed consumer.",
|
|
5
|
-
"keywords": [
|
|
5
|
+
"keywords": [
|
|
6
|
+
"babelqueue",
|
|
7
|
+
"azure",
|
|
8
|
+
"servicebus",
|
|
9
|
+
"asb",
|
|
10
|
+
"queue",
|
|
11
|
+
"polyglot",
|
|
12
|
+
"messaging"
|
|
13
|
+
],
|
|
6
14
|
"homepage": "https://babelqueue.com",
|
|
7
15
|
"bugs": {
|
|
8
16
|
"url": "https://github.com/BabelQueue/babelqueue-node-adapters/issues"
|
|
@@ -30,7 +38,9 @@
|
|
|
30
38
|
"main": "./dist/index.cjs",
|
|
31
39
|
"module": "./dist/index.js",
|
|
32
40
|
"types": "./dist/index.d.ts",
|
|
33
|
-
"files": [
|
|
41
|
+
"files": [
|
|
42
|
+
"dist"
|
|
43
|
+
],
|
|
34
44
|
"sideEffects": false,
|
|
35
45
|
"engines": {
|
|
36
46
|
"node": ">=18"
|
|
@@ -41,7 +51,7 @@
|
|
|
41
51
|
"test": "node --import tsx --test test/*.test.ts"
|
|
42
52
|
},
|
|
43
53
|
"dependencies": {
|
|
44
|
-
"@babelqueue/core": "^1.
|
|
54
|
+
"@babelqueue/core": "^1.4.0"
|
|
45
55
|
},
|
|
46
56
|
"peerDependencies": {
|
|
47
57
|
"@azure/service-bus": "^7.0.0"
|