@vercel/queue 0.0.0-alpha.3 → 0.0.0-alpha.31

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
@@ -1,775 +1,159 @@
1
- /**
2
- * Serializer/Deserializer interface for message payloads
3
- */
4
- interface Transport<T = unknown> {
5
- /**
6
- * Serialize a value to a buffer or stream for transmission
7
- */
8
- serialize(value: T): Buffer | ReadableStream<Uint8Array>;
9
- /**
10
- * Deserialize a readable stream back to the original value
11
- */
12
- deserialize(stream: ReadableStream<Uint8Array>): Promise<T>;
13
- /**
14
- * Optional cleanup method for deserialized payloads that may contain resources
15
- * Should be called when the payload is no longer needed, especially in error cases
16
- * @param payload The deserialized payload to clean up
17
- */
18
- finalize?(payload: T): Promise<void>;
19
- /**
20
- * MIME type for this serialization format
21
- */
22
- contentType: string;
23
- }
24
- /**
25
- * Built-in JSON serializer/deserializer
26
- * This implementation reads the entire stream into memory for JSON parsing
27
- */
28
- declare class JsonTransport<T = unknown> implements Transport<T> {
29
- readonly contentType = "application/json";
30
- serialize(value: T): Buffer;
31
- deserialize(stream: ReadableStream<Uint8Array>): Promise<T>;
32
- }
33
- /**
34
- * Built-in Buffer serializer/deserializer (reads entire stream into a Buffer)
35
- */
36
- declare class BufferTransport implements Transport<Buffer> {
37
- readonly contentType = "application/octet-stream";
38
- serialize(value: Buffer): Buffer;
39
- deserialize(stream: ReadableStream<Uint8Array>): Promise<Buffer>;
40
- }
41
- /**
42
- * Stream serializer/deserializer (pass-through for streaming binary data)
43
- * This is ideal for large payloads that don't need to be buffered in memory
44
- *
45
- * IMPORTANT: When using StreamTransport, you must call finalize(payload) when done
46
- * processing the message to prevent resource leaks, especially in error cases.
47
- * ConsumerGroup handles this automatically, but direct QueueClient usage requires manual cleanup.
48
- *
49
- * Example usage:
50
- * ```typescript
51
- * const transport = new StreamTransport();
52
- * try {
53
- * for await (const message of client.receiveMessages(options, transport)) {
54
- * // Process the stream...
55
- * const reader = message.payload.getReader();
56
- * // ... handle stream data
57
- * }
58
- * } catch (error) {
59
- * // Cleanup is handled automatically by ConsumerGroup
60
- * // or manually: await transport.finalize(message.payload);
61
- * }
62
- */
63
- declare class StreamTransport implements Transport<ReadableStream<Uint8Array>> {
64
- readonly contentType = "application/octet-stream";
65
- serialize(value: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
66
- deserialize(stream: ReadableStream<Uint8Array>): Promise<ReadableStream<Uint8Array>>;
67
- finalize(payload: ReadableStream<Uint8Array>): Promise<void>;
68
- }
1
+ import { M as MessageHandler, C as ConsumerGroupOptions, P as PublishOptions, T as Transport } from './types-JvOenjfT.js';
2
+ export { a as BadRequestError, B as BufferTransport, F as ForbiddenError, I as InternalServerError, b as InvalidLimitError, J as JsonTransport, g as Message, c as MessageCorruptedError, h as MessageHandlerResult, d as MessageLockedError, i as MessageMetadata, e as MessageNotAvailableError, f as MessageNotFoundError, j as MessageTimeoutResult, Q as QueueEmptyError, k as SendMessageOptions, l as SendMessageResponse, S as StreamTransport, U as UnauthorizedError } from './types-JvOenjfT.js';
69
3
 
70
4
  /**
71
- * Vercel Queue Service client types
72
- */
73
-
74
- interface QueueClientOptions {
75
- /**
76
- * Base URL for the Vercel Queue Service API
77
- * @default "https://vqs.vercel.sh"
78
- */
79
- baseUrl?: string;
80
- /**
81
- * Vercel function OIDC token
82
- * Can be obtained from x-vercel-oidc-token header in Vercel Serverless Functions
83
- */
84
- token: string;
85
- }
86
- /**
87
- * Callback configuration for a consumer group
88
- */
89
- interface CallbackConfig {
90
- /**
91
- * Webhook URL to notify when messages are available
92
- */
93
- url: string;
94
- /**
95
- * Delay in seconds before sending the first callback
96
- */
97
- delay?: number;
98
- /**
99
- * Delay in seconds between retry attempts when the callback fails
100
- */
101
- frequency?: number;
102
- }
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;
112
- /**
113
- * Unique key to prevent duplicate message submissions
114
- * @default random UUID
115
- */
116
- idempotencyKey?: string;
117
- /**
118
- * Message retention time in seconds
119
- * @default 86400 (24 hours)
120
- * @min 60
121
- * @max 86400
122
- */
123
- retentionSeconds?: number;
124
- /**
125
- * Callback configuration
126
- * - If a single CallbackConfig is provided, it will use the "default" consumer group
127
- * - If an object is provided, keys are consumer group names with their respective callback configs
128
- * Format: { consumerGroup: { url, delay?, frequency? } } or { url, delay?, frequency? }
129
- */
130
- callback?: Record<string, CallbackConfig> | CallbackConfig;
131
- }
132
- interface SendMessageResponse {
133
- /**
134
- * The generated message ID
135
- */
136
- messageId: string;
137
- }
138
- interface Message<T = unknown> {
139
- /**
140
- * The message ID
141
- */
142
- messageId: string;
143
- /**
144
- * The deserialized message payload
145
- * Note: If using streaming transports, ensure proper cleanup by calling transport.finalize(payload)
146
- * when done processing, especially in error cases
147
- */
148
- payload: T;
149
- /**
150
- * Number of times this message has been delivered
151
- */
152
- deliveryCount: number;
153
- /**
154
- * Timestamp when the message was created
155
- */
156
- timestamp: string;
157
- /**
158
- * MIME type of the message content
159
- */
160
- contentType: string;
161
- /**
162
- * Unique ticket for this message delivery (required for delete/patch operations)
163
- */
164
- ticket: string;
165
- }
166
- interface ReceiveMessagesOptions<T = unknown> {
167
- /**
168
- * The queue name to receive messages from
169
- */
170
- queueName: string;
171
- /**
172
- * Consumer group name
173
- */
174
- consumerGroup: string;
175
- /**
176
- * Time in seconds that messages will be invisible to other consumers
177
- * @default 900 (15 minutes)
178
- */
179
- visibilityTimeoutSeconds?: number;
180
- /**
181
- * Maximum number of messages to retrieve
182
- * @default 10
183
- * @max 10
184
- * @note FIFO queues must use limit=1
185
- */
186
- limit?: number;
187
- }
188
- interface DeleteMessageOptions {
189
- /**
190
- * The queue name the message belongs to
191
- */
192
- queueName: string;
193
- /**
194
- * Consumer group name
195
- */
196
- consumerGroup: string;
197
- /**
198
- * The message ID to delete
199
- */
200
- messageId: string;
201
- /**
202
- * Ticket received from the message
203
- */
204
- ticket: string;
205
- }
206
- interface DeleteMessageResponse {
207
- /**
208
- * Whether the message was successfully deleted
209
- */
210
- deleted: boolean;
211
- }
212
- interface ChangeVisibilityOptions {
213
- /**
214
- * The queue name the message belongs to
215
- */
216
- queueName: string;
217
- /**
218
- * Consumer group name
219
- */
220
- consumerGroup: string;
221
- /**
222
- * The message ID to update
223
- */
224
- messageId: string;
225
- /**
226
- * Ticket received from the message
227
- */
228
- ticket: string;
229
- /**
230
- * New visibility timeout in seconds
231
- */
232
- visibilityTimeoutSeconds: number;
233
- }
234
- interface ChangeVisibilityResponse {
235
- /**
236
- * Whether the visibility was successfully updated
237
- */
238
- updated: boolean;
239
- }
240
- /**
241
- * Result indicating the message should be timed out for retry later
5
+ * Options for the consume method
242
6
  */
