@vercel/queue 0.0.0-alpha.2 → 0.0.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -80,8 +80,9 @@ interface QueueClientOptions {
80
80
  /**
81
81
  * Vercel function OIDC token
82
82
  * Can be obtained from x-vercel-oidc-token header in Vercel Serverless Functions
83
+ * If not provided, will automatically attempt to retrieve from Vercel Function environment
83
84
  */
84
- token: string;
85
+ token?: string;
85
86
  }
86
87
  /**
87
88
  * Callback configuration for a consumer group
@@ -100,15 +101,10 @@ interface CallbackConfig {
100
101
  */
101
102
  frequency?: number;
102
103
  }
103
- interface SendMessageOptions<T = unknown> {
104
- /**
105
- * The queue name to send the message to
106
- */
107
- queueName: string;
108
- /**
109
- * The message payload
110
- */
111
- payload: T;
104
+ /**
105
+ * Shared options for publishing messages
106
+ */
107
+ interface PublishOptions {
112
108
  /**
113
109
  * Unique key to prevent duplicate message submissions
114
110
  * @default random UUID
@@ -122,10 +118,21 @@ interface SendMessageOptions<T = unknown> {
122
118
  */
123
119
  retentionSeconds?: number;
124
120
  /**
125
- * Consumer group callback configurations
126
- * Format: { consumerGroup: { url, delay?, frequency? } }
121
+ * Callback configuration
122
+ * - If a single CallbackConfig is provided, it will use the "default" consumer group
123
+ * - If an object is provided, keys are consumer group names with their respective callback configs
127
124
  */
128
- callbacks?: Record<string, CallbackConfig>;
125
+ callback?: Record<string, CallbackConfig> | CallbackConfig;
126
+ }
127
+ interface SendMessageOptions<T = unknown> extends PublishOptions {
128
+ /**
129
+ * The queue name to send the message to
130
+ */
131
+ queueName: string;
132
+ /**
133
+ * The message payload
134
+ */
135
+ payload: T;
129
136
  }
130
137
  interface SendMessageResponse {
131
138
  /**
@@ -248,10 +255,18 @@ interface MessageTimeoutResult {
248
255
  * Result returned by message handlers
249
256
  */
250
257
  type MessageHandlerResult = void | MessageTimeoutResult;
258
+ /**
259
+ * Message metadata provided to handlers
260
+ */
261
+ interface MessageMetadata {
262
+ messageId: string;
263
+ deliveryCount: number;
264
+ timestamp: string;
265
+ }
251
266
  /**
252
267
  * Message handler function type
253
268
  */
254
- type MessageHandler<T = unknown> = (message: Message<T>) => Promise<MessageHandlerResult> | MessageHandlerResult;
269
+ type MessageHandler<T = unknown> = (message: T, metadata: MessageMetadata) => Promise<MessageHandlerResult> | MessageHandlerResult;
255
270
  /**
256
271
  * Options for creating a ConsumerGroup instance
257
272
  */
@@ -300,16 +315,6 @@ interface ReceiveMessageByIdOptions<T = unknown> {
300
315
  interface ReceiveMessageByIdResponse<T = unknown, TSkipPayload extends boolean = false> {
301
316
  message: TSkipPayload extends true ? Message<void> : Message<T>;
302
317
  }
303
- interface FifoOrderingError {
304
- /**
305
- * Error message describing the FIFO ordering violation
306
- */
307
- error: string;
308
- /**
309
- * The message ID that must be processed first
310
- */
311
- nextMessageId: string;
312
- }
313
318
  /**
314
319
  * Error thrown when a message is not found (404)
315
320
  */
@@ -324,11 +329,10 @@ declare class MessageNotAvailableError extends Error {
324
329
  constructor(messageId: string, reason?: string);
325
330
  }
326
331
  /**
327
- * Error thrown when there's a FIFO ordering violation (409 with nextMessageId)
332
+ * Error thrown when there's a FIFO ordering violation (409)
328
333
  */
329
334
  declare class FifoOrderingViolationError extends Error {
330
- readonly nextMessageId: string;
331
- constructor(messageId: string, nextMessageId: string, reason: string);
335
+ constructor(messageId: string, reason: string);
332
336
  }
333
337
  /**
334
338
  * Error thrown when message data is corrupted or can't be parsed
@@ -371,8 +375,7 @@ declare class BadRequestError extends Error {
371
375
  * Error thrown when there's a failed dependency (424) - FIFO ordering violation in receive by ID
372
376
  */
373
377
  declare class FailedDependencyError extends Error {
374
- readonly nextMessageId: string;
375
- constructor(messageId: string, nextMessageId: string);
378
+ constructor(messageId: string);
376
379
  }
377
380
  /**
378
381
  * Error thrown for internal server errors (500)
@@ -416,19 +419,26 @@ declare class InvalidCallbackError extends Error {
416
419
  declare class QueueClient {
417
420
  private baseUrl;
418
421
  private token;
422
+ /**
423
+ * Internal default instance for use by createTopic and other convenience functions
424
+ * @internal
425
+ */
426
+ private static _defaultInstance;
419
427
  /**
420
428
  * Create a new Vercel Queue Service client
421
- * @param options Client configuration options
429
+ * @param options Client configuration options (optional - will auto-detect Vercel Function environment)
422
430
  */
423
- constructor(options: QueueClientOptions);
431
+ constructor(options?: QueueClientOptions);
424
432
  /**
425
- * Create a QueueClient automatically configured for Vercel Functions
426
- * This method automatically retrieves the OIDC token from the Vercel Function environment
427
- * Always creates a fresh instance since OIDC tokens expire after 15 minutes
428
- * @param baseUrl Optional base URL override
429
- * @returns Promise resolving to a new QueueClient instance
433
+ * Get the default client instance for internal use by convenience functions
434
+ * @internal
430
435
  */
431
- static fromVercelFunction(baseUrl?: string): Promise<QueueClient>;
436
+ static _getDefaultInstance(): QueueClient;
437
+ /**
438
+ * Synchronously get OIDC token from environment
439
+ * Used internally by constructor - mirrors the logic from getVercelOidcToken but synchronously
440
+ */
441
+ private getVercelOidcTokenSync;
432
442
  /**
433
443
  * Send a message to a queue
434
444
  * @param options Send message options
@@ -463,7 +473,6 @@ declare class QueueClient {
463
473
  * @throws {MessageLockedError} When the message is temporarily locked (423)
464
474
  * @throws {FailedDependencyError} When FIFO ordering is violated (424)
465
475
  * @throws {MessageNotAvailableError} When message exists but isn't available (409)
466
- * @throws {FifoOrderingViolationError} When FIFO ordering is violated (409 with nextMessageId)
467
476
  * @throws {MessageCorruptedError} When message data is corrupted
468
477
  * @throws {BadRequestError} When request parameters are invalid
469
478
  * @throws {UnauthorizedError} When authentication fails
@@ -502,6 +511,15 @@ declare class QueueClient {
502
511
  changeVisibility(options: ChangeVisibilityOptions): Promise<ChangeVisibilityResponse>;
503
512
  }
504
513
 
514
+ /**
515
+ * Options for the consume method
516
+ */
517
+ interface ConsumeOptions {
518
+ /** The specific message ID to consume (if not provided, consumes next available message) */
519
+ messageId?: string;
520
+ /** Whether to skip downloading the payload (only allowed when messageId is provided) */
521
+ skipPayload?: boolean;
522
+ }
505
523
  /**
506
524
  * A ConsumerGroup represents a named group of consumers that process messages from a topic
507
525
  */
@@ -546,75 +564,34 @@ declare class ConsumerGroup<T = unknown> {
546
564
  */
547
565
  private processMessage;
548
566
  /**
549
- * Start continuous processing of messages from the topic
550
- * @param signal AbortSignal to control when to stop processing
551
- * @param handler Function to process each message
552
- * @param options Processing options
553
- * @returns Promise that resolves when processing stops (due to signal or error)
554
- */
555
- subscribe(signal: AbortSignal, handler: MessageHandler<T>, options?: {
556
- pollingInterval?: number;
557
- }): Promise<void>;
558
- /**
559
- * Receive and process a specific message by its ID with full payload
560
- * @param messageId The ID of the message to receive and process
561
- * @param handler Function to process the message with full payload
562
- * @returns Promise that resolves when the message is processed or rejects with specific errors
563
- * @throws {MessageNotFoundError} When the message doesn't exist (404)
564
- * @throws {MessageNotAvailableError} When the message exists but isn't available for processing (409)
565
- * @throws {MessageLockedError} When the message is temporarily locked (423)
566
- * @throws {FifoOrderingViolationError} When there's a FIFO ordering violation (409 with nextMessageId)
567
- * @throws {FailedDependencyError} When FIFO ordering is violated (424)
568
- * @throws {MessageCorruptedError} When the message data is corrupted
569
- * @throws {BadRequestError} When request parameters are invalid
570
- * @throws {UnauthorizedError} When authentication fails
571
- * @throws {ForbiddenError} When access is denied
572
- * @throws {InternalServerError} When server encounters an error
573
- */
574
- receiveMessage(messageId: string, handler: MessageHandler<T>): Promise<void>;
575
- /**
576
- * Receive and process the next available message from the queue
567
+ * Consume the next available message from the queue
577
568
  * @param handler Function to process the message
578
- * @returns Promise that resolves when the message is processed or rejects with specific errors
579
- * @throws {QueueEmptyError} When no messages are available in the queue (204)
580
- * @throws {MessageLockedError} When the next message in a FIFO queue is locked (423)
581
- * @throws {BadRequestError} When request parameters are invalid
582
- * @throws {UnauthorizedError} When authentication fails
583
- * @throws {ForbiddenError} When access is denied
584
- * @throws {InternalServerError} When server encounters an error
569
+ * @returns Promise that resolves when the message is processed
570
+ * @throws All the same errors as the underlying client methods
585
571
  */
586
- receiveNextMessage(handler: MessageHandler<T>): Promise<void>;
572
+ consume(handler: MessageHandler<T>): Promise<void>;
587
573
  /**
588
- * Receive and process multiple next available messages from the queue
589
- * @param limit Number of messages to process (1-10)
590
- * @param handler Function to process each message
591
- * @returns Promise that resolves to an array of PromiseSettledResult (same as Promise.allSettled)
592
- * @throws {InvalidLimitError} When limit parameter is not between 1 and 10
593
- * @throws {QueueEmptyError} When no messages are available in the queue (204)
594
- * @throws {MessageLockedError} When the next message in a FIFO queue is locked (423)
595
- * @throws {BadRequestError} When request parameters are invalid
596
- * @throws {UnauthorizedError} When authentication fails
597
- * @throws {ForbiddenError} When access is denied
598
- * @throws {InternalServerError} When server encounters an error
574
+ * Consume a specific message by its ID with full payload
575
+ * @param handler Function to process the message
576
+ * @param options Consume options with messageId specified
577
+ * @returns Promise that resolves when the message is processed
578
+ * @throws All the same errors as the underlying client methods
599
579
  */
600
- receiveNextMessages(limit: number, handler: MessageHandler<T>): Promise<PromiseSettledResult<void>[]>;
580
+ consume(handler: MessageHandler<T>, options: {
581
+ messageId: string;
582
+ skipPayload?: false | undefined;
583
+ }): Promise<void>;
601
584
  /**
602
- * Handle a specific message by its ID without downloading the payload (metadata only)
603
- * @param messageId The ID of the message to handle
585
+ * Consume a specific message by its ID without downloading the payload (metadata only)
604
586
  * @param handler Function to process the message metadata (payload will be void)
605
- * @returns Promise that resolves when the message is handled or rejects with specific errors
606
- * @throws {MessageNotFoundError} When the message doesn't exist (404)
607
- * @throws {MessageNotAvailableError} When the message exists but isn't available for processing (409)
608
- * @throws {MessageLockedError} When the message is temporarily locked (423)
609
- * @throws {FifoOrderingViolationError} When there's a FIFO ordering violation (409 with nextMessageId)
610
- * @throws {FailedDependencyError} When FIFO ordering is violated (424)
611
- * @throws {MessageCorruptedError} When the message data is corrupted
612
- * @throws {BadRequestError} When request parameters are invalid
613
- * @throws {UnauthorizedError} When authentication fails
614
- * @throws {ForbiddenError} When access is denied
615
- * @throws {InternalServerError} When server encounters an error
587
+ * @param options Consume options with messageId and skipPayload specified
588
+ * @returns Promise that resolves when the message is processed
589
+ * @throws All the same errors as the underlying client methods
616
590
  */
617
- handleMessage(messageId: string, handler: MessageHandler<void>): Promise<void>;
591
+ consume(handler: MessageHandler<void>, options: {
592
+ messageId: string;
593
+ skipPayload: true;
594
+ }): Promise<void>;
618
595
  /**
619
596
  * Get the consumer group name
620
597
  */
@@ -649,11 +626,7 @@ declare class Topic<T = unknown> {
649
626
  * @throws {ForbiddenError} When access is denied (environment mismatch)
650
627
  * @throws {InternalServerError} When server encounters an error
651
628
  */
652
- publish(payload: T, options?: {
653
- idempotencyKey?: string;
654
- retentionSeconds?: number;
655
- callbacks?: Record<string, CallbackConfig>;
656
- }): Promise<{
629
+ publish(payload: T, options?: PublishOptions): Promise<{
657
630
  messageId: string;
658
631
  }>;
659
632
  /**
@@ -674,13 +647,79 @@ declare class Topic<T = unknown> {
674
647
  }
675
648
 
676
649
  /**
677
- * Create a new Topic instance
678
- * @param client QueueClient instance to use for API calls
650
+ * Create a new Topic instance using the default QueueClient
651
+ * For custom client configuration, use `new Topic(customClient, topicName, transport)` directly
679
652
  * @param topicName Name of the topic
680
653
  * @param transport Optional serializer/deserializer for the payload (defaults to JSON)
681
654
  * @returns A Topic instance
682
655
  */
683
- declare function createTopic<T = unknown>(client: QueueClient, topicName: string, transport?: Transport<T>): Topic<T>;
656
+ declare function createTopic<T = unknown>(topicName: string, transport?: Transport<T>): Topic<T>;
657
+ /**
658
+ * Options for the send function
659
+ */
660
+ interface SendOptions<T = unknown> extends PublishOptions {
661
+ /**
662
+ * Serializer/deserializer for the payload
663
+ * @default JsonTransport instance
664
+ */
665
+ transport?: Transport<T>;
666
+ }
667
+ /**
668
+ * Send a message to a topic (shorthand for topic creation and publishing)
669
+ * Uses the default QueueClient with automatic OIDC token detection
670
+ * @param topicName Name of the topic to send to
671
+ * @param payload The data to send
672
+ * @param options Optional send options including transport and publish settings
673
+ * @returns Promise with the message ID
674
+ * @throws {BadRequestError} When request parameters are invalid
675
+ * @throws {UnauthorizedError} When authentication fails
676
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
677
+ * @throws {InternalServerError} When server encounters an error
678
+ */
679
+ declare function send<T = unknown>(topicName: string, payload: T, options?: SendOptions<T>): Promise<{
680
+ messageId: string;
681
+ }>;
682
+ /**
683
+ * Options for the receive function
684
+ */
685
+ interface ReceiveOptions<T = unknown> extends ConsumerGroupOptions<T>, ConsumeOptions {
686
+ }
687
+ /**
688
+ * Receive a message from a topic (shorthand for topic and consumer group creation)
689
+ * Uses the default QueueClient with automatic OIDC token detection
690
+ * @param topicName Name of the topic to receive from
691
+ * @param consumerGroup Name of the consumer group
692
+ * @param handler Function to process the message
693
+ * @returns Promise that resolves when the message is processed
694
+ * @throws All the same errors as the underlying client methods
695
+ */
696
+ declare function receive<T = unknown>(topicName: string, consumerGroup: string, handler: MessageHandler<T>, options?: ReceiveOptions<T>): Promise<void>;
697
+ /**
698
+ * Receive a specific message by its ID with full payload
699
+ * @param topicName Name of the topic to receive from
700
+ * @param consumerGroup Name of the consumer group
701
+ * @param handler Function to process the message
702
+ * @param options Receive options with messageId specified
703
+ * @returns Promise that resolves when the message is processed
704
+ * @throws All the same errors as the underlying client methods
705
+ */
706
+ declare function receive<T = unknown>(topicName: string, consumerGroup: string, handler: MessageHandler<T>, options: ReceiveOptions<T> & {
707
+ messageId: string;
708
+ skipPayload?: false | undefined;
709
+ }): Promise<void>;
710
+ /**
711
+ * Receive a specific message by its ID without downloading the payload (metadata only)
712
+ * @param topicName Name of the topic to receive from
713
+ * @param consumerGroup Name of the consumer group
714
+ * @param handler Function to process the message metadata (payload will be void)
715
+ * @param options Receive options with messageId and skipPayload specified
716
+ * @returns Promise that resolves when the message is processed
717
+ * @throws All the same errors as the underlying client methods
718
+ */
719
+ declare function receive<T = unknown>(topicName: string, consumerGroup: string, handler: MessageHandler<void>, options: ReceiveOptions<T> & {
720
+ messageId: string;
721
+ skipPayload: true;
722
+ }): Promise<void>;
684
723
 
685
724
  /**
686
725
  * Queue Callback utilities for handling incoming webhook payloads
@@ -719,7 +758,41 @@ declare function createTopic<T = unknown>(client: QueueClient, topicName: string
719
758
  * ```
720
759
  */
721
760
  declare function parseCallbackRequest(request: Request): CallbackMessageOptions;
761
+ /**
762
+ * Configuration object with handlers for different topics
763
+ * Each topic can have either:
764
+ * - A single handler function (uses 'default' consumer group)
765
+ * - An object with handlers for specific consumer groups
766
+ */
767
+ type CallbackHandlers = {
768
+ [topicName: string]: MessageHandler | {
769
+ [consumerGroup: string]: MessageHandler;
770
+ };
771
+ };
772
+ /**
773
+ * Simplified queue callback handler for NextJS route handlers
774
+ *
775
+ * @param handlers Object with topic-specific handlers
776
+ * @returns A NextJS route handler function
777
+ *
778
+ * @example
779
+ * ```typescript
780
+ * // Topic handler (uses 'default' consumer group)
781
+ * export const POST = handleCallback({
782
+ * "new-users": (message, metadata) => {
783
+ * console.log(`New user event:`, message, metadata);
784
+ * }
785
+ * });
786
+ *
787
+ * // Consumer group specific handlers
788
+ * export const POST = handleCallback({
789
+ * "image-processing": {
790
+ * "compress": (message, metadata) => console.log("Compressing image", message),
791
+ * "resize": (message, metadata) => console.log("Resizing image", message),
792
+ * }
793
+ * });
794
+ * ```
795
+ */
796
+ declare function handleCallback(handlers: CallbackHandlers): (request: Request) => Promise<Response>;
722
797
 
723
- declare function getVercelOidcToken(): Promise<string>;
724
-
725
- export { BadRequestError, BufferTransport, type CallbackConfig, type CallbackMessageOptions, type ChangeVisibilityOptions, type ChangeVisibilityResponse, ConsumerGroup, type ConsumerGroupOptions, type DeleteMessageOptions, type DeleteMessageResponse, FailedDependencyError, type FifoOrderingError, FifoOrderingViolationError, ForbiddenError, InternalServerError, InvalidCallbackError, InvalidLimitError, JsonTransport, type Message, MessageCorruptedError, type MessageHandler, type MessageHandlerResult, MessageLockedError, MessageNotAvailableError, MessageNotFoundError, type MessageTimeoutResult, QueueClient, type QueueClientOptions, QueueEmptyError, type ReceiveMessageByIdOptions, type ReceiveMessageByIdResponse, type ReceiveMessagesOptions, type SendMessageOptions, type SendMessageResponse, StreamTransport, Topic, type Transport, UnauthorizedError, createTopic, getVercelOidcToken, parseCallbackRequest };
798
+ export { BadRequestError, BufferTransport, type CallbackConfig, type CallbackMessageOptions, type ChangeVisibilityOptions, type ChangeVisibilityResponse, type ConsumeOptions, ConsumerGroup, type ConsumerGroupOptions, type DeleteMessageOptions, type DeleteMessageResponse, FailedDependencyError, FifoOrderingViolationError, ForbiddenError, InternalServerError, InvalidCallbackError, InvalidLimitError, JsonTransport, type Message, MessageCorruptedError, type MessageHandler, type MessageHandlerResult, MessageLockedError, type MessageMetadata, MessageNotAvailableError, MessageNotFoundError, type MessageTimeoutResult, type PublishOptions, QueueClient, type QueueClientOptions, QueueEmptyError, type ReceiveMessageByIdOptions, type ReceiveMessageByIdResponse, type ReceiveMessagesOptions, type ReceiveOptions, type SendMessageOptions, type SendMessageResponse, type SendOptions, StreamTransport, Topic, type Transport, UnauthorizedError, createTopic, handleCallback, parseCallbackRequest, receive, send };