Skip to content

@amqp-contract/contract


@amqp-contract/contract

Type Aliases

AnySchema

ts
type AnySchema = StandardSchemaV1;

Defined in: types.ts:12

Any schema that conforms to Standard Schema v1.

This library supports any validation library that implements the Standard Schema v1 specification, including Zod, Valibot, and ArkType. This allows you to use your preferred validation library while maintaining type safety.

See

https://github.com/standard-schema/standard-schema


BaseExchangeDefinition

ts
type BaseExchangeDefinition<TName> = object;

Defined in: types.ts:376

Base definition of an AMQP exchange.

An exchange receives messages from publishers and routes them to queues based on the exchange type and routing rules. This type contains properties common to all exchange types.

Type Parameters

Type ParameterDefault type
TName extends stringstring

Properties

PropertyTypeDescriptionDefined in
arguments?Record<string, unknown>Additional AMQP arguments for advanced configuration. Common arguments include alternate-exchange for handling unroutable messages.types.ts:405
autoDelete?booleanIf true, the exchange is deleted when all queues have finished using it. Default falsetypes.ts:392
durable?booleanIf true, the exchange survives broker restarts. Durable exchanges are persisted to disk. Default falsetypes.ts:386
internal?booleanIf true, the exchange cannot be directly published to by clients. It can only receive messages from other exchanges via exchange-to-exchange bindings. Default falsetypes.ts:399
nameTNameThe name of the exchange. Must be unique within the RabbitMQ virtual host.types.ts:380

BindingDefinition

ts
type BindingDefinition = 
  | QueueBindingDefinition
  | ExchangeBindingDefinition;

Defined in: types.ts:833

Union type of all binding definitions.

A binding can be either:

  • Queue-to-exchange binding: Routes messages from an exchange to a queue
  • Exchange-to-exchange binding: Forwards messages from one exchange to another

BindingPattern

ts
type BindingPattern<S> = S extends "" ? never : S;

Defined in: builder/routing-types.ts:52

Type-safe binding pattern that validates basic format and wildcards.