243
- interface MessageTimeoutResult {
244
- /**
245
- * Time in seconds before the message becomes visible again
246
- */
247
- timeoutSeconds: number;
7
+ interface ConsumeOptions {
8
+ /** The specific message ID to consume (if not provided, consumes next available message) */
9
+ messageId?: string;
10
+ /** Whether to skip downloading the payload (only allowed when messageId is provided) */
11
+ skipPayload?: boolean;
248
12
  }
13
+
249
14
  /**
250
- * Result returned by message handlers
251
- */
252
- type MessageHandlerResult = void | MessageTimeoutResult;
253
- /**
254
- * Message handler function type
255
- */
256
- type MessageHandler<T = unknown> = (message: Message<T>) => Promise<MessageHandlerResult> | MessageHandlerResult;
257
- /**
258
- * Options for creating a ConsumerGroup instance
15
+ * Options for the send function
259
16
  */
260
- interface ConsumerGroupOptions<T = unknown> {
17
+ interface SendOptions<T = unknown> extends PublishOptions {
261
18
  /**
262
19
  * Serializer/deserializer for the payload
263
20
  * @default JsonTransport instance
264
21
  */
265
22
  transport?: Transport<T>;
266
- /**
267
- * Time in seconds that messages will be invisible to other consumers
268
- * @default 30
269
- */
270
- visibilityTimeoutSeconds?: number;
271
- /**
272
- * How often to refresh the visibility timeout during processing (in seconds)
273
- * @default 10
274
- */
275
- refreshInterval?: number;
276
- }
277
- interface ReceiveMessageByIdOptions<T = unknown> {
278
- /**
279
- * The queue name to receive the message from
280
- */
281
- queueName: string;
282
- /**
283
- * Consumer group name
284
- */
285
- consumerGroup: string;
286
- /**
287
- * The message ID to retrieve
288
- */
289
- messageId: string;
290
- /**
291
- * Time in seconds that the message will be invisible to other consumers
292
- * @default 900 (15 minutes)
293
- */
294
- visibilityTimeoutSeconds?: number;
295
- /**
296
- * Skip payload content and only return message metadata
297
- * When true, the server returns a 204 status with headers containing message metadata
298
- * @default false
299
- */
300
- skipPayload?: boolean;
301
- }
302
- interface ReceiveMessageByIdResponse<T = unknown, TSkipPayload extends boolean = false> {
303
- message: TSkipPayload extends true ? Message<void> : Message<T>;
304
- }
305
- interface FifoOrderingError {
306
- /**
307
- * Error message describing the FIFO ordering violation
308
- */
309
- error: string;
310
- /**
311
- * The message ID that must be processed first
312
- */
313
- nextMessageId: string;
314
23
  }
315
24
  /**
316
- * Error thrown when a message is not found (404)
25
+ * Send a message to a topic (shorthand for topic creation and publishing)
26
+ * Uses the default QueueClient with automatic OIDC token detection
27
+ * @param topicName Name of the topic to send to
28
+ * @param payload The data to send
29
+ * @param options Optional send options including transport and publish settings
30
+ * @returns Promise with the message ID
31
+ * @throws {BadRequestError} When request parameters are invalid
32
+ * @throws {UnauthorizedError} When authentication fails
33
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
34
+ * @throws {InternalServerError} When server encounters an error
317
35
  */
318
- declare class MessageNotFoundError extends Error {
319
- constructor(messageId: string);
320
- }
321
- /**
322
- * Error thrown when a message is not available for processing (409)
323
- * This can happen when the message is in the wrong state, already claimed, etc.
324
- */
325
- declare class MessageNotAvailableError extends Error {
326
- constructor(messageId: string, reason?: string);
327
- }
328
- /**
329
- * Error thrown when there's a FIFO ordering violation (409 with nextMessageId)
330
- */
331
- declare class FifoOrderingViolationError extends Error {
332
- readonly nextMessageId: string;
333
- constructor(messageId: string, nextMessageId: string, reason: string);
334
- }
335
- /**
336
- * Error thrown when message data is corrupted or can't be parsed
337
- */
338
- declare class MessageCorruptedError extends Error {
339
- constructor(messageId: string, reason: string);
340
- }
341
- /**
342
- * Error thrown when there are no messages available in the queue (204)
343
- */
344
- declare class QueueEmptyError extends Error {
345
- constructor(queueName: string, consumerGroup: string);
346
- }
347
- /**
348
- * Error thrown when a message is temporarily locked in a FIFO queue (423)
349
- */
350
- declare class MessageLockedError extends Error {
351
- readonly retryAfter?: number;
352
- constructor(messageId: string, retryAfter?: number);
353
- }
354
- /**
355
- * Error thrown when authentication fails (401)
356
- */
357
- declare class UnauthorizedError extends Error {
358
- constructor(message?: string);
359
- }
360
- /**
361
- * Error thrown when access is forbidden (403)
362
- */
363
- declare class ForbiddenError extends Error {
364
- constructor(message?: string);
365
- }
36
+ declare function send<T = unknown>(topicName: string, payload: T, options?: SendOptions<T>): Promise<{
37
+ messageId: string;
38
+ }>;
366
39
  /**
367
- * Error thrown for bad requests (400)
40
+ * Options for the receive function
368
41
  */
369
- declare class BadRequestError extends Error {
370
- constructor(message: string);
42
+ interface ReceiveOptions<T = unknown> extends ConsumerGroupOptions<T>, ConsumeOptions {
371
43
  }
372
44
  /**
373
- * Error thrown when there's a failed dependency (424) - FIFO ordering violation in receive by ID
45
+ * Receive a message from a topic (shorthand for topic and consumer group creation)
46
+ * Uses the default QueueClient with automatic OIDC token detection
47
+ * @param topicName Name of the topic to receive from
48
+ * @param consumerGroup Name of the consumer group
49
+ * @param handler Function to process the message
50
+ * @returns Promise that resolves when the message is processed
51
+ * @throws All the same errors as the underlying client methods
374
52
  */
375
- declare class FailedDependencyError extends Error {
376
- readonly nextMessageId: string;
377
- constructor(messageId: string, nextMessageId: string);
378
- }
53
+ declare function receive<T = unknown>(topicName: string, consumerGroup: string, handler: MessageHandler<T>, options?: ReceiveOptions<T>): Promise<void>;
379
54
  /**
380
- * Error thrown for internal server errors (500)
55
+ * Receive a specific message by its ID with full payload
56
+ * @param topicName Name of the topic to receive from
57
+ * @param consumerGroup Name of the consumer group
58
+ * @param handler Function to process the message
59
+ * @param options Receive options with messageId specified
60
+ * @returns Promise that resolves when the message is processed
61
+ * @throws All the same errors as the underlying client methods
381
62
  */
382
- declare class InternalServerError extends Error {
383
- constructor(message?: string);
384
- }
63
+ declare function receive<T = unknown>(topicName: string, consumerGroup: string, handler: MessageHandler<T>, options: ReceiveOptions<T> & {
64
+ messageId: string;
65
+ skipPayload?: false | undefined;
66
+ }): Promise<void>;
67
+ /**
68
+ * Receive a specific message by its ID without downloading the payload (metadata only)
69
+ * @param topicName Name of the topic to receive from
70
+ * @param consumerGroup Name of the consumer group
71
+ * @param handler Function to process the message metadata (payload will be void)
72
+ * @param options Receive options with messageId and skipPayload specified
73
+ * @returns Promise that resolves when the message is processed
74
+ * @throws All the same errors as the underlying client methods
75
+ */
76
+ declare function receive<T = unknown>(topicName: string, consumerGroup: string, handler: MessageHandler<void>, options: ReceiveOptions<T> & {
77
+ messageId: string;
78
+ skipPayload: true;
79
+ }): Promise<void>;
80
+
385
81
  /**
386
- * Error thrown when batch limit parameter is invalid
82
+ * Configuration object with handlers for different topics and consumer groups
387
83
  */
388
- declare class InvalidLimitError extends Error {
389
- constructor(limit: number, min?: number, max?: number);
390
- }
84
+ type CallbackHandlers = {
85
+ [topicName: string]: {
86
+ [consumerGroup: string]: MessageHandler;
87
+ };
88
+ };
391
89
  /**
392
- * Options extracted from a queue callback request
90
+ * Parsed callback request information
393
91
  */
394
- interface CallbackMessageOptions {
395
- /**
396
- * The queue name extracted from Vqs-Queue-Name header
397
- */
92
+ type ParsedCallbackRequest = {
398
93
  queueName: string;
399
- /**
400
- * The consumer group extracted from Vqs-Consumer-Group header
401
- */
402
94
  consumerGroup: string;
403
- /**
404
- * The message ID extracted from Vqs-Message-Id header
405
- */
406
95
  messageId: string;
407
- }
408
- /**
409
- * Error thrown when queue callback headers are missing or invalid
410
- */
411
- declare class InvalidCallbackError extends Error {
412
- constructor(message: string);
413
- }
414
-
415
- /**
416
- * Client for interacting with the Vercel Queue Service API
417
- */
418
- declare class QueueClient {
419
- private baseUrl;
420
- private token;
421
- /**
422
- * Create a new Vercel Queue Service client
423
- * @param options Client configuration options
424
- */
425
- constructor(options: QueueClientOptions);
426
- /**
427
- * Create a QueueClient automatically configured for Vercel Functions
428
- * This method automatically retrieves the OIDC token from the Vercel Function environment
429
- * Always creates a fresh instance since OIDC tokens expire after 15 minutes
430
- * @param baseUrl Optional base URL override
431
- * @returns Promise resolving to a new QueueClient instance
432
- */
433
- static fromVercelFunction(baseUrl?: string): Promise<QueueClient>;
434
- /**
435
- * Send a message to a queue
436
- * @param options Send message options
437
- * @param transport Serializer/deserializer for the payload
438
- * @returns Promise with the message ID
439
- * @throws {BadRequestError} When request parameters are invalid
440
- * @throws {UnauthorizedError} When authentication fails
441
- * @throws {ForbiddenError} When access is denied (environment mismatch)
442
- * @throws {InternalServerError} When server encounters an error
443
- */
444
- sendMessage<T = unknown>(options: SendMessageOptions<T>, transport: Transport<T>): Promise<SendMessageResponse>;
445
- /**
446
- * Receive messages from a queue
447
- * @param options Receive messages options
448
- * @param transport Serializer/deserializer for the payload
449
- * @returns AsyncGenerator that yields messages as they arrive
450
- * @throws {InvalidLimitError} When limit parameter is not between 1 and 10
451
- * @throws {QueueEmptyError} When no messages are available (204)
452
- * @throws {MessageLockedError} When FIFO queue has locked messages (423)
453
- * @throws {BadRequestError} When request parameters are invalid
454
- * @throws {UnauthorizedError} When authentication fails
455
- * @throws {ForbiddenError} When access is denied (environment mismatch)
456
- * @throws {InternalServerError} When server encounters an error
457
- */
458
- receiveMessages<T = unknown>(options: ReceiveMessagesOptions<T>, transport: Transport<T>): AsyncGenerator<Message<T>, void, unknown>;
459
- /**
460
- * Receive a specific message by its ID from a queue
461
- * @param options Receive message by ID options
462
- * @param transport Serializer/deserializer for the payload
463
- * @returns Promise with the message or null if not found/available
464
- * @throws {MessageNotFoundError} When the message doesn't exist (404)
465
- * @throws {MessageLockedError} When the message is temporarily locked (423)
466
- * @throws {FailedDependencyError} When FIFO ordering is violated (424)
467
- * @throws {MessageNotAvailableError} When message exists but isn't available (409)
468
- * @throws {FifoOrderingViolationError} When FIFO ordering is violated (409 with nextMessageId)
469
- * @throws {MessageCorruptedError} When message data is corrupted
470
- * @throws {BadRequestError} When request parameters are invalid
471
- * @throws {UnauthorizedError} When authentication fails
472
- * @throws {ForbiddenError} When access is denied (environment mismatch)
473
- * @throws {InternalServerError} When server encounters an error
474
- */
475
- receiveMessageById<T = unknown>(options: ReceiveMessageByIdOptions<T> & {
476
- skipPayload: true;
477
- }, transport?: Transport<T>): Promise<ReceiveMessageByIdResponse<T, true>>;
478
- receiveMessageById<T = unknown>(options: ReceiveMessageByIdOptions<T> & {
479
- skipPayload?: false | undefined;
480
- }, transport: Transport<T>): Promise<ReceiveMessageByIdResponse<T, false>>;
481
- /**
482
- * Delete a message (acknowledge processing)
483
- * @param options Delete message options
484
- * @returns Promise with delete status
485
- * @throws {MessageNotFoundError} When the message doesn't exist (404)
486
- * @throws {MessageNotAvailableError} When message can't be deleted (409)
487
- * @throws {BadRequestError} When ticket is missing or invalid (400)
488
- * @throws {UnauthorizedError} When authentication fails
489
- * @throws {ForbiddenError} When access is denied (environment mismatch)
490
- * @throws {InternalServerError} When server encounters an error
491
- */
492
- deleteMessage(options: DeleteMessageOptions): Promise<DeleteMessageResponse>;
493
- /**
494
- * Change the visibility timeout of a message
495
- * @param options Change visibility options
496
- * @returns Promise with update status
497
- * @throws {MessageNotFoundError} When the message doesn't exist (404)
498
- * @throws {MessageNotAvailableError} When message can't be updated (409)
499
- * @throws {BadRequestError} When ticket is missing or visibility timeout invalid (400)
500
- * @throws {UnauthorizedError} When authentication fails
501
- * @throws {ForbiddenError} When access is denied (environment mismatch)
502
- * @throws {InternalServerError} When server encounters an error
503
- */
504
- changeVisibility(options: ChangeVisibilityOptions): Promise<ChangeVisibilityResponse>;
505
- }
506
-
507
- /**
508
- * A ConsumerGroup represents a named group of consumers that process messages from a topic
509
- */
510
- declare class ConsumerGroup<T = unknown> {
511
- private client;
512
- private topicName;
513
- private consumerGroupName;
514
- private visibilityTimeout;
515
- private refreshInterval;
516
- private transport;
517
- /**
518
- * Create a new ConsumerGroup instance
519
- * @param client QueueClient instance to use for API calls
520
- * @param topicName Name of the topic to consume from
521
- * @param consumerGroupName Name of the consumer group
522
- * @param options Optional configuration
523
- */
524
- constructor(client: QueueClient, topicName: string, consumerGroupName: string, options?: ConsumerGroupOptions<T>);
525
- /**
526
- * Starts a background loop that periodically extends the visibility timeout for a message.
527
- * This prevents the message from becoming visible to other consumers while it's being processed.
528
- *
529
- * The extension loop runs every `refreshInterval` seconds and updates the message's
530
- * visibility timeout to `visibilityTimeout` seconds from the current time.
531
- *
532
- * @param messageId - The unique identifier of the message to extend visibility for
533
- * @param ticket - The receipt ticket that proves ownership of the message
534
- * @returns A function that when called will stop the extension loop
535
- *
536
- * @remarks
537
- * - The first extension attempt occurs after `refreshInterval` seconds, not immediately
538
- * - If an extension fails, the loop terminates with an error logged to console
539
- * - The returned stop function is idempotent - calling it multiple times is safe
540
- * - By default, the stop function returns immediately without waiting for in-flight
541
- * - Pass `true` to the stop function to wait for any in-flight extension to complete
542
- */
543
- private startVisibilityExtension;
544
- /**
545
- * Process a single message with the given handler
546
- * @param message The message to process
547
- * @param handler Function to process the message
548
- */
549
- private processMessage;
550
- /**
551
- * Start continuous processing of messages from the topic
552
- * @param signal AbortSignal to control when to stop processing
553
- * @param handler Function to process each message
554
- * @param options Processing options
555
- * @returns Promise that resolves when processing stops (due to signal or error)
556
- */
557
- subscribe(signal: AbortSignal, handler: MessageHandler<T>, options?: {
558
- pollingInterval?: number;
559
- }): Promise<void>;
560
- /**
561
- * Receive and process a specific message by its ID with full payload
562
- * @param messageId The ID of the message to receive and process
563
- * @param handler Function to process the message with full payload
564
- * @returns Promise that resolves when the message is processed or rejects with specific errors
565
- * @throws {MessageNotFoundError} When the message doesn't exist (404)
566
- * @throws {MessageNotAvailableError} When the message exists but isn't available for processing (409)
567
- * @throws {MessageLockedError} When the message is temporarily locked (423)
568
- * @throws {FifoOrderingViolationError} When there's a FIFO ordering violation (409 with nextMessageId)
569
- * @throws {FailedDependencyError} When FIFO ordering is violated (424)
570
- * @throws {MessageCorruptedError} When the message data is corrupted
571
- * @throws {BadRequestError} When request parameters are invalid
572
- * @throws {UnauthorizedError} When authentication fails
573
- * @throws {ForbiddenError} When access is denied
574
- * @throws {InternalServerError} When server encounters an error
575
- */
576
- receiveMessage(messageId: string, handler: MessageHandler<T>): Promise<void>;
577
- /**
578
- * Receive and process the next available message from the queue
579
- * @param handler Function to process the message
580
- * @returns Promise that resolves when the message is processed or rejects with specific errors
581
- * @throws {QueueEmptyError} When no messages are available in the queue (204)
582
- * @throws {MessageLockedError} When the next message in a FIFO queue is locked (423)
583
- * @throws {BadRequestError} When request parameters are invalid
584
- * @throws {UnauthorizedError} When authentication fails
585
- * @throws {ForbiddenError} When access is denied
586
- * @throws {InternalServerError} When server encounters an error
587
- */
588
- receiveNextMessage(handler: MessageHandler<T>): Promise<void>;
589
- /**
590
- * Receive and process multiple next available messages from the queue
591
- * @param limit Number of messages to process (1-10)
592
- * @param handler Function to process each message
593
- * @returns Promise that resolves to an array of PromiseSettledResult (same as Promise.allSettled)
594
- * @throws {InvalidLimitError} When limit parameter is not between 1 and 10
595
- * @throws {QueueEmptyError} When no messages are available in the queue (204)
596
- * @throws {MessageLockedError} When the next message in a FIFO queue is locked (423)
597
- * @throws {BadRequestError} When request parameters are invalid
598
- * @throws {UnauthorizedError} When authentication fails
599
- * @throws {ForbiddenError} When access is denied
600
- * @throws {InternalServerError} When server encounters an error
601
- */
602
- receiveNextMessages(limit: number, handler: MessageHandler<T>): Promise<PromiseSettledResult<void>[]>;
603
- /**
604
- * Handle a specific message by its ID without downloading the payload (metadata only)
605
- * @param messageId The ID of the message to handle
606
- * @param handler Function to process the message metadata (payload will be void)
607
- * @returns Promise that resolves when the message is handled or rejects with specific errors
608
- * @throws {MessageNotFoundError} When the message doesn't exist (404)
609
- * @throws {MessageNotAvailableError} When the message exists but isn't available for processing (409)
610
- * @throws {MessageLockedError} When the message is temporarily locked (423)
611
- * @throws {FifoOrderingViolationError} When there's a FIFO ordering violation (409 with nextMessageId)
612
- * @throws {FailedDependencyError} When FIFO ordering is violated (424)
613
- * @throws {MessageCorruptedError} When the message data is corrupted
614
- * @throws {BadRequestError} When request parameters are invalid
615
- * @throws {UnauthorizedError} When authentication fails
616
- * @throws {ForbiddenError} When access is denied
617
- * @throws {InternalServerError} When server encounters an error
618
- */
619
- handleMessage(messageId: string, handler: MessageHandler<void>): Promise<void>;
620
- /**
621
- * Get the consumer group name
622
- */
623
- get name(): string;
624
- /**
625
- * Get the topic name this consumer group is subscribed to
626
- */
627
- get topic(): string;
628
- }
629
-
630
- /**
631
- * A Topic represents a named channel for publishing messages in a pub/sub pattern
632
- */
633
- declare class Topic<T = unknown> {
634
- private client;
635
- private topicName;
636
- private transport;
637
- /**
638
- * Create a new Topic instance
639
- * @param client QueueClient instance to use for API calls
640
- * @param topicName Name of the topic to work with
641
- * @param transport Optional serializer/deserializer for the payload (defaults to JSON)
642
- */
643
- constructor(client: QueueClient, topicName: string, transport?: Transport<T>);
644
- /**
645
- * Publish a message to the topic
646
- * @param payload The data to publish
647
- * @param options Optional publish options
648
- * @returns An object containing the message ID
649
- * @throws {BadRequestError} When request parameters are invalid
650
- * @throws {UnauthorizedError} When authentication fails
651
- * @throws {ForbiddenError} When access is denied (environment mismatch)
652
- * @throws {InternalServerError} When server encounters an error
653
- */
654
- publish(payload: T, options?: {
655
- idempotencyKey?: string;
656
- retentionSeconds?: number;
657
- callback?: Record<string, CallbackConfig> | CallbackConfig;
658
- }): Promise<{
659
- messageId: string;
660
- }>;
661
- /**
662
- * Create a consumer group for this topic
663
- * @param consumerGroupName Name of the consumer group
664
- * @param options Optional configuration for the consumer group
665
- * @returns A ConsumerGroup instance
666
- */
667
- consumerGroup<U = T>(consumerGroupName: string, options?: ConsumerGroupOptions<U>): ConsumerGroup<U>;
668
- /**
669
- * Get the topic name
670
- */
671
- get name(): string;
672
- /**
673
- * Get the transport used by this topic
674
- */
675
- get serializer(): Transport<T>;
676
- }
677
-
678
- /**
679
- * Create a new Topic instance
680
- * @param client QueueClient instance to use for API calls
681
- * @param topicName Name of the topic
682
- * @param transport Optional serializer/deserializer for the payload (defaults to JSON)
683
- * @returns A Topic instance
684
- */
685
- declare function createTopic<T = unknown>(client: QueueClient, topicName: string, transport?: Transport<T>): Topic<T>;
686
-
687
- /**
688
- * Queue Callback utilities for handling incoming webhook payloads
689
- */
690
-
96
+ };
691
97
  /**
692
- * Parse a queue callback request and extract the required information for receiveMessageById
98
+ * Parse and validate callback request using CloudEvent specification
693
99
  *
694
- * @param request The incoming Request object from the queue callback
695
- * @returns CallbackMessageOptions that can be used with receiveMessageById
696
- * @throws {InvalidCallbackError} When required queue headers are missing or invalid
100
+ * Extracts queue information from CloudEvent format and validates
101
+ * that all required fields are present.
102
+ *
103
+ * @param request The incoming webhook request
104
+ * @returns Parsed queue information
105
+ * @throws Error if required fields are missing
697
106
  *
698
107
  * @example
699
108
  * ```typescript
700
- * import { parseCallbackRequest } from '@vercel/queue';
701
- *
702
- * // In your webhook handler
109
+ * // In Next.js API route
703
110
  * export async function POST(request: Request) {
704
111
  * try {
705
- * const callbackOptions = parseCallbackRequest(request);
112
+ * const { queueName, consumerGroup, messageId } = parseCallback(request);
706
113
  *
707
- * // Use with receiveMessageById
708
- * const message = await client.receiveMessageById({
709
- * ...callbackOptions,
710
- * visibilityTimeoutSeconds: 30
711
- * }, transport);
114
+ * // Use the parsed information...
115
+ * await myWorkflow.handleWebhook(queueName, consumerGroup, messageId);
712
116
  *
713
- * // Process the message...
117
+ * return Response.json({ status: "success" });
714
118
  * } catch (error) {
715
- * if (error instanceof InvalidCallbackError) {
716
- * return new Response('Invalid callback', { status: 400 });
717
- * }
718
- * throw error;
119
+ * return Response.json({ error: error.message }, { status: 400 });
719
120
  * }
720
121
  * }
721
122
  * ```
722
123
  */
723
- declare function parseCallbackRequest(request: Request): CallbackMessageOptions;
724
- /**
725
- * Message metadata provided to handlers
726
- */
727
- interface MessageMetadata {
728
- messageId: string;
729
- deliveryCount: number;
730
- timestamp: string;
731
- }
732
- /**
733
- * Handler function signature
734
- */
735
- type Handler<T = unknown> = (payload: T, metadata: MessageMetadata) => Promise<MessageHandlerResult> | MessageHandlerResult;
736
- /**
737
- * Configuration object with handlers for different topics
738
- * Each topic can have either:
739
- * - A single handler function (uses 'default' consumer group)
740
- * - An object with handlers for specific consumer groups
741
- */
742
- type CallbackHandlers = {
743
- [topicName: string]: Handler | {
744
- [consumerGroup: string]: Handler;
745
- };
746
- };
124
+ declare function parseCallback(request: Request): Promise<ParsedCallbackRequest>;
747
125
  /**
748
- * Simplified queue callback handler for NextJS route handlers
126
+ * Simplified queue callback handler for Next.js route handlers
749
127
  *
750
- * @param handlers Object with topic-specific handlers
751
- * @returns A NextJS route handler function
128
+ * Automatically extracts queue information from CloudEvent format
129
+ * and routes to the appropriate handler based on topic and consumer group.
130
+ *
131
+ * @param handlers Object with topic-specific handlers organized by consumer groups
132
+ * @returns A Next.js route handler function
752
133
  *
753
134
  * @example
754
135
  * ```typescript
755
- * // Topic handler (uses 'default' consumer group)
136
+ * // Single topic with multiple consumer groups
756
137
  * export const POST = handleCallback({
757
- * "new-users": (message, metadata) => {
758
- * console.log(`New user event:`, message, metadata);
138
+ * "image-processing": {
139
+ * "compress": (message, metadata) => console.log("Compressing image", message),
140
+ * "resize": (message, metadata) => console.log("Resizing image", message),
759
141
  * }
760
142
  * });
761
143
  *
762
- * // Consumer group specific handlers
144
+ * // Multiple topics with consumer groups
763
145
  * export const POST = handleCallback({
764
- * "image-processing": {
765
- * "compress": (message, metadata) => console.log("Compressing image", message),
766
- * "resize": (message, metadata) => console.log("Resizing image", message),
146
+ * "user-events": {
147
+ * "welcome": (user, metadata) => console.log("Welcoming user", user),
148
+ * "analytics": (user, metadata) => console.log("Tracking user", user),
149
+ * },
150
+ * "order-events": {
151
+ * "fulfillment": (order, metadata) => console.log("Fulfilling order", order),
152
+ * "notifications": (order, metadata) => console.log("Notifying order", order),
767
153
  * }
768
154
  * });
769
155
  * ```
770
156
  */
771
157
  declare function handleCallback(handlers: CallbackHandlers): (request: Request) => Promise<Response>;
772
158
 
773
- declare function getVercelOidcToken(): Promise<string>;
774
-
775
- 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, type MessageMetadata, 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, handleCallback, parseCallbackRequest };
159
+ export { MessageHandler, type ParsedCallbackRequest, PublishOptions, type ReceiveOptions, type SendOptions, Transport, handleCallback, parseCallback, receive, send };