Validates that a binding pattern follows basic AMQP binding pattern rules:

  • Can contain wildcards (* for one word, # for zero or more words)
  • Must not be empty
  • Should contain alphanumeric characters, dots, hyphens, underscores, and wildcards

Note: Full character-by-character validation is not performed to avoid TypeScript recursion depth limits. Runtime validation is still recommended.

Type Parameters

Type ParameterDescription
S extends stringThe binding pattern string to validate

Example

typescript
type ValidPattern = BindingPattern<"order.*">; // "order.*"
type ValidHash = BindingPattern<"order.#">; // "order.#"
type ValidConcrete = BindingPattern<"order.created">; // "order.created"
type Invalid = BindingPattern<"">; // never (empty string)

BridgedPublisherConfig

ts
type BridgedPublisherConfig<TMessage, TBridgeExchange, TTargetExchange> = object;

Defined in: builder/command.ts:66

Configuration for a bridged command publisher.

A bridged publisher publishes to a bridge exchange (local domain), which forwards messages to the target exchange (remote domain) via an exchange-to-exchange binding.

Type Parameters

Type ParameterDescription
TMessage extends MessageDefinitionThe message definition
TBridgeExchange extends ExchangeDefinitionThe bridge (local domain) exchange definition
TTargetExchange extends ExchangeDefinitionThe target (remote domain) exchange definition

Properties

PropertyTypeDescriptionDefined in
__brand"BridgedPublisherConfig"Discriminator to identify this as a bridged publisher configbuilder/command.ts:72
bridgeExchangeTBridgeExchangeThe bridge (local domain) exchangebuilder/command.ts:78
exchangeBindingExchangeBindingDefinitionThe exchange-to-exchange binding (bridge → target)builder/command.ts:76
publisherPublisherDefinition<TMessage>The publisher definition (publishes to bridge exchange)builder/command.ts:74
targetExchangeTTargetExchangeThe target (remote domain) exchangebuilder/command.ts:80

BridgedPublisherConfigBase

ts
type BridgedPublisherConfigBase = object;

Defined in: types.ts:968

Base type for bridged publisher configuration.

A bridged publisher publishes to a bridge exchange, which forwards messages to the target exchange via an exchange-to-exchange binding.

See

defineCommandPublisher with bridgeExchange option

Properties

PropertyTypeDefined in
__brand"BridgedPublisherConfig"types.ts:969
bridgeExchangeExchangeDefinitiontypes.ts:972
exchangeBindingExchangeBindingDefinitiontypes.ts:971
publisherPublisherDefinitiontypes.ts:970
targetExchangeExchangeDefinitiontypes.ts:973

ClassicQueueDefinition

ts
type ClassicQueueDefinition<TName> = BaseQueueDefinition<TName> & object;

Defined in: types.ts:595

Definition of a classic queue.

Classic queues are the traditional RabbitMQ queue type. Use them when you need specific features not supported by quorum queues (e.g., exclusive queues, priority queues).

Type Declaration

NameTypeDescriptionDefined in
deliveryLimit?neverClassic queues do not support delivery limits. Use type: 'quorum' if you need native retry with delivery limits.types.ts:605
exclusive?booleanIf true, the queue can only be used by the declaring connection and is deleted when that connection closes. Exclusive queues are private to the connection. Default falsetypes.ts:612
retryResolvedTtlBackoffRetryOptionsRetry configuration for handling failed message processing. Classic queues only support TTL-backoff retry mode (default). When the queue is created, defaults are applied.types.ts:620
type"classic"Queue type discriminator: classic queue.types.ts:599

Type Parameters

Type ParameterDefault type
TName extends stringstring

ClassicQueueOptions

ts
type ClassicQueueOptions = BaseQueueOptions & object;

Defined in: types.ts:318

Options for creating a classic queue.

Classic queues support all traditional RabbitMQ features including:

  • exclusive: true - For connection-scoped queues
  • maxPriority - For priority queues
  • durable: false - For non-durable queues

Type Declaration

NameTypeDescriptionDefined in
exclusive?booleanIf true, the queue can only be used by the declaring connection and is deleted when that connection closes. Exclusive queues are private to the connection. Default falsetypes.ts:329
maxPriority?numberMaximum priority level for priority queue (1-255, recommended: 1-10). Sets x-max-priority argument. Only supported with classic queues.types.ts:336
retry?TtlBackoffRetryOptionsRetry configuration for handling failed message processing. Classic queues only support TTL-backoff retry mode, which uses wait queues with exponential backoff. For quorum-native retry, use quorum queues instead. Example const orderQueue = defineQueue('order-processing', { type: 'classic', durable: true, deadLetter: { exchange: dlx }, retry: { maxRetries: 5, initialDelayMs: 1000, maxDelayMs: 30000, }, });types.ts:358
type"classic"Queue type: classic (for special cases)types.ts:322

Example

typescript
const priorityQueue = defineQueue('tasks', {
  type: 'classic',
  durable: true,
  maxPriority: 10,
});

CommandConsumerConfig

ts
type CommandConsumerConfig<TMessage, TExchange, TRoutingKey, TQueue, TDlxExchange> = object;

Defined in: builder/command.ts:31

Configuration for a command consumer.

Commands are sent by one or more publishers to a single consumer (task queue pattern). The consumer "owns" the queue, and publishers send commands to it.

Type Parameters

Type ParameterDefault typeDescription
TMessage extends MessageDefinition-The message definition
TExchange extends ExchangeDefinition-The exchange definition
TRoutingKey extends string | undefinedundefinedThe routing key type (undefined for fanout)
TQueue extends QueueDefinitionQueueDefinition-
TDlxExchange extends ExchangeDefinition | undefinedExchangeDefinition | undefined-

Properties

PropertyTypeDescriptionDefined in
__brand"CommandConsumerConfig"Discriminator to identify this as a command consumer configbuilder/command.ts:39
bindingQueueBindingDefinitionThe binding connecting the queue to the exchangebuilder/command.ts:43
consumerConsumerDefinition<TMessage>The consumer definition for processing commandsbuilder/command.ts:41
deadLetterExchangeTDlxExchangeThe dead letter exchange from the queue, if configuredbuilder/command.ts:49
exchangeTExchangeThe exchange that receives commandsbuilder/command.ts:45
messageTMessageThe message definitionbuilder/command.ts:51
queueTQueueThe queue this consumer reads frombuilder/command.ts:47
routingKeyTRoutingKeyThe routing key pattern for the bindingbuilder/command.ts:53

CommandConsumerConfigBase

ts
type CommandConsumerConfigBase = object;

Defined in: types.ts:930

Base type for command consumer configuration.

This is a simplified type used in ContractDefinition. The full generic type is defined in the builder module.

See

defineCommandConsumer for creating command consumers

Properties

PropertyTypeDefined in
__brand"CommandConsumerConfig"types.ts:931
bindingQueueBindingDefinitiontypes.ts:933
consumerConsumerDefinitiontypes.ts:932
deadLetterExchangeExchangeDefinition | undefinedtypes.ts:936
exchangeExchangeDefinitiontypes.ts:934
messageMessageDefinitiontypes.ts:937
queueQueueDefinitiontypes.ts:935
routingKeystring | undefinedtypes.ts:938

CompressionAlgorithm

ts
type CompressionAlgorithm = "gzip" | "deflate";

Defined in: types.ts:134

Supported compression algorithms for message payloads.

  • gzip: GZIP compression (standard, widely supported, good compression ratio)
  • deflate: DEFLATE compression (faster than gzip, slightly less compression)

Compression is configured at runtime via PublishOptions when calling AmqpClient.publish, not at publisher definition time.

When compression is enabled, the message payload is compressed before publishing and automatically decompressed when consuming. The content-encoding AMQP message property is set to indicate the compression algorithm used.

To disable compression, simply omit the compression option (it's optional).

Example

typescript
// Define a publisher without compression configuration
const orderCreatedPublisher = definePublisher(exchange, message, {
  routingKey: "order.created",
});

// Later, choose whether to compress at publish time
await client.publish("orderCreated", payload, {
  compression: "gzip",
});

ConsumerDefinition

ts
type ConsumerDefinition<TMessage> = object;

Defined in: types.ts:894

Definition of a message consumer.

A consumer receives and processes messages from a queue with automatic schema validation. The message payload is validated against the schema before being passed to your handler. If the message is compressed (indicated by the content-encoding header), it will be automatically decompressed before validation.

Example

typescript
const consumer: ConsumerDefinition = {
  queue: orderProcessingQueue,
  message: orderMessage
};

Type Parameters

Type ParameterDefault typeDescription
TMessage extends MessageDefinitionMessageDefinitionThe message definition with payload schema

Properties

PropertyTypeDescriptionDefined in
messageTMessageThe message definition including the payload schematypes.ts:899
queueQueueDefinitionThe queue to consume messages fromtypes.ts:896

ConsumerEntry

ts
type ConsumerEntry = 
  | ConsumerDefinition
  | EventConsumerResultBase
  | CommandConsumerConfigBase;

Defined in: types.ts:1066

Consumer entry that can be passed to defineContract's consumers section.

Can be either:

  • A plain ConsumerDefinition from defineConsumer
  • An EventConsumerResult from defineEventConsumer (binding auto-extracted)
  • A CommandConsumerConfig from defineCommandConsumer (binding auto-extracted)

ContractDefinition

ts
type ContractDefinition = object;

Defined in: types.ts:1009

Complete AMQP contract definition (output type).

A contract brings together all AMQP resources into a single, type-safe definition. It defines the complete messaging topology including exchanges, queues, bindings, publishers, and consumers.

The contract is used by:

  • Clients (TypedAmqpClient) for type-safe message publishing
  • Workers (TypedAmqpWorker) for type-safe message consumption
  • AsyncAPI generator for documentation

Example

typescript
const contract: ContractDefinition = {
  exchanges: {
    orders: ordersExchange,
  },
  queues: {
    orderProcessing: orderProcessingQueue,
  },
  bindings: {
    orderBinding: orderQueueBinding,
  },
  publishers: {
    orderCreated: orderCreatedPublisher,
  },
  consumers: {
    processOrder: processOrderConsumer,
  },
};

Properties

PropertyTypeDescriptionDefined in
bindings?Record<string, BindingDefinition>Named binding definitions. Bindings can be queue-to-exchange or exchange-to-exchange.types.ts:1029
consumers?Record<string, ConsumerDefinition>Named consumer definitions. Each key requires a corresponding handler in the TypedAmqpWorker. The handler will be fully typed based on the message schema.types.ts:1043
exchanges?Record<string, ExchangeDefinition>Named exchange definitions. Each key becomes available as a named resource in the contract.types.ts:1014
publishers?Record<string, PublisherDefinition>Named publisher definitions. Each key becomes a method on the TypedAmqpClient for publishing messages. The method will be fully typed based on the message schema.types.ts:1036
queues?Record<string, QueueEntry>Named queue definitions. Each key becomes available as a named resource in the contract. When a queue has TTL-backoff retry configured, pass the QueueWithTtlBackoffInfrastructure object returned by defineQueue. The wait queue and bindings will be automatically added.types.ts:1023

ContractDefinitionInput

ts
type ContractDefinitionInput = object;

Defined in: types.ts:1095

Contract definition input type with automatic extraction of event/command patterns.

Users only define publishers and consumers. Exchanges, queues, and bindings are automatically extracted from these definitions.

Example

typescript
const contract = defineContract({
  publishers: {
    // EventPublisherConfig → auto-extracted to publisher
    orderCreated: defineEventPublisher(ordersExchange, orderMessage, { routingKey: "order.created" }),
  },
  consumers: {
    // CommandConsumerConfig → auto-extracted to consumer + binding
    processOrder: defineCommandConsumer(orderQueue, ordersExchange, orderMessage, { routingKey: "order.process" }),
    // EventConsumerResult → auto-extracted to consumer + binding
    notify: defineEventConsumer(orderCreatedEvent, notificationQueue),
  },
});

See

defineContract - Processes this input and returns a ContractDefinition

Properties

PropertyTypeDescriptionDefined in
consumers?Record<string, ConsumerEntry>Named consumer definitions. Can accept: - ConsumerDefinition from defineConsumer - EventConsumerResult from defineEventConsumer (binding auto-extracted) - CommandConsumerConfig from defineCommandConsumer (binding auto-extracted)types.ts:1113
publishers?Record<string, PublisherEntry>Named publisher definitions. Can accept: - PublisherDefinition from definePublisher - EventPublisherConfig from defineEventPublisher (auto-extracted to publisher)types.ts:1103

ContractOutput

ts
type ContractOutput<TContract> = object;

Defined in: types.ts:1422

Contract output type with all resources extracted and properly typed.

This type represents the fully expanded contract with:

  • exchanges: Extracted from publishers and consumer bindings
  • queues: Extracted from consumers
  • bindings: Extracted from event/command consumers
  • publishers: Normalized publisher definitions
  • consumers: Normalized consumer definitions

Type Parameters

Type Parameter
TContract extends ContractDefinitionInput

Properties

PropertyTypeDefined in
bindingsTContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractBindingsFromConsumers<TContract["consumers"]> : object & TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractExchangeBindingsFromConsumers<TContract["consumers"]> : object & TContract["publishers"] extends Record<string, PublisherEntry> ? ExtractExchangeBindingsFromPublishers<TContract["publishers"]> : objecttypes.ts:1441
consumersTContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractConsumerDefinitions<TContract["consumers"]> : objecttypes.ts:1453
exchangesTContract["publishers"] extends Record<string, PublisherEntry> ? ExtractExchangesFromPublishers<TContract["publishers"]> : object & TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractExchangesFromConsumers<TContract["consumers"]> : object & TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractDeadLetterExchangesFromConsumers<TContract["consumers"]> : object & TContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractBridgeExchangesFromConsumers<TContract["consumers"]> : object & TContract["publishers"] extends Record<string, PublisherEntry> ? ExtractTargetExchangesFromPublishers<TContract["publishers"]> : objecttypes.ts:1423
publishersTContract["publishers"] extends Record<string, PublisherEntry> ? ExtractPublisherDefinitions<TContract["publishers"]> : objecttypes.ts:1450
queuesTContract["consumers"] extends Record<string, ConsumerEntry> ? ExtractQueuesFromConsumers<TContract["consumers"]> : objecttypes.ts:1438

DeadLetterConfig

ts
type DeadLetterConfig = object;

Defined in: types.ts:483

Configuration for dead letter exchange (DLX) on a queue.

When a message in a queue is rejected, expires, or exceeds the queue length limit, it can be automatically forwarded to a dead letter exchange for further processing or storage.

Properties

PropertyTypeDescriptionDefined in
exchangeExchangeDefinitionThe exchange to send dead-lettered messages to. This exchange must be declared in the contract.types.ts:488
routingKey?stringOptional routing key to use when forwarding messages to the dead letter exchange. If not specified, the original message routing key is used.types.ts:494

DefineQueueOptions

ts
type DefineQueueOptions = 
  | QuorumQueueOptions
  | ClassicQueueOptions;

Defined in: types.ts:368

Options for defining a queue. Uses a discriminated union based on the type property to enforce quorum queue constraints at compile time.

  • Quorum queues (default): Do not support exclusive or maxPriority
  • Classic queues: Support all options including exclusive and maxPriority

DefineQuorumQueueOptions

ts
type DefineQuorumQueueOptions = object;

Defined in: builder/queue.ts:399

Options for creating a quorum queue with quorum-native retry.

This simplified helper enforces the required configuration for quorum-native retry:

  • Dead letter exchange is required (for failed messages)
  • Delivery limit is required (for retry count)

Properties

PropertyTypeDescriptionDefined in
arguments?Record<string, unknown>Additional AMQP arguments for advanced configuration.builder/queue.ts:421
autoDelete?booleanIf true, the queue is deleted when the last consumer unsubscribes. Default falsebuilder/queue.ts:416
deadLetterDeadLetterConfigDead letter configuration - required for retry support. Failed messages will be sent to this exchange.builder/queue.ts:404
deliveryLimitnumberMaximum number of delivery attempts before dead-lettering. Minimum 1builder/queue.ts:410

DefineTtlBackoffQueueOptions

ts
type DefineTtlBackoffQueueOptions = object;

Defined in: builder/queue.ts:486

Options for creating a queue with TTL-backoff retry.

This simplified helper enforces the required configuration for TTL-backoff retry:

  • Dead letter exchange is required (used for retry routing)
  • Returns infrastructure that includes wait queue and bindings

Properties

PropertyTypeDescriptionDefined in
arguments?Record<string, unknown>Additional AMQP arguments for advanced configuration.builder/queue.ts:532
autoDelete?booleanIf true, the queue is deleted when the last consumer unsubscribes. Default falsebuilder/queue.ts:527
backoffMultiplier?numberExponential backoff multiplier. Default 2builder/queue.ts:515
deadLetterDeadLetterConfigDead letter configuration - required for TTL-backoff retry. Used for routing messages to the wait queue and back.builder/queue.ts:491
initialDelayMs?numberInitial delay in ms before first retry. Default 1000builder/queue.ts:503
jitter?booleanAdd jitter to prevent thundering herd. Default truebuilder/queue.ts:521
maxDelayMs?numberMaximum delay in ms between retries. Default 30000builder/queue.ts:509
maxRetries?numberMaximum retry attempts before sending to DLQ. Default 3builder/queue.ts:497

DirectExchangeDefinition

ts
type DirectExchangeDefinition<TName> = BaseExchangeDefinition<TName> & object;

Defined in: types.ts:439

A direct exchange definition.

Direct exchanges route messages to queues based on exact routing key matches. This is ideal for point-to-point messaging where each message should go to specific queues.

Type Declaration

NameTypeDefined in
type"direct"types.ts:441

Type Parameters

Type ParameterDefault type
TName extends stringstring

Example

typescript
const tasksExchange: DirectExchangeDefinition = defineExchange('tasks', 'direct', {
  durable: true
});

EventConsumerResult

ts
type EventConsumerResult<TMessage, TExchange, TQueue, TDlxExchange, TExchangeBinding, TBridgeExchange> = object;

Defined in: builder/event.ts:56

Result from defineEventConsumer.

Contains the consumer definition and binding needed to subscribe to an event. Can be used directly in defineContract's consumers section - the binding will be automatically extracted.

Type Parameters

Type ParameterDefault typeDescription
TMessage extends MessageDefinition-The message definition
TExchange extends ExchangeDefinitionExchangeDefinition-
TQueue extends QueueDefinitionQueueDefinition-
TDlxExchange extends ExchangeDefinition | undefinedExchangeDefinition | undefined-
TExchangeBinding extends ExchangeBindingDefinition | undefinedExchangeBindingDefinition | undefined-
TBridgeExchange extends ExchangeDefinition | undefinedExchangeDefinition | undefined-

Properties

PropertyTypeDescriptionDefined in
__brand"EventConsumerResult"Discriminator to identify this as an event consumer resultbuilder/event.ts:67
bindingQueueBindingDefinitionThe binding connecting the queue to the exchangebuilder/event.ts:71
bridgeExchangeTBridgeExchangeThe bridge (local domain) exchange when bridging, if configuredbuilder/event.ts:81
consumerConsumerDefinition<TMessage>The consumer definition for processing messagesbuilder/event.ts:69
deadLetterExchangeTDlxExchangeThe dead letter exchange from the queue, if configuredbuilder/event.ts:77
exchangeTExchangeThe source exchange this consumer subscribes tobuilder/event.ts:73
exchangeBindingTExchangeBindingThe exchange-to-exchange binding when bridging, if configuredbuilder/event.ts:79
queueTQueueThe queue this consumer reads frombuilder/event.ts:75

EventConsumerResultBase

ts
type EventConsumerResultBase = object;

Defined in: types.ts:949

Base type for event consumer result.

This is a simplified type used in ContractDefinitionInput. The full generic type is defined in the builder module.

See

defineEventConsumer for creating event consumers

Properties

PropertyTypeDefined in
__brand"EventConsumerResult"types.ts:950
bindingQueueBindingDefinitiontypes.ts:952
bridgeExchangeExchangeDefinition | undefinedtypes.ts:957
consumerConsumerDefinitiontypes.ts:951
deadLetterExchangeExchangeDefinition | undefinedtypes.ts:955
exchangeExchangeDefinitiontypes.ts:953
exchangeBindingExchangeBindingDefinition | undefinedtypes.ts:956
queueQueueDefinitiontypes.ts:954

EventPublisherConfig

ts
type EventPublisherConfig<TMessage, TExchange, TRoutingKey> = object;

Defined in: builder/event.ts:30

Configuration for an event publisher.

Events are published without knowing who consumes them. Multiple consumers can subscribe to the same event. This follows the pub/sub pattern where publishers broadcast events and consumers subscribe to receive them.

Type Parameters

Type ParameterDefault typeDescription
TMessage extends MessageDefinition-The message definition
TExchange extends ExchangeDefinition-The exchange definition
TRoutingKey extends string | undefinedundefinedThe routing key type (undefined for fanout)

Properties

PropertyTypeDescriptionDefined in
__brand"EventPublisherConfig"Discriminator to identify this as an event publisher configbuilder/event.ts:36
arguments?Record<string, unknown>Additional AMQP argumentsbuilder/event.ts:44
exchangeTExchangeThe exchange to publish tobuilder/event.ts:38
messageTMessageThe message definitionbuilder/event.ts:40
routingKeyTRoutingKeyThe routing key for direct/topic exchangesbuilder/event.ts:42

EventPublisherConfigBase

ts
type EventPublisherConfigBase = object;

Defined in: types.ts:914

Base type for event publisher configuration.

This is a simplified type used in ContractDefinition. The full generic type is defined in the builder module.

See

defineEventPublisher for creating event publishers

Properties

PropertyTypeDefined in
__brand"EventPublisherConfig"types.ts:915
arguments?Record<string, unknown>types.ts:919
exchangeExchangeDefinitiontypes.ts:916
messageMessageDefinitiontypes.ts:917
routingKeystring | undefinedtypes.ts:918

ExchangeBindingDefinition

ts
type ExchangeBindingDefinition = object & 
  | {
  routingKey: string;
  source:   | DirectExchangeDefinition
     | TopicExchangeDefinition;
}
  | {
  routingKey?: never;
  source: FanoutExchangeDefinition;
};

Defined in: types.ts:797

Binding between two exchanges (exchange-to-exchange routing).

Defines how messages should be forwarded from a source exchange to a destination exchange. This allows for more complex routing topologies.

Type Declaration

NameTypeDescriptionDefined in
arguments?Record<string, unknown>Additional AMQP arguments for the binding.types.ts:807
destinationExchangeDefinitionThe destination exchange that will receive forwarded messagestypes.ts:802
type"exchange"Discriminator indicating this is an exchange-to-exchange bindingtypes.ts:799

Example

typescript
// Forward high-priority orders to a special processing exchange
const binding: ExchangeBindingDefinition = {
  type: 'exchange',
  source: ordersExchange,
  destination: highPriorityExchange,
  routingKey: 'order.high-priority.*'
};

ExchangeDefinition

ts
type ExchangeDefinition<TName> = 
  | FanoutExchangeDefinition<TName>
  | DirectExchangeDefinition<TName>
  | TopicExchangeDefinition<TName>;

Defined in: types.ts:471

Union type of all exchange definitions.

Represents any type of AMQP exchange: fanout, direct, or topic.

Type Parameters

Type ParameterDefault type
TName extends stringstring

FanoutExchangeDefinition

ts
type FanoutExchangeDefinition<TName> = BaseExchangeDefinition<TName> & object;

Defined in: types.ts:421

A fanout exchange definition.

Fanout exchanges broadcast all messages to all bound queues, ignoring routing keys. This is the simplest exchange type for pub/sub messaging patterns.

Type Declaration

NameTypeDefined in
type"fanout"types.ts:423

Type Parameters

Type ParameterDefault type
TName extends stringstring

Example

typescript
const logsExchange: FanoutExchangeDefinition = defineExchange('logs', 'fanout', {
  durable: true
});

InferConsumerNames

ts
type InferConsumerNames<TContract> = TContract["consumers"] extends Record<string, unknown> ? keyof TContract["consumers"] : never;

Defined in: types.ts:1491

Extract consumer names from a contract.

This utility type extracts the keys of all consumers defined in a contract. It's used internally for type inference in the TypedAmqpWorker.

Type Parameters

Type ParameterDescription
TContract extends ContractDefinitionThe contract definition

Returns

Union of consumer names, or never if no consumers defined

Example

typescript
type ConsumerNames = InferConsumerNames<typeof myContract>;
// Result: 'processOrder' | 'sendNotification' | 'updateInventory'

InferPublisherNames

ts
type InferPublisherNames<TContract> = TContract["publishers"] extends Record<string, unknown> ? keyof TContract["publishers"] : never;

Defined in: types.ts:1473

Extract publisher names from a contract.

This utility type extracts the keys of all publishers defined in a contract. It's used internally for type inference in the TypedAmqpClient.

Type Parameters

Type ParameterDescription
TContract extends ContractDefinitionThe contract definition

Returns

Union of publisher names, or never if no publishers defined

Example

typescript
type PublisherNames = InferPublisherNames<typeof myContract>;
// Result: 'orderCreated' | 'orderUpdated' | 'orderCancelled'

MatchingRoutingKey

ts
type MatchingRoutingKey<Pattern, Key> = RoutingKey<Key> extends never ? never : BindingPattern<Pattern> extends never ? never : MatchesPattern<Key, Pattern> extends true ? Key : never;

Defined in: builder/routing-types.ts:114

Validate that a routing key matches a binding pattern.

This is a utility type provided for users who want compile-time validation that a routing key matches a specific pattern. It's not enforced internally in the API to avoid TypeScript recursion depth issues with complex routing keys.

Returns the routing key if it's valid and matches the pattern, never otherwise.

Type Parameters

Type ParameterDescription
Pattern extends stringThe binding pattern (can contain * and # wildcards)
Key extends stringThe routing key to validate

Example

typescript
type ValidKey = MatchingRoutingKey<"order.*", "order.created">; // "order.created"
type InvalidKey = MatchingRoutingKey<"order.*", "user.created">; // never

MessageDefinition

ts
type MessageDefinition<TPayload, THeaders> = object;

Defined in: types.ts:711

Definition of a message with typed payload and optional headers.

Type Parameters

Type ParameterDefault typeDescription
TPayload extends AnySchemaAnySchemaThe Standard Schema v1 compatible schema for the message payload
THeaders extends | StandardSchemaV1<Record<string, unknown>> | undefined| StandardSchemaV1<Record<string, unknown>> | undefinedThe Standard Schema v1 compatible schema for the message headers (optional)

Properties

PropertyTypeDescriptionDefined in
description?stringDetailed description of the message for documentation purposes. Used in AsyncAPI specification generation.types.ts:739
headers?THeadersOptional headers schema for validating message metadata. Must be a Standard Schema v1 compatible schema.types.ts:727
payloadTPayloadThe payload schema for validating message content. Must be a Standard Schema v1 compatible schema (Zod, Valibot, ArkType, etc.).types.ts:721
summary?stringBrief description of the message for documentation purposes. Used in AsyncAPI specification generation.types.ts:733

PublisherDefinition

ts
type PublisherDefinition<TMessage> = object & 
  | {
  exchange:   | DirectExchangeDefinition
     | TopicExchangeDefinition;
  routingKey: string;
}
  | {
  exchange: FanoutExchangeDefinition;
  routingKey?: never;
};

Defined in: types.ts:855

Definition of a message publisher.

A publisher sends messages to an exchange with automatic schema validation. The message payload is validated against the schema before being sent to RabbitMQ.

Compression can be optionally applied at publish time by specifying a compression algorithm when calling the publish method.

Type Declaration

NameTypeDescriptionDefined in
messageTMessageThe message definition including the payload schematypes.ts:857

Type Parameters

Type ParameterDefault typeDescription
TMessage extends MessageDefinitionMessageDefinitionThe message definition with payload schema

Example

typescript
const publisher: PublisherDefinition = {
  exchange: ordersExchange,
  message: orderMessage,
  routingKey: 'order.created'
};

PublisherEntry

ts
type PublisherEntry = 
  | PublisherDefinition
  | EventPublisherConfigBase
  | BridgedPublisherConfigBase;

Defined in: types.ts:1053

Publisher entry that can be passed to defineContract's publishers section.

Can be either:

  • A plain PublisherDefinition from definePublisher
  • An EventPublisherConfig from defineEventPublisher (auto-extracted to publisher)

QueueBindingDefinition

ts
type QueueBindingDefinition = object & 
  | {
  exchange:   | DirectExchangeDefinition
     | TopicExchangeDefinition;
  routingKey: string;
}
  | {
  exchange: FanoutExchangeDefinition;
  routingKey?: never;
};

Defined in: types.ts:749

Binding between a queue and an exchange.

Defines how messages from an exchange should be routed to a queue. For direct and topic exchanges, a routing key is required. For fanout exchanges, no routing key is needed as all messages are broadcast.

Type Declaration

NameTypeDescriptionDefined in
arguments?Record<string, unknown>Additional AMQP arguments for the binding. Can be used for advanced routing scenarios with the headers exchange type.types.ts:760
queueQueueDefinitionThe queue that will receive messagestypes.ts:754
type"queue"Discriminator indicating this is a queue-to-exchange bindingtypes.ts:751

QueueDefinition

ts
type QueueDefinition<TName> = 
  | QuorumQueueDefinition<TName>
  | ClassicQueueDefinition<TName>;

Defined in: types.ts:632

Definition of an AMQP queue.

A discriminated union based on queue type:

  • QuorumQueueDefinition: For quorum queues (type: "quorum")
  • ClassicQueueDefinition: For classic queues (type: "classic")

Use queue.type as the discriminator to narrow the type.

Type Parameters

Type ParameterDefault type
TName extends stringstring

QueueEntry

ts
type QueueEntry<TName> = 
  | QueueDefinition<TName>
  | QueueWithTtlBackoffInfrastructure<TName>;

Defined in: types.ts:701

A queue entry that can be passed to defineContract.

Can be either a plain queue definition or a queue with TTL-backoff infrastructure.

Type Parameters

Type ParameterDefault type
TName extends stringstring

QueueType

ts
type QueueType = "quorum" | "classic";

Defined in: types.ts:163

Supported queue types in RabbitMQ.

  • quorum: Quorum queues (default, recommended) - Provide better durability and high-availability using the Raft consensus algorithm. Best for most production use cases.
  • classic: Classic queues - The traditional RabbitMQ queue type. Use only when you need specific features not supported by quorum queues (e.g., non-durable queues, priority queues).

Note: Quorum queues require durable: true and do not support exclusive: true. When using quorum queues, durable is automatically set to true.

See

https://www.rabbitmq.com/docs/quorum-queues

Example

typescript
// Create a quorum queue (default, recommended)
const orderQueue = defineQueue('order-processing', {
  type: 'quorum', // This is the default
});

// Create a classic queue (for special cases)
const tempQueue = defineQueue('temp-queue', {
  type: 'classic',
  durable: false, // Only supported with classic queues
});

QueueWithTtlBackoffInfrastructure

ts
type QueueWithTtlBackoffInfrastructure<TName> = object;

Defined in: types.ts:662

A queue with automatically generated TTL-backoff retry infrastructure.

This type is returned by defineQueue when TTL-backoff retry is configured with a dead letter exchange. When passed to defineContract, the wait queue and bindings are automatically added to the contract.

Example

typescript
const dlx = defineExchange('orders-dlx', 'direct', { durable: true });
const exchange = defineExchange('orders', 'topic', { durable: true });
const queue = defineQueue('order-processing', {
  deadLetter: { exchange: dlx },
  retry: { mode: 'ttl-backoff', maxRetries: 5 },
});
// queue is QueueWithTtlBackoffInfrastructure
const message = defineMessage(z.object({ orderId: z.string() }));
const orderCreated = defineEventPublisher(exchange, message, { routingKey: 'order.created' });

// Wait queue, bindings, and DLX exchange are automatically extracted
const contract = defineContract({
  publishers: { orderCreated },
  consumers: { processOrder: defineEventConsumer(orderCreated, extractQueue(queue)) },
});

Type Parameters

Type ParameterDefault type
TName extends stringstring

Properties

PropertyTypeDescriptionDefined in
deadLetterDeadLetterConfigDead letter configuration from the main queue. Always present since TTL-backoff infrastructure requires a dead letter exchange.types.ts:678
mainQueueRetryBindingQueueBindingDefinitionBinding that routes retried messages back to the main queue.types.ts:693
queueQueueDefinition<TName>The main queue definition.types.ts:672
waitQueueQueueDefinitionThe wait queue for holding messages during backoff delay.types.ts:683
waitQueueBindingQueueBindingDefinitionBinding that routes failed messages to the wait queue.types.ts:688

QuorumNativeRetryOptions

ts
type QuorumNativeRetryOptions = object;

Defined in: types.ts:72

Quorum-Native retry options using RabbitMQ's native delivery limit feature.

Uses quorum queue's x-delivery-limit feature. Messages are requeued immediately with nack(requeue=true), and RabbitMQ tracks delivery count via x-delivery-count header. When the count exceeds the queue's deliveryLimit, the message is automatically dead-lettered.

Benefits: Simpler architecture, no wait queues needed, no head-of-queue blocking. Limitation: Immediate retries only (no exponential backoff).

See

https://www.rabbitmq.com/docs/quorum-queues#poison-message-handling

Properties

PropertyTypeDescriptionDefined in
mode"quorum-native"Quorum-Native mode uses RabbitMQ's native delivery limit feature. Requires the queue to be a quorum queue with deliveryLimit configured.types.ts:77

QuorumQueueDefinition

ts
type QuorumQueueDefinition<TName> = BaseQueueDefinition<TName> & object;

Defined in: types.ts:545

Definition of a quorum queue.

Quorum queues provide better durability and high-availability using the Raft consensus algorithm. They support native retry handling via deliveryLimit and both TTL-backoff and quorum-native retry modes.

Type Declaration

NameTypeDescriptionDefined in
deliveryLimit?numberMaximum number of delivery attempts before the message is dead-lettered. This is a quorum queue-specific feature. When a message is rejected (nacked) and requeued, RabbitMQ increments the x-delivery-count header. When this count reaches the delivery limit, the message is automatically dead-lettered (if DLX is configured) or dropped. Minimum 1 - Must be a positive integer (1 or greater) See https://www.rabbitmq.com/docs/quorum-queues#poison-message-handlingtypes.ts:575
exclusive?neverQuorum queues do not support exclusive mode. Use type: 'classic' if you need exclusive queues.types.ts:555
maxPriority?neverQuorum queues do not support priority queues. Use type: 'classic' if you need priority queues.types.ts:561
retryResolvedRetryOptionsRetry configuration for handling failed message processing. Quorum queues support both: - ttl-backoff: Uses wait queues with exponential backoff (default) - quorum-native: Uses RabbitMQ's native delivery limit feature When the queue is created, defaults are applied for TTL-backoff options.types.ts:586
type"quorum"Queue type discriminator: quorum queue.types.ts:549

Type Parameters

Type ParameterDefault type
TName extends stringstring

QuorumQueueOptions

ts
type QuorumQueueOptions = BaseQueueOptions & object;

Defined in: types.ts:214

Options for creating a quorum queue.

Quorum queues do not support:

  • exclusive - Use classic queues for exclusive access
  • maxPriority - Use classic queues for priority queues

Quorum queues provide native retry support via deliveryLimit:

  • RabbitMQ tracks delivery count automatically via x-delivery-count header
  • When the limit is exceeded, messages are dead-lettered (if DLX is configured)
  • This is simpler than TTL-based retry and avoids head-of-queue blocking issues

Type Declaration

NameTypeDescriptionDefined in
deliveryLimit?numberMaximum number of delivery attempts before the message is dead-lettered. When a message is rejected (nacked) and requeued, RabbitMQ increments the x-delivery-count header. When this count reaches the delivery limit, the message is automatically dead-lettered (if DLX is configured) or dropped. This is a quorum queue-specific feature that provides native retry handling without the complexity of TTL-based wait queues. Benefits over TTL-based retry: - Simpler architecture (no wait queues needed) - No head-of-queue blocking issues (TTL only works at queue head) - Native RabbitMQ feature with atomic guarantees Minimum 1 - Must be a positive integer (1 or greater) See https://www.rabbitmq.com/docs/quorum-queues#poison-message-handling Example const orderQueue = defineQueue('order-processing', { type: 'quorum', deliveryLimit: 5, // Allow up to 5 delivery attempts deadLetter: { exchange: dlx, routingKey: 'order.failed', }, });types.ts:263
exclusive?neverQuorum queues do not support exclusive mode. Use type: 'classic' if you need exclusive queues.types.ts:224
maxPriority?neverQuorum queues do not support priority queues. Use type: 'classic' if you need priority queues.types.ts:230
retry?| TtlBackoffRetryOptions | QuorumNativeRetryOptionsRetry configuration for handling failed message processing. Determines how the worker handles retries for consumers using this queue: - "ttl-backoff" (default): Uses wait queues with exponential backoff - "quorum-native": Uses RabbitMQ's native delivery limit feature When using "ttl-backoff" mode, the core package will automatically create a wait queue ({queueName}-wait) and the necessary bindings. Example // TTL-backoff mode with custom options const orderQueue = defineQueue('order-processing', { type: 'quorum', deadLetter: { exchange: dlx }, retry: { mode: 'ttl-backoff', maxRetries: 5, initialDelayMs: 1000, maxDelayMs: 30000, }, }); // Quorum-native mode const orderQueue = defineQueue('order-processing', { type: 'quorum', deliveryLimit: 5, deadLetter: { exchange: dlx }, retry: { mode: 'quorum-native' }, });types.ts:298
type?"quorum"Queue type: quorum (default, recommended)types.ts:218

Example

typescript
const orderQueue = defineQueue('orders', {
  type: 'quorum',
  deadLetter: { exchange: dlx },
  deliveryLimit: 3, // Message dead-lettered after 3 delivery attempts
});

ResolvedRetryOptions

ts
type ResolvedRetryOptions = 
  | ResolvedTtlBackoffRetryOptions
  | QuorumNativeRetryOptions;

Defined in: types.ts:104

Resolved retry configuration stored in queue definitions.

This is a discriminated union based on the mode field:

  • ttl-backoff: Has all TTL-backoff options with defaults applied
  • quorum-native: No additional options (uses RabbitMQ native retry)

RoutingKey

ts
type RoutingKey<S> = S extends "" ? never : S extends `${string}*${string}` | `${string}#${string}` ? never : S;

Defined in: builder/routing-types.ts:25

Type-safe routing key that validates basic format.

Validates that a routing key follows basic AMQP routing key rules:

  • Must not contain wildcards (* or #)
  • Must not be empty
  • Should contain alphanumeric characters, dots, hyphens, and underscores

Note: Full character-by-character validation is not performed to avoid TypeScript recursion depth limits. Runtime validation is still recommended.

Type Parameters

Type ParameterDescription
S extends stringThe routing key string to validate

Example

typescript
type Valid = RoutingKey<"order.created">; // "order.created"
type Invalid = RoutingKey<"order.*">; // never (contains wildcard)
type Invalid2 = RoutingKey<"">; // never (empty string)

TopicExchangeDefinition

ts
type TopicExchangeDefinition<TName> = BaseExchangeDefinition<TName> & object;

Defined in: types.ts:461

A topic exchange definition.

Topic exchanges route messages to queues based on routing key patterns with wildcards:

  • * (star) matches exactly one word
  • # (hash) matches zero or more words

Words are separated by dots (e.g., order.created.high-value).

Type Declaration

NameTypeDefined in
type"topic"types.ts:463

Type Parameters

Type ParameterDefault type
TName extends stringstring

Example

typescript
const ordersExchange: TopicExchangeDefinition = defineExchange('orders', 'topic', {
  durable: true
});
// Can be bound with patterns like 'order.*' or 'order.#'

TtlBackoffRetryInfrastructure

ts
type TtlBackoffRetryInfrastructure = object;

Defined in: builder/ttl-backoff.ts:9

Result type for TTL-backoff retry infrastructure builder.

Contains the wait queue and bindings needed for TTL-backoff retry.

Properties

PropertyTypeDescriptionDefined in
mainQueueRetryBindingQueueBindingDefinitionBinding that routes retried messages back to the main queue.builder/ttl-backoff.ts:22
waitQueueQueueDefinitionThe wait queue for holding messages during backoff delay. This is a classic queue with a dead letter exchange pointing back to the main queue.builder/ttl-backoff.ts:14
waitQueueBindingQueueBindingDefinitionBinding that routes failed messages to the wait queue.builder/ttl-backoff.ts:18

TtlBackoffRetryOptions

ts
type TtlBackoffRetryOptions = object;

Defined in: types.ts:27

TTL-Backoff retry options for exponential backoff with configurable delays.

Uses TTL + wait queue pattern. Messages are published to a wait queue with per-message TTL, then dead-lettered back to the main queue after the TTL expires.

Benefits: Configurable delays with exponential backoff and jitter. Limitation: More complex, potential head-of-queue blocking with mixed TTLs.

Properties

PropertyTypeDescriptionDefined in
backoffMultiplier?numberExponential backoff multiplier. Default 2types.ts:51
initialDelayMs?numberInitial delay in ms before first retry. Default 1000types.ts:41
jitter?booleanAdd jitter to prevent thundering herd. Default truetypes.ts:56
maxDelayMs?numberMaximum delay in ms between retries. Default 30000types.ts:46
maxRetries?numberMaximum retry attempts before sending to DLQ. Default 3types.ts:36
mode"ttl-backoff"TTL-Backoff mode uses wait queues with per-message TTL for exponential backoff.types.ts:31

Functions

defineConsumer()

ts
function defineConsumer<TMessage>(
   queue, 
   message, 
   options?): ConsumerDefinition<TMessage>;

Defined in: builder/consumer.ts:121

Define a message consumer.

A consumer receives and processes messages from a queue. The message schema is validated automatically when messages are consumed, ensuring type safety for your handlers.

Consumers are associated with a specific queue and message type. When you create a worker with this consumer, it will process messages from the queue according to the schema.

Which pattern to use:

PatternBest forDescription
definePublisher + defineConsumerIndependent definitionDefine publishers and consumers separately with manual schema consistency
defineEventPublisher + defineEventConsumerEvent broadcastingDefine event publisher first, create consumers that subscribe to it
defineCommandConsumer + defineCommandPublisherTask queuesDefine command consumer first, create publishers that send commands to it

Use defineCommandConsumer when:

  • One consumer receives from multiple publishers
  • You want automatic schema consistency between consumer and publishers
  • You're building task queue or command patterns

Type Parameters

Type Parameter
TMessage extends MessageDefinition

Parameters

ParameterTypeDescription
queueQueueEntryThe queue definition to consume from
messageTMessageThe message definition with payload schema
options?Omit<ConsumerDefinition<TMessage>, "queue" | "message">Optional consumer configuration

Returns

ConsumerDefinition<TMessage>

A consumer definition with inferred message types

Example

typescript
import { z } from 'zod';

const orderQueue = defineQueue('order-processing', { durable: true });
const orderMessage = defineMessage(
  z.object({
    orderId: z.string().uuid(),
    customerId: z.string().uuid(),
    amount: z.number().positive(),
  })
);

const processOrderConsumer = defineConsumer(orderQueue, orderMessage);

// Later, when creating a worker, you'll provide a handler for this consumer:
// const worker = await TypedAmqpWorker.create({
//   contract,
//   handlers: {
//     processOrder: async (message) => {
//       // message is automatically typed based on the schema
//       console.log(message.orderId); // string
//     }
//   },
//   connection
// });

See

  • defineCommandConsumer - For task queue patterns with automatic schema consistency
  • defineEventPublisher - For event-driven patterns with automatic schema consistency

defineContract()

ts
function defineContract<TContract>(definition): ContractOutput<TContract>;

Defined in: builder/contract.ts:82

Define an AMQP contract.

A contract is the central definition of your AMQP messaging topology. It brings together publishers and consumers in a single, type-safe definition. Exchanges, queues, and bindings are automatically extracted from publishers and consumers.

The contract is used by both clients (for publishing) and workers (for consuming) to ensure type safety throughout your messaging infrastructure. TypeScript will infer all message types and publisher/consumer names from the contract.

Type Parameters

Type Parameter
TContract extends ContractDefinitionInput

Parameters

ParameterTypeDescription
definitionTContractThe contract definition containing publishers and consumers

Returns

ContractOutput<TContract>

The contract definition with fully inferred exchanges, queues, bindings, publishers, and consumers

Example

typescript
import {
  defineContract,
  defineExchange,
  defineQueue,
  defineEventPublisher,
  defineEventConsumer,
  defineMessage,
} from '@amqp-contract/contract';
import { z } from 'zod';

// Define resources
const ordersExchange = defineExchange('orders', 'topic', { durable: true });
const dlx = defineExchange('orders-dlx', 'direct', { durable: true });
const orderQueue = defineQueue('order-processing', {
  deadLetter: { exchange: dlx },
  retry: { mode: 'quorum-native' },
  deliveryLimit: 3,
});
const orderMessage = defineMessage(
  z.object({
    orderId: z.string(),
    amount: z.number(),
  })
);

// Define event publisher
const orderCreatedEvent = defineEventPublisher(ordersExchange, orderMessage, {
  routingKey: 'order.created',
});

// Compose contract - exchanges, queues, bindings are auto-extracted
export const contract = defineContract({
  publishers: {
    orderCreated: orderCreatedEvent,
  },
  consumers: {
    processOrder: defineEventConsumer(orderCreatedEvent, orderQueue),
  },
});

// TypeScript now knows:
// - contract.exchanges.orders, contract.exchanges['orders-dlx']
// - contract.queues['order-processing']
// - contract.bindings.processOrderBinding
// - client.publish('orderCreated', { orderId: string, amount: number })
// - handler: (message: { orderId: string, amount: number }) => Future<Result<void, HandlerError>>

defineMessage()

ts
function defineMessage<TPayload, THeaders>(payload, options?): MessageDefinition<TPayload, THeaders>;

Defined in: builder/message.ts:39

Define a message definition with payload and optional headers/metadata.

A message definition specifies the schema for message payloads and headers using Standard Schema v1 compatible libraries (Zod, Valibot, ArkType, etc.). The schemas are used for automatic validation when publishing or consuming messages.

Type Parameters

Type ParameterDefault type
TPayload extends AnySchema-
THeaders extends | StandardSchemaV1<Record<string, unknown>, Record<string, unknown>> | undefinedundefined

Parameters

ParameterTypeDescription
payloadTPayloadThe payload schema (must be Standard Schema v1 compatible)
options?{ description?: string; headers?: THeaders; summary?: string; }Optional message metadata
options.description?stringDetailed description for documentation (used in AsyncAPI generation)
options.headers?THeadersOptional header schema for message headers
options.summary?stringBrief description for documentation (used in AsyncAPI generation)

Returns

MessageDefinition<TPayload, THeaders>

A message definition with inferred types

Example

typescript
import { z } from 'zod';

const orderMessage = defineMessage(
  z.object({
    orderId: z.string().uuid(),
    customerId: z.string().uuid(),
    amount: z.number().positive(),
    items: z.array(z.object({
      productId: z.string(),
      quantity: z.number().int().positive(),
    })),
  }),
  {
    summary: 'Order created event',
    description: 'Emitted when a new order is created in the system'
  }
);

defineQueue()

Call Signature

ts
function defineQueue<TName, TDlx>(name, options): QueueDefinition<TName> | QueueWithTtlBackoffInfrastructure<TName> & object;

Defined in: builder/queue.ts:255

Define an AMQP queue.

A queue stores messages until they are consumed by workers. Queues can be bound to exchanges to receive messages based on routing rules.

By default, queues are created as quorum queues which provide better durability and high-availability. Use type: 'classic' for special cases like non-durable queues or priority queues.

Type Parameters
Type Parameter
TName extends string
TDlx extends ExchangeDefinition
Parameters
ParameterTypeDescription
nameTNameThe name of the queue
optionsDefineQueueOptions & objectOptional queue configuration
Returns

QueueDefinition<TName> | QueueWithTtlBackoffInfrastructure<TName> & object

A queue definition

Example
typescript
// Quorum queue (default, recommended for production)
const orderQueue = defineQueue('order-processing');

// Explicit quorum queue with dead letter exchange
const dlx = defineExchange('orders-dlx', 'topic', { durable: true });
const orderQueueWithDLX = defineQueue('order-processing', {
  type: 'quorum',
  deadLetter: {
    exchange: dlx,
    routingKey: 'order.failed'
  },
  arguments: {
    'x-message-ttl': 86400000, // 24 hours
  }
});

// Classic queue (for special cases)
const tempQueue = defineQueue('temp-queue', {
  type: 'classic',
  durable: false,
  autoDelete: true,
});

// Priority queue (requires classic type)
const taskQueue = defineQueue('urgent-tasks', {
  type: 'classic',
  durable: true,
  maxPriority: 10,
});

// Queue with TTL-backoff retry (returns infrastructure automatically)
const dlx = defineExchange('orders-dlx', 'direct', { durable: true });
const orderQueue = defineQueue('order-processing', {
  deadLetter: { exchange: dlx },
  retry: { mode: 'ttl-backoff', maxRetries: 5 },
});
// orderQueue is QueueWithTtlBackoffInfrastructure, pass directly to defineContract

Call Signature

ts
function defineQueue<TName>(name, options?): 
  | QueueDefinition<TName>
  | QueueWithTtlBackoffInfrastructure<TName>;

Defined in: builder/queue.ts:262

Define an AMQP queue.

A queue stores messages until they are consumed by workers. Queues can be bound to exchanges to receive messages based on routing rules.

By default, queues are created as quorum queues which provide better durability and high-availability. Use type: 'classic' for special cases like non-durable queues or priority queues.

Type Parameters
Type Parameter
TName extends string
Parameters
ParameterTypeDescription
nameTNameThe name of the queue
options?DefineQueueOptionsOptional queue configuration
Returns

| QueueDefinition<TName> | QueueWithTtlBackoffInfrastructure<TName>

A queue definition

Example
typescript
// Quorum queue (default, recommended for production)
const orderQueue = defineQueue('order-processing');

// Explicit quorum queue with dead letter exchange
const dlx = defineExchange('orders-dlx', 'topic', { durable: true });
const orderQueueWithDLX = defineQueue('order-processing', {
  type: 'quorum',
  deadLetter: {
    exchange: dlx,
    routingKey: 'order.failed'
  },
  arguments: {
    'x-message-ttl': 86400000, // 24 hours
  }
});

// Classic queue (for special cases)
const tempQueue = defineQueue('temp-queue', {
  type: 'classic',
  durable: false,
  autoDelete: true,
});

// Priority queue (requires classic type)
const taskQueue = defineQueue('urgent-tasks', {
  type: 'classic',
  durable: true,
  maxPriority: 10,
});

// Queue with TTL-backoff retry (returns infrastructure automatically)
const dlx = defineExchange('orders-dlx', 'direct', { durable: true });
const orderQueue = defineQueue('order-processing', {
  deadLetter: { exchange: dlx },
  retry: { mode: 'ttl-backoff', maxRetries: 5 },
});
// orderQueue is QueueWithTtlBackoffInfrastructure, pass directly to defineContract

defineQuorumQueue()

ts
function defineQuorumQueue<TName>(name, options): QuorumQueueDefinition<TName>;

Defined in: builder/queue.ts:460

Create a quorum queue with quorum-native retry.

This is a simplified helper that enforces best practices:

  • Uses quorum queues (recommended for most use cases)
  • Requires dead letter exchange for failed message handling
  • Uses quorum-native retry mode (simpler than TTL-backoff)

When to use:

  • You want simple, immediate retries without exponential backoff
  • You don't need configurable delays between retries
  • You want the simplest retry configuration

Type Parameters

Type Parameter
TName extends string

Parameters

ParameterTypeDescription
nameTNameThe queue name
optionsDefineQuorumQueueOptionsConfiguration options

Returns

QuorumQueueDefinition<TName>

A quorum queue definition with quorum-native retry

Example

typescript
const dlx = defineExchange('orders-dlx', 'direct', { durable: true });

const orderQueue = defineQuorumQueue('order-processing', {
  deadLetter: { exchange: dlx },
  deliveryLimit: 3, // Retry up to 3 times
});

// Use in a contract — exchanges, queues, and bindings are auto-extracted
const contract = defineContract({
  publishers: { ... },
  consumers: { processOrder: defineEventConsumer(event, orderQueue) },
});

See

  • defineQueue - For full queue configuration options
  • defineTtlBackoffQueue - For queues with exponential backoff retry

defineTtlBackoffQueue()

ts
function defineTtlBackoffQueue<TName>(name, options): QueueWithTtlBackoffInfrastructure<TName>;

Defined in: builder/queue.ts:583

Create a queue with TTL-backoff retry (exponential backoff).

This is a simplified helper that enforces best practices:

  • Uses quorum queues (recommended for most use cases)
  • Requires dead letter exchange for retry routing
  • Uses TTL-backoff retry mode with configurable delays
  • Automatically generates wait queue and bindings

When to use:

  • You need exponential backoff between retries
  • You want configurable delays (initial delay, max delay, jitter)
  • You're processing messages that may need time before retry

Returns: A QueueWithTtlBackoffInfrastructure object that includes the main queue, wait queue, and bindings. Pass this directly to defineContract and it will be expanded automatically.

Type Parameters

Type Parameter
TName extends string

Parameters

ParameterTypeDescription
nameTNameThe queue name
optionsDefineTtlBackoffQueueOptionsConfiguration options

Returns

QueueWithTtlBackoffInfrastructure<TName>

A queue with TTL-backoff infrastructure

Example

typescript
const dlx = defineExchange('orders-dlx', 'direct', { durable: true });

const orderQueue = defineTtlBackoffQueue('order-processing', {
  deadLetter: { exchange: dlx },
  maxRetries: 5,
  initialDelayMs: 1000,  // Start with 1s delay
  maxDelayMs: 30000,     // Cap at 30s
});

// Use in a contract — wait queue, bindings, and DLX are auto-extracted
const contract = defineContract({
  publishers: { ... },
  consumers: { processOrder: defineEventConsumer(event, extractQueue(orderQueue)) },
});

// To access the underlying queue definition (e.g., for the queue name):
import { extractQueue } from '@amqp-contract/contract';
const queueName = extractQueue(orderQueue).name;

See

  • defineQueue - For full queue configuration options
  • defineQuorumQueue - For queues with quorum-native retry (simpler, immediate retries)
  • extractQueue - To access the underlying queue definition

defineTtlBackoffRetryInfrastructure()

ts
function defineTtlBackoffRetryInfrastructure(queueEntry, options?): TtlBackoffRetryInfrastructure;

Defined in: builder/ttl-backoff.ts:67

Create TTL-backoff retry infrastructure for a queue.

This builder helper generates the wait queue and bindings needed for TTL-backoff retry. The generated infrastructure can be spread into a contract definition.

TTL-backoff retry works by:

  1. Failed messages are sent to the DLX with routing key {queueName}-wait
  2. The wait queue receives these messages and holds them for a TTL period
  3. After TTL expires, messages are dead-lettered back to the DLX with routing key {queueName}
  4. The main queue receives the retried message via its binding to the DLX

Parameters

ParameterTypeDescription
queueEntryQueueEntry-
options?{ waitQueueDurable?: boolean; }Optional configuration for the wait queue
options.waitQueueDurable?booleanWhether the wait queue should be durable (default: same as main queue)

Returns

TtlBackoffRetryInfrastructure

TTL-backoff retry infrastructure containing wait queue and bindings

Throws

If the queue does not have a dead letter exchange configured

Example

typescript
const dlx = defineExchange('orders-dlx', 'direct', { durable: true });
const orderQueue = defineQueue('order-processing', {
  type: 'quorum',
  deadLetter: { exchange: dlx },
  retry: {
    mode: 'ttl-backoff',
    maxRetries: 5,
    initialDelayMs: 1000,
  },
});

// Infrastructure is auto-extracted when using defineContract:
const contract = defineContract({
  publishers: { ... },
  consumers: { processOrder: defineEventConsumer(event, extractQueue(orderQueue)) },
});
// contract.queues includes the wait queue, contract.bindings includes retry bindings

// Or generate manually for advanced use cases:
const retryInfra = defineTtlBackoffRetryInfrastructure(orderQueue);

extractConsumer()

ts
function extractConsumer(entry): ConsumerDefinition;

Defined in: builder/consumer.ts:55

Extract the ConsumerDefinition from any ConsumerEntry type.

Handles the following entry types:

  • ConsumerDefinition: returned as-is
  • EventConsumerResult: returns the nested .consumer property
  • CommandConsumerConfig: returns the nested .consumer property

Use this function when you need to access the underlying ConsumerDefinition from a consumer entry that may have been created with defineEventConsumer or defineCommandConsumer.

Parameters

ParameterTypeDescription
entryConsumerEntryThe consumer entry to extract from

Returns

ConsumerDefinition

The underlying ConsumerDefinition

Example

typescript
// Works with plain ConsumerDefinition
const consumer1 = defineConsumer(queue, message);
extractConsumer(consumer1).queue.name; // "my-queue"

// Works with EventConsumerResult
const consumer2 = defineEventConsumer(eventPublisher, queue);
extractConsumer(consumer2).queue.name; // "my-queue"

// Works with CommandConsumerConfig
const consumer3 = defineCommandConsumer(queue, exchange, message, { routingKey: "cmd" });
extractConsumer(consumer3).queue.name; // "my-queue"

extractQueue()

ts
function extractQueue<T>(entry): ExtractQueueFromEntry<T>;

Defined in: builder/queue.ts:127

Extract the plain QueueDefinition from a QueueEntry.

Why this function exists: When you configure a queue with TTL-backoff retry and a dead letter exchange, defineQueue (or defineTtlBackoffQueue) returns a wrapper object that includes the main queue, wait queue, and bindings. This function extracts the underlying queue definition so you can access properties like name, type, etc.

When to use:

  • When you need to access queue properties (name, type, deadLetter, etc.)
  • When passing a queue to functions that expect a plain QueueDefinition
  • Works safely on both plain queues and infrastructure wrappers

How it works:

  • If the entry is a QueueWithTtlBackoffInfrastructure, returns entry.queue
  • Otherwise, returns the entry as-is (it's already a plain QueueDefinition)

Type Parameters

Type Parameter
T extends QueueEntry

Parameters

ParameterTypeDescription
entryTThe queue entry (either plain QueueDefinition or QueueWithTtlBackoffInfrastructure)

Returns

ExtractQueueFromEntry<T>

The plain QueueDefinition

Example

typescript
import { defineQueue, defineTtlBackoffQueue, extractQueue } from '@amqp-contract/contract';

// TTL-backoff queue returns a wrapper
const orderQueue = defineTtlBackoffQueue('orders', {
  deadLetter: { exchange: dlx },
  maxRetries: 3,
});

// Use extractQueue to access the queue name
const queueName = extractQueue(orderQueue).name; // 'orders'

// Also works safely on plain queues
const plainQueue = defineQueue('simple', { type: 'quorum', retry: { mode: 'quorum-native' } });
const plainName = extractQueue(plainQueue).name; // 'simple'

// Access other properties
const queueDef = extractQueue(orderQueue);
console.log(queueDef.name);       // 'orders'
console.log(queueDef.type);       // 'quorum'
console.log(queueDef.deadLetter); // { exchange: dlx, ... }

See

  • isQueueWithTtlBackoffInfrastructure - Type guard to check if extraction is needed
  • defineTtlBackoffQueue - Creates queues with TTL-backoff infrastructure

isBridgedPublisherConfig()

ts
function isBridgedPublisherConfig(value): value is BridgedPublisherConfig<MessageDefinition, ExchangeDefinition, ExchangeDefinition>;

Defined in: builder/command.ts:460

Type guard to check if a value is a BridgedPublisherConfig.

Parameters

ParameterTypeDescription
valueunknownThe value to check

Returns

value is BridgedPublisherConfig<MessageDefinition, ExchangeDefinition, ExchangeDefinition>

True if the value is a BridgedPublisherConfig


isCommandConsumerConfig()

ts
function isCommandConsumerConfig(value): value is CommandConsumerConfig<MessageDefinition, ExchangeDefinition, string | undefined, QueueDefinition, ExchangeDefinition | undefined>;

Defined in: builder/command.ts:443

Type guard to check if a value is a CommandConsumerConfig.

Parameters

ParameterTypeDescription
valueunknownThe value to check

Returns

value is CommandConsumerConfig<MessageDefinition, ExchangeDefinition, string | undefined, QueueDefinition, ExchangeDefinition | undefined>

True if the value is a CommandConsumerConfig


isEventConsumerResult()

ts
function isEventConsumerResult(value): value is EventConsumerResult<MessageDefinition, ExchangeDefinition, QueueDefinition, ExchangeDefinition | undefined, ExchangeBindingDefinition | undefined, ExchangeDefinition | undefined>;

Defined in: builder/event.ts:526

Type guard to check if a value is an EventConsumerResult.

Parameters

ParameterTypeDescription
valueunknownThe value to check

Returns

value is EventConsumerResult<MessageDefinition, ExchangeDefinition, QueueDefinition, ExchangeDefinition | undefined, ExchangeBindingDefinition | undefined, ExchangeDefinition | undefined>

True if the value is an EventConsumerResult


isEventPublisherConfig()

ts
function isEventPublisherConfig(value): value is EventPublisherConfig<MessageDefinition, ExchangeDefinition, string | undefined>;

Defined in: builder/event.ts:509

Type guard to check if a value is an EventPublisherConfig.

Parameters

ParameterTypeDescription
valueunknownThe value to check

Returns

value is EventPublisherConfig<MessageDefinition, ExchangeDefinition, string | undefined>

True if the value is an EventPublisherConfig


isQueueWithTtlBackoffInfrastructure()

ts
function isQueueWithTtlBackoffInfrastructure(entry): entry is QueueWithTtlBackoffInfrastructure;

Defined in: builder/queue.ts:73

Type guard to check if a queue entry is a QueueWithTtlBackoffInfrastructure.

When you configure a queue with TTL-backoff retry and a dead letter exchange, defineQueue returns a QueueWithTtlBackoffInfrastructure instead of a plain QueueDefinition. This type guard helps you distinguish between the two.

When to use:

  • When you need to check the type of a queue entry at runtime
  • When writing generic code that handles both plain queues and infrastructure wrappers

Related functions:

  • extractQueue() - Use this to get the underlying queue definition from either type

Parameters

ParameterTypeDescription
entryQueueEntryThe queue entry to check

Returns

entry is QueueWithTtlBackoffInfrastructure

True if the entry is a QueueWithTtlBackoffInfrastructure, false otherwise

Example

typescript
const queue = defineQueue('orders', {
  deadLetter: { exchange: dlx },
  retry: { mode: 'ttl-backoff' },
});

if (isQueueWithTtlBackoffInfrastructure(queue)) {
  // queue has .queue, .waitQueue, .waitQueueBinding, .mainQueueRetryBinding
  console.log('Wait queue:', queue.waitQueue.name);
} else {
  // queue is a plain QueueDefinition
  console.log('Queue:', queue.name);
}

Released under the MIT License.