@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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/oidc.ts","../src/client.ts","../src/local.ts","../src/types.ts","../src/transports.ts","../src/consumer-group.ts","../src/topic.ts","../src/factory.ts","../src/callback.ts"],"sourcesContent":["export async function getVercelOidcToken(): Promise<string> {\n const SYMBOL_FOR_REQ_CONTEXT = Symbol.for(\"@vercel/request-context\");\n const fromSymbol = globalThis as any;\n const context = fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};\n\n const token =\n context.headers?.[\"x-vercel-oidc-token\"] ?? process.env.VERCEL_OIDC_TOKEN;\n\n if (!token) {\n throw new Error(\n `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`,\n );\n }\n\n return token;\n}\n","import { getVercelOidcToken } from \"./oidc\";\nimport { parseMultipartStream } from \"mixpart\";\nimport { processDevelopmentCallbacks, fireLocalhostCallbacks } from \"./local\";\nimport {\n FifoOrderingViolationError,\n MessageCorruptedError,\n MessageNotAvailableError,\n MessageNotFoundError,\n QueueEmptyError,\n MessageLockedError,\n UnauthorizedError,\n ForbiddenError,\n BadRequestError,\n FailedDependencyError,\n InternalServerError,\n InvalidLimitError,\n} from \"./types\";\nimport type {\n CallbackConfig,\n ChangeVisibilityOptions,\n ChangeVisibilityResponse,\n DeleteMessageOptions,\n DeleteMessageResponse,\n FifoOrderingError,\n Message,\n ReceiveMessageByIdOptions,\n ReceiveMessageByIdResponse,\n ReceiveMessagesOptions,\n SendMessageOptions,\n SendMessageResponse,\n Transport,\n QueueClientOptions,\n} from \"./types\";\n\n/**\n * Helper function to consume a ReadableStream to completion\n * This is necessary when we need to drain a stream to let the multipart parser proceed\n */\nasync function consumeStream(\n stream: ReadableStream<Uint8Array>,\n): Promise<void> {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done } = await reader.read();\n if (done) break;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Helper function to parse queue headers into a partial message object\n * Handles both multipart message headers and HTTP response headers\n */\nfunction parseQueueHeaders(\n headers: Headers,\n): Omit<Message<unknown>, \"payload\"> | null {\n const messageId = headers.get(\"Vqs-Message-Id\");\n const deliveryCountStr = headers.get(\"Vqs-Delivery-Count\") || \"0\";\n const timestamp = headers.get(\"Vqs-Timestamp\");\n const contentType = headers.get(\"Content-Type\") || \"application/octet-stream\";\n const ticket = headers.get(\"Vqs-Ticket\");\n\n if (!messageId || !timestamp || !ticket) {\n return null;\n }\n\n const deliveryCount = parseInt(deliveryCountStr, 10);\n if (isNaN(deliveryCount)) {\n return null;\n }\n\n return {\n messageId,\n deliveryCount,\n timestamp,\n contentType,\n ticket,\n };\n}\n\n/**\n * Client for interacting with the Vercel Queue Service API\n */\nexport class QueueClient {\n private baseUrl: string;\n private token: string;\n\n /**\n * Create a new Vercel Queue Service client\n * @param options Client configuration options\n */\n constructor(options: QueueClientOptions) {\n this.baseUrl = options.baseUrl || \"https://vqs.vercel.sh\";\n this.token = options.token;\n }\n\n /**\n * Create a QueueClient automatically configured for Vercel Functions\n * This method automatically retrieves the OIDC token from the Vercel Function environment\n * Always creates a fresh instance since OIDC tokens expire after 15 minutes\n * @param baseUrl Optional base URL override\n * @returns Promise resolving to a new QueueClient instance\n */\n static async fromVercelFunction(baseUrl?: string): Promise<QueueClient> {\n const token = await getVercelOidcToken();\n if (!token) {\n throw new Error(\n \"Failed to get OIDC token from Vercel Functions. Make sure you are running in a Vercel Function environment.\",\n );\n }\n\n return new QueueClient({\n token,\n baseUrl,\n });\n }\n\n /**\n * Send a message to a queue\n * @param options Send message options\n * @param transport Serializer/deserializer for the payload\n * @returns Promise with the message ID\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async sendMessage<T = unknown>(\n options: SendMessageOptions<T>,\n transport: Transport<T>,\n ): Promise<SendMessageResponse> {\n const { queueName, payload, idempotencyKey, retentionSeconds, callbacks } =\n options;\n\n const headers = new Headers({\n Authorization: `Bearer ${this.token}`,\n \"Vqs-Queue-Name\": queueName,\n \"Content-Type\": transport.contentType,\n });\n\n if (idempotencyKey) {\n headers.set(\"Vqs-Idempotency-Key\", idempotencyKey);\n }\n\n if (retentionSeconds !== undefined) {\n headers.set(\"Vqs-Retention-Seconds\", retentionSeconds.toString());\n }\n\n // Handle callbacks based on environment\n let localhostCallbacks: Array<{\n group: string;\n config: CallbackConfig;\n port: number;\n }> = [];\n\n if (callbacks) {\n const isDevelopment = process.env.NODE_ENV === \"development\";\n\n if (isDevelopment) {\n // Development mode - process localhost callbacks only\n localhostCallbacks = processDevelopmentCallbacks(callbacks);\n } else {\n // Production mode - set normal callback headers for all callbacks\n const endpoints = Object.entries(callbacks)\n .map(\n ([group, config]) =>\n `${group}=${Buffer.from(config.url).toString(\"base64\")}`,\n )\n .join(\",\");\n headers.set(\"Vqs-Callback-Url\", endpoints);\n\n const delays = Object.entries(callbacks)\n .filter(([, config]) => config.delay !== undefined)\n .map(([group, config]) => `${group}=${config.delay}`)\n .join(\",\");\n if (delays) {\n headers.set(\"Vqs-Callback-Delay\", delays);\n }\n\n const frequencies = Object.entries(callbacks)\n .filter(([, config]) => config.frequency !== undefined)\n .map(([group, config]) => `${group}=${config.frequency}`)\n .join(\",\");\n if (frequencies) {\n headers.set(\"Vqs-Callback-Frequency\", frequencies);\n }\n }\n }\n\n // Serialize the payload using the provided transport\n const body = transport.serialize(payload);\n\n const response = await fetch(`${this.baseUrl}/api/v2/messages`, {\n method: \"POST\",\n headers,\n body,\n });\n\n if (!response.ok) {\n if (response.status === 400) {\n const errorText = await response.text();\n throw new BadRequestError(errorText || \"Invalid parameters\");\n }\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n }\n if (response.status === 409) {\n throw new Error(\"Duplicate idempotency key detected\");\n }\n if (response.status >= 500) {\n throw new InternalServerError(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n throw new Error(\n `Failed to send message: ${response.status} ${response.statusText}`,\n );\n }\n\n const responseData = (await response.json()) as SendMessageResponse;\n\n // Fire localhost callbacks in development mode after successful server response\n if (localhostCallbacks.length > 0) {\n fireLocalhostCallbacks(localhostCallbacks, queueName, responseData);\n }\n\n return responseData;\n }\n\n /**\n * Receive messages from a queue\n * @param options Receive messages options\n * @param transport Serializer/deserializer for the payload\n * @returns AsyncGenerator that yields messages as they arrive\n * @throws {InvalidLimitError} When limit parameter is not between 1 and 10\n * @throws {QueueEmptyError} When no messages are available (204)\n * @throws {MessageLockedError} When FIFO queue has locked messages (423)\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async *receiveMessages<T = unknown>(\n options: ReceiveMessagesOptions<T>,\n transport: Transport<T>,\n ): AsyncGenerator<Message<T>, void, unknown> {\n const { queueName, consumerGroup, visibilityTimeoutSeconds, limit } =\n options;\n\n // Validate limit parameter\n if (limit !== undefined && (limit < 1 || limit > 10)) {\n throw new InvalidLimitError(limit);\n }\n\n const headers = new Headers({\n Authorization: `Bearer ${this.token}`,\n \"Vqs-Queue-Name\": queueName,\n \"Vqs-Consumer-Group\": consumerGroup,\n Accept: \"multipart/mixed\",\n });\n\n if (visibilityTimeoutSeconds !== undefined) {\n headers.set(\n \"Vqs-Visibility-Timeout\",\n visibilityTimeoutSeconds.toString(),\n );\n }\n\n if (limit !== undefined) {\n headers.set(\"Vqs-Limit\", limit.toString());\n }\n\n const response = await fetch(`${this.baseUrl}/api/v2/messages`, {\n method: \"GET\",\n headers,\n });\n\n // Check for 204 No Content - queue is empty\n if (response.status === 204) {\n throw new QueueEmptyError(queueName, consumerGroup);\n }\n\n if (!response.ok) {\n if (response.status === 400) {\n const errorText = await response.text();\n throw new BadRequestError(errorText || \"Invalid parameters\");\n }\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n }\n if (response.status === 423) {\n // FIFO queue locked - next message in sequence is being processed\n const retryAfterHeader = response.headers.get(\"Retry-After\");\n let retryAfter: number | undefined;\n if (retryAfterHeader) {\n const parsed = parseInt(retryAfterHeader, 10);\n retryAfter = isNaN(parsed) ? undefined : parsed;\n }\n throw new MessageLockedError(\"next message in FIFO queue\", retryAfter);\n }\n if (response.status >= 500) {\n throw new InternalServerError(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n throw new Error(\n `Failed to receive messages: ${response.status} ${response.statusText}`,\n );\n }\n\n // Stream messages as they arrive from the multipart parser\n // Each message's payload stream must be consumed immediately for the parser to proceed\n for await (const multipartMessage of parseMultipartStream(response)) {\n try {\n // Parse VQS headers using the helper function\n const parsedHeaders = parseQueueHeaders(multipartMessage.headers);\n\n if (!parsedHeaders) {\n console.warn(\"Missing required queue headers in multipart part\");\n // Still need to consume the payload stream to let the parser proceed\n await consumeStream(multipartMessage.payload);\n continue;\n }\n\n // Deserialize using the provided transport (must consume the stream)\n const deserializedPayload = await transport.deserialize(\n multipartMessage.payload,\n );\n\n const message: Message<T> = {\n ...parsedHeaders,\n payload: deserializedPayload,\n };\n\n yield message;\n } catch (error) {\n console.warn(\"Failed to process multipart message:\", error);\n // If deserialization failed, we still need to consume the payload stream\n // to let the multipart parser proceed to the next message\n await consumeStream(multipartMessage.payload);\n }\n }\n }\n\n /**\n * Receive a specific message by its ID from a queue\n * @param options Receive message by ID options\n * @param transport Serializer/deserializer for the payload\n * @returns Promise with the message or null if not found/available\n * @throws {MessageNotFoundError} When the message doesn't exist (404)\n * @throws {MessageLockedError} When the message is temporarily locked (423)\n * @throws {FailedDependencyError} When FIFO ordering is violated (424)\n * @throws {MessageNotAvailableError} When message exists but isn't available (409)\n * @throws {FifoOrderingViolationError} When FIFO ordering is violated (409 with nextMessageId)\n * @throws {MessageCorruptedError} When message data is corrupted\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async receiveMessageById<T = unknown>(\n options: ReceiveMessageByIdOptions<T> & { skipPayload: true },\n transport?: Transport<T>,\n ): Promise<ReceiveMessageByIdResponse<T, true>>;\n async receiveMessageById<T = unknown>(\n options: ReceiveMessageByIdOptions<T> & { skipPayload?: false | undefined },\n transport: Transport<T>,\n ): Promise<ReceiveMessageByIdResponse<T, false>>;\n async receiveMessageById<T = unknown>(\n options: ReceiveMessageByIdOptions<T>,\n transport?: Transport<T>,\n ): Promise<ReceiveMessageByIdResponse<T, boolean>> {\n const {\n queueName,\n consumerGroup,\n messageId,\n visibilityTimeoutSeconds,\n skipPayload,\n } = options;\n\n const headers = new Headers({\n Authorization: `Bearer ${this.token}`,\n \"Vqs-Queue-Name\": queueName,\n \"Vqs-Consumer-Group\": consumerGroup,\n Accept: \"multipart/mixed\",\n });\n\n if (visibilityTimeoutSeconds !== undefined) {\n headers.set(\n \"Vqs-Visibility-Timeout\",\n visibilityTimeoutSeconds.toString(),\n );\n }\n\n if (skipPayload) {\n headers.set(\"Vqs-Skip-Payload\", \"1\");\n }\n\n const response = await fetch(\n `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,\n {\n method: \"GET\",\n headers,\n },\n );\n\n if (!response.ok) {\n if (response.status === 400) {\n const errorText = await response.text();\n throw new BadRequestError(errorText || \"Invalid parameters\");\n }\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n }\n if (response.status === 404) {\n // Message not found\n throw new MessageNotFoundError(messageId);\n }\n if (response.status === 423) {\n // Message is temporarily locked (FIFO queue)\n const retryAfterHeader = response.headers.get(\"Retry-After\");\n let retryAfter: number | undefined;\n if (retryAfterHeader) {\n const parsed = parseInt(retryAfterHeader, 10);\n retryAfter = isNaN(parsed) ? undefined : parsed;\n }\n throw new MessageLockedError(messageId, retryAfter);\n }\n if (response.status === 424) {\n // Failed dependency - FIFO ordering violation\n try {\n const errorData = (await response.json()) as {\n meta?: { nextMessageId?: string };\n };\n if (errorData.meta?.nextMessageId) {\n throw new FailedDependencyError(\n messageId,\n errorData.meta.nextMessageId,\n );\n }\n } catch (parseError) {\n // If we can't parse the error response or it's already a FailedDependencyError, rethrow\n if (parseError instanceof FailedDependencyError) {\n throw parseError;\n }\n }\n // Fallback if we can't parse the nextMessageId\n throw new MessageNotAvailableError(\n messageId,\n \"FIFO ordering violation\",\n );\n }\n if (response.status === 409) {\n // Message not available (wrong state, FIFO ordering violation, or claimed by another consumer)\n // For FIFO queues, this might include nextMessageId in the response\n try {\n const errorData = (await response.json()) as FifoOrderingError;\n if (errorData.nextMessageId) {\n throw new FifoOrderingViolationError(\n messageId,\n errorData.nextMessageId,\n errorData.error,\n );\n }\n } catch (parseError) {\n // If we can't parse the error response, fall back to generic message not available\n }\n throw new MessageNotAvailableError(messageId);\n }\n if (response.status >= 500) {\n throw new InternalServerError(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n throw new Error(\n `Failed to receive message by ID: ${response.status} ${response.statusText}`,\n );\n }\n\n // Handle skipPayload case with 204 response\n if (skipPayload && response.status === 204) {\n const parsedHeaders = parseQueueHeaders(response.headers);\n\n if (!parsedHeaders) {\n throw new MessageCorruptedError(\n messageId,\n \"Missing required queue headers in 204 response\",\n );\n }\n\n const message: Message<void> = {\n ...parsedHeaders,\n payload: undefined as void,\n };\n\n return { message } as ReceiveMessageByIdResponse<T, boolean>;\n }\n\n // Handle regular multipart response\n if (!transport) {\n throw new Error(\"Transport is required when skipPayload is not true\");\n }\n\n // Parse multipart/mixed response using streaming parser\n try {\n for await (const multipartMessage of parseMultipartStream(response)) {\n try {\n // Parse queue headers using the helper function\n const parsedHeaders = parseQueueHeaders(multipartMessage.headers);\n\n if (!parsedHeaders) {\n console.warn(\"Missing required queue headers in multipart part\");\n // Still need to consume the payload stream to let the parser proceed\n await consumeStream(multipartMessage.payload);\n continue;\n }\n\n // Deserialize using the provided transport (must consume the stream)\n const deserializedPayload = await transport.deserialize(\n multipartMessage.payload,\n );\n\n const message: Message<T> = {\n ...parsedHeaders,\n payload: deserializedPayload,\n };\n\n return { message };\n } catch (error) {\n console.warn(\"Failed to deserialize message by ID:\", error);\n // If deserialization failed, we still need to consume the payload stream\n // to let the multipart parser proceed to the next message\n await consumeStream(multipartMessage.payload);\n throw new MessageCorruptedError(\n messageId,\n `Failed to deserialize payload: ${error}`,\n );\n }\n }\n } catch (error) {\n if (error instanceof MessageCorruptedError) {\n throw error; // Re-throw our own errors\n }\n throw new MessageCorruptedError(\n messageId,\n `Failed to parse multipart response: ${error}`,\n );\n }\n\n // If we get here, no message was found in the multipart response\n throw new MessageNotFoundError(messageId);\n }\n\n /**\n * Delete a message (acknowledge processing)\n * @param options Delete message options\n * @returns Promise with delete status\n * @throws {MessageNotFoundError} When the message doesn't exist (404)\n * @throws {MessageNotAvailableError} When message can't be deleted (409)\n * @throws {BadRequestError} When ticket is missing or invalid (400)\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async deleteMessage(\n options: DeleteMessageOptions,\n ): Promise<DeleteMessageResponse> {\n const { queueName, consumerGroup, messageId, ticket } = options;\n\n const response = await fetch(\n `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,\n {\n method: \"DELETE\",\n headers: new Headers({\n Authorization: `Bearer ${this.token}`,\n \"Vqs-Queue-Name\": queueName,\n \"Vqs-Consumer-Group\": consumerGroup,\n \"Vqs-Ticket\": ticket,\n }),\n },\n );\n\n if (!response.ok) {\n if (response.status === 400) {\n throw new BadRequestError(\"Missing or invalid ticket\");\n }\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n }\n if (response.status === 404) {\n throw new MessageNotFoundError(messageId);\n }\n if (response.status === 409) {\n throw new MessageNotAvailableError(\n messageId,\n \"Invalid ticket, message not in correct state, or already processed\",\n );\n }\n if (response.status >= 500) {\n throw new InternalServerError(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n throw new Error(\n `Failed to delete message: ${response.status} ${response.statusText}`,\n );\n }\n\n return { deleted: true };\n }\n\n /**\n * Change the visibility timeout of a message\n * @param options Change visibility options\n * @returns Promise with update status\n * @throws {MessageNotFoundError} When the message doesn't exist (404)\n * @throws {MessageNotAvailableError} When message can't be updated (409)\n * @throws {BadRequestError} When ticket is missing or visibility timeout invalid (400)\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async changeVisibility(\n options: ChangeVisibilityOptions,\n ): Promise<ChangeVisibilityResponse> {\n const {\n queueName,\n consumerGroup,\n messageId,\n ticket,\n visibilityTimeoutSeconds,\n } = options;\n\n const response = await fetch(\n `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,\n {\n method: \"PATCH\",\n headers: new Headers({\n Authorization: `Bearer ${this.token}`,\n \"Vqs-Queue-Name\": queueName,\n \"Vqs-Consumer-Group\": consumerGroup,\n \"Vqs-Ticket\": ticket,\n \"Vqs-Visibility-Timeout\": visibilityTimeoutSeconds.toString(),\n }),\n },\n );\n\n if (!response.ok) {\n if (response.status === 400) {\n throw new BadRequestError(\n \"Missing ticket or invalid visibility timeout\",\n );\n }\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n }\n if (response.status === 404) {\n throw new MessageNotFoundError(messageId);\n }\n if (response.status === 409) {\n throw new MessageNotAvailableError(\n messageId,\n \"Invalid ticket, message not in correct state, or already processed\",\n );\n }\n if (response.status >= 500) {\n throw new InternalServerError(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n throw new Error(\n `Failed to change visibility: ${response.status} ${response.statusText}`,\n );\n }\n\n return { updated: true };\n }\n}\n","import { spawn } from \"node:child_process\";\nimport type { CallbackConfig, SendMessageResponse } from \"./types\";\n\n/**\n * Helper function to check if a URL is localhost with a non-zero port\n * for development callback handling\n */\nfunction isLocalhostWithPort(url: string): {\n isLocalhost: boolean;\n port?: number;\n} {\n try {\n const parsedUrl = new URL(url);\n const isLocalhost = parsedUrl.hostname === \"localhost\";\n const port = parsedUrl.port ? parseInt(parsedUrl.port, 10) : 0;\n return { isLocalhost, port };\n } catch {\n return { isLocalhost: false };\n }\n}\n\n/**\n * Check if the current platform supports localhost callback handling\n * @returns true if platform supports bash/nc/curl (macOS, Linux), false otherwise\n */\nfunction isSupportedPlatform(): boolean {\n const platform = process.platform;\n return platform === \"darwin\" || platform === \"linux\";\n}\n\n/**\n * Process callbacks for development mode - separates localhost callbacks from others\n * @param callbacks - The callback configurations\n * @returns Array of localhost callbacks to process after server response\n */\nexport function processDevelopmentCallbacks(\n callbacks: Record<string, CallbackConfig>,\n): Array<{\n group: string;\n config: CallbackConfig;\n port: number;\n}> {\n const isDevelopment = process.env.NODE_ENV === \"development\";\n\n if (!isDevelopment) {\n return [];\n }\n\n // Check if platform supports localhost callback handling\n if (!isSupportedPlatform()) {\n const hasLocalhostCallbacks = Object.values(callbacks).some((config) => {\n const { isLocalhost } = isLocalhostWithPort(config.url);\n return isLocalhost;\n });\n\n if (hasLocalhostCallbacks) {\n console.warn(\n `Queue Development Mode: Localhost callbacks are not supported on ${process.platform}. ` +\n `Localhost callback handling requires bash, nc, and curl which are available on macOS and Linux only. ` +\n `Consider using a production callback URL or developing on a supported platform.`,\n );\n }\n return [];\n }\n\n // Development mode - separate localhost callbacks and warn about others\n const localhostCallbacks: Array<{\n group: string;\n config: CallbackConfig;\n port: number;\n }> = [];\n\n Object.entries(callbacks).forEach(([group, config]) => {\n const { isLocalhost, port } = isLocalhostWithPort(config.url);\n if (isLocalhost && port && port > 0) {\n // Store localhost callback for processing after server response\n localhostCallbacks.push({ group, config, port });\n } else {\n // Log warning for non-localhost callbacks in development\n console.warn(\n `Queue Development Mode: Skipping non-localhost callback for group \"${group}\": ${config.url}. Only localhost callbacks with explicit ports are supported in development.`,\n );\n }\n });\n\n return localhostCallbacks;\n}\n\n/**\n * Fire localhost callbacks after successful message send in development mode\n * @param localhostCallbacks - Array of localhost callbacks to process\n * @param queueName - The queue name the message was sent to\n * @param responseData - The response from the server containing the message ID\n */\nexport function fireLocalhostCallbacks(\n localhostCallbacks: Array<{\n group: string;\n config: CallbackConfig;\n port: number;\n }>,\n queueName: string,\n responseData: SendMessageResponse,\n): void {\n localhostCallbacks.forEach(({ group, config, port }) => {\n // Create queue callback headers with real message ID from server response\n const callbackHeaders = new Headers();\n callbackHeaders.set(\"Vqs-Message-Id\", responseData.messageId);\n callbackHeaders.set(\"Vqs-Queue-Name\", queueName);\n callbackHeaders.set(\"Vqs-Consumer-Group\", group);\n\n // Fire-and-forget wait for localhost endpoints\n fireAndForgetWaitForHttpReady(\n config.url,\n port,\n config.delay || 0,\n 3, // Default retry frequency\n callbackHeaders,\n );\n });\n}\n\n/**\n * Fire-and-forget: check if `port` is listening, then that `url` returns 2xx.\n * If the port is closed twice in a row, the subprocess exits nonzero.\n * Otherwise it loops until both conditions succeed, with no further Node logic.\n *\n * Note: Only works on macOS and Linux (requires bash, nc, curl)\n *\n * @param {string} url – Full URL to check (e.g. \"http://localhost:3000/health\")\n * @param {number} port – TCP port to probe (e.g. 3000)\n * @param {number} initialDelaySeconds – How many seconds to sleep before first check\n * @param {number} retryFrequencySeconds – Seconds to wait between each check\n * @param {Headers} headers – Optional headers to include in the HTTP request\n */\nexport function fireAndForgetWaitForHttpReady(\n url: string,\n port: number,\n initialDelaySeconds: number = 0,\n retryFrequencySeconds: number = 3,\n headers?: Headers,\n) {\n // Early return if platform doesn't support bash/nc/curl\n if (!isSupportedPlatform()) {\n console.warn(\n `Queue: fireAndForgetWaitForHttpReady is not supported on ${process.platform}. ` +\n `This function requires bash, nc, and curl which are available on macOS and Linux only.`,\n );\n return;\n }\n // Convert headers to curl header arguments\n let headerArgs = \"\";\n if (headers) {\n const headerArray: string[] = [];\n headers.forEach((value, key) => {\n headerArray.push(`-H '${key}: ${value}'`);\n });\n headerArgs = headerArray.join(\" \");\n }\n\n // This entire loop lives inside a single Bash subprocess:\n const bashScript = `\n # Wait for any initial boot time\n sleep ${initialDelaySeconds}\n\n missed=0\n while true; do\n # 1) Check if TCP port is listening\n if nc -z localhost ${port} 2>/dev/null; then\n missed=0\n # 2) If port is open, try HTTP POST check\n if curl -sSL --fail -o /dev/null -X POST ${headerArgs} \"${url}\"; then\n # Success: port is up AND HTTP returned 2xx (following redirects)\n exit 0\n fi\n else\n # Port was closed—increment miss counter\n ((missed+=1))\n # If closed twice in a row, give up immediately\n if [ \"$missed\" -ge 2 ]; then\n exit 1\n fi\n fi\n # Wait before next cycle\n sleep ${retryFrequencySeconds}\n done\n `;\n\n // Spawn bash; stdio→ignore sends stdout/stderr to /dev/null\n const childProcess = spawn(\"bash\", [\"-c\", bashScript], {\n stdio: \"ignore\",\n detached: true,\n });\n\n // Unref the process so it doesn't keep the parent alive and can survive parent death\n childProcess.unref();\n\n // We do NOT attach any Node-side cleanup. Once spawned, this subprocess\n // lives on its own until it either exits 0 (success) or 1 (port missed twice).\n}\n","/**\n * Vercel Queue Service client types\n */\nimport type { Transport } from \"./transports\";\n\n// Re-export transport interface for convenience\nexport type { Transport };\n\nexport interface QueueClientOptions {\n /**\n * Base URL for the Vercel Queue Service API\n * @default \"https://vqs.vercel.sh\"\n */\n baseUrl?: string;\n /**\n * Vercel function OIDC token\n * Can be obtained from x-vercel-oidc-token header in Vercel Serverless Functions\n */\n token: string;\n}\n\n/**\n * Callback configuration for a consumer group\n */\nexport interface CallbackConfig {\n /**\n * Webhook URL to notify when messages are available\n */\n url: string;\n /**\n * Delay in seconds before sending the first callback\n */\n delay?: number;\n /**\n * Delay in seconds between retry attempts when the callback fails\n */\n frequency?: number;\n}\n\nexport interface SendMessageOptions<T = unknown> {\n /**\n * The queue name to send the message to\n */\n queueName: string;\n /**\n * The message payload\n */\n payload: T;\n /**\n * Unique key to prevent duplicate message submissions\n * @default random UUID\n */\n idempotencyKey?: string;\n /**\n * Message retention time in seconds\n * @default 86400 (24 hours)\n * @min 60\n * @max 86400\n */\n retentionSeconds?: number;\n /**\n * Consumer group callback configurations\n * Format: { consumerGroup: { url, delay?, frequency? } }\n */\n callbacks?: Record<string, CallbackConfig>;\n}\n\nexport interface SendMessageResponse {\n /**\n * The generated message ID\n */\n messageId: string;\n}\n\nexport interface Message<T = unknown> {\n /**\n * The message ID\n */\n messageId: string;\n /**\n * The deserialized message payload\n * Note: If using streaming transports, ensure proper cleanup by calling transport.finalize(payload)\n * when done processing, especially in error cases\n */\n payload: T;\n /**\n * Number of times this message has been delivered\n */\n deliveryCount: number;\n /**\n * Timestamp when the message was created\n */\n timestamp: string;\n /**\n * MIME type of the message content\n */\n contentType: string;\n /**\n * Unique ticket for this message delivery (required for delete/patch operations)\n */\n ticket: string;\n}\n\nexport interface ReceiveMessagesOptions<T = unknown> {\n /**\n * The queue name to receive messages from\n */\n queueName: string;\n /**\n * Consumer group name\n */\n consumerGroup: string;\n /**\n * Time in seconds that messages will be invisible to other consumers\n * @default 900 (15 minutes)\n */\n visibilityTimeoutSeconds?: number;\n /**\n * Maximum number of messages to retrieve\n * @default 10\n * @max 10\n * @note FIFO queues must use limit=1\n */\n limit?: number;\n}\n\nexport interface DeleteMessageOptions {\n /**\n * The queue name the message belongs to\n */\n queueName: string;\n /**\n * Consumer group name\n */\n consumerGroup: string;\n /**\n * The message ID to delete\n */\n messageId: string;\n /**\n * Ticket received from the message\n */\n ticket: string;\n}\n\nexport interface DeleteMessageResponse {\n /**\n * Whether the message was successfully deleted\n */\n deleted: boolean;\n}\n\nexport interface ChangeVisibilityOptions {\n /**\n * The queue name the message belongs to\n */\n queueName: string;\n /**\n * Consumer group name\n */\n consumerGroup: string;\n /**\n * The message ID to update\n */\n messageId: string;\n /**\n * Ticket received from the message\n */\n ticket: string;\n /**\n * New visibility timeout in seconds\n */\n visibilityTimeoutSeconds: number;\n}\n\nexport interface ChangeVisibilityResponse {\n /**\n * Whether the visibility was successfully updated\n */\n updated: boolean;\n}\n\n/**\n * Result indicating the message should be timed out for retry later\n */\nexport interface MessageTimeoutResult {\n /**\n * Time in seconds before the message becomes visible again\n */\n timeoutSeconds: number;\n}\n\n/**\n * Result returned by message handlers\n */\nexport type MessageHandlerResult = void | MessageTimeoutResult;\n\n/**\n * Message handler function type\n */\nexport type MessageHandler<T = unknown> = (\n message: Message<T>,\n) => Promise<MessageHandlerResult> | MessageHandlerResult;\n\n/**\n * Options for creating a ConsumerGroup instance\n */\nexport interface ConsumerGroupOptions<T = unknown> {\n /**\n * Serializer/deserializer for the payload\n * @default JsonTransport instance\n */\n transport?: Transport<T>;\n /**\n * Time in seconds that messages will be invisible to other consumers\n * @default 30\n */\n visibilityTimeoutSeconds?: number;\n /**\n * How often to refresh the visibility timeout during processing (in seconds)\n * @default 10\n */\n refreshInterval?: number;\n}\n\nexport interface ReceiveMessageByIdOptions<T = unknown> {\n /**\n * The queue name to receive the message from\n */\n queueName: string;\n /**\n * Consumer group name\n */\n consumerGroup: string;\n /**\n * The message ID to retrieve\n */\n messageId: string;\n /**\n * Time in seconds that the message will be invisible to other consumers\n * @default 900 (15 minutes)\n */\n visibilityTimeoutSeconds?: number;\n /**\n * Skip payload content and only return message metadata\n * When true, the server returns a 204 status with headers containing message metadata\n * @default false\n */\n skipPayload?: boolean;\n}\n\n// Response type that always contains a message (errors are thrown for failures)\nexport interface ReceiveMessageByIdResponse<\n T = unknown,\n TSkipPayload extends boolean = false,\n> {\n message: TSkipPayload extends true ? Message<void> : Message<T>;\n}\n\nexport interface FifoOrderingError {\n /**\n * Error message describing the FIFO ordering violation\n */\n error: string;\n /**\n * The message ID that must be processed first\n */\n nextMessageId: string;\n}\n\n/**\n * Error thrown when a message is not found (404)\n */\nexport class MessageNotFoundError extends Error {\n constructor(messageId: string) {\n super(`Message ${messageId} not found`);\n this.name = \"MessageNotFoundError\";\n }\n}\n\n/**\n * Error thrown when a message is not available for processing (409)\n * This can happen when the message is in the wrong state, already claimed, etc.\n */\nexport class MessageNotAvailableError extends Error {\n constructor(messageId: string, reason?: string) {\n super(\n `Message ${messageId} not available for processing${reason ? `: ${reason}` : \"\"}`,\n );\n this.name = \"MessageNotAvailableError\";\n }\n}\n\n/**\n * Error thrown when there's a FIFO ordering violation (409 with nextMessageId)\n */\nexport class FifoOrderingViolationError extends Error {\n public readonly nextMessageId: string;\n\n constructor(messageId: string, nextMessageId: string, reason: string) {\n super(\n `FIFO ordering violation for message ${messageId}: ${reason}. Process message ${nextMessageId} first.`,\n );\n this.name = \"FifoOrderingViolationError\";\n this.nextMessageId = nextMessageId;\n }\n}\n\n/**\n * Error thrown when message data is corrupted or can't be parsed\n */\nexport class MessageCorruptedError extends Error {\n constructor(messageId: string, reason: string) {\n super(`Message ${messageId} is corrupted: ${reason}`);\n this.name = \"MessageCorruptedError\";\n }\n}\n\n/**\n * Error thrown when there are no messages available in the queue (204)\n */\nexport class QueueEmptyError extends Error {\n constructor(queueName: string, consumerGroup: string) {\n super(\n `No messages available in queue \"${queueName}\" for consumer group \"${consumerGroup}\"`,\n );\n this.name = \"QueueEmptyError\";\n }\n}\n\n/**\n * Error thrown when a message is temporarily locked in a FIFO queue (423)\n */\nexport class MessageLockedError extends Error {\n public readonly retryAfter?: number;\n\n constructor(messageId: string, retryAfter?: number) {\n const retryMessage = retryAfter\n ? ` Retry after ${retryAfter} seconds.`\n : \" Try again later.\";\n super(`Message ${messageId} is temporarily locked.${retryMessage}`);\n this.name = \"MessageLockedError\";\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Error thrown when authentication fails (401)\n */\nexport class UnauthorizedError extends Error {\n constructor(message: string = \"Missing or invalid authentication token\") {\n super(message);\n this.name = \"UnauthorizedError\";\n }\n}\n\n/**\n * Error thrown when access is forbidden (403)\n */\nexport class ForbiddenError extends Error {\n constructor(\n message: string = \"Queue environment doesn't match token environment\",\n ) {\n super(message);\n this.name = \"ForbiddenError\";\n }\n}\n\n/**\n * Error thrown for bad requests (400)\n */\nexport class BadRequestError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BadRequestError\";\n }\n}\n\n/**\n * Error thrown when there's a failed dependency (424) - FIFO ordering violation in receive by ID\n */\nexport class FailedDependencyError extends Error {\n public readonly nextMessageId: string;\n\n constructor(messageId: string, nextMessageId: string) {\n super(\n `Failed dependency: FIFO ordering violation for message ${messageId}. Must process message ${nextMessageId} first.`,\n );\n this.name = \"FailedDependencyError\";\n this.nextMessageId = nextMessageId;\n }\n}\n\n/**\n * Error thrown for internal server errors (500)\n */\nexport class InternalServerError extends Error {\n constructor(message: string = \"Unexpected server error\") {\n super(message);\n this.name = \"InternalServerError\";\n }\n}\n\n/**\n * Error thrown when batch limit parameter is invalid\n */\nexport class InvalidLimitError extends Error {\n constructor(limit: number, min: number = 1, max: number = 10) {\n super(`Invalid limit: ${limit}. Limit must be between ${min} and ${max}.`);\n this.name = \"InvalidLimitError\";\n }\n}\n\n/**\n * Options extracted from a queue callback request\n */\nexport interface CallbackMessageOptions {\n /**\n * The queue name extracted from Vqs-Queue-Name header\n */\n queueName: string;\n /**\n * The consumer group extracted from Vqs-Consumer-Group header\n */\n consumerGroup: string;\n /**\n * The message ID extracted from Vqs-Message-Id header\n */\n messageId: string;\n}\n\n/**\n * Error thrown when queue callback headers are missing or invalid\n */\nexport class InvalidCallbackError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidCallbackError\";\n }\n}\n","/**\n * Serializer/Deserializer interface for message payloads\n */\nexport interface Transport<T = unknown> {\n /**\n * Serialize a value to a buffer or stream for transmission\n */\n serialize(value: T): Buffer | ReadableStream<Uint8Array>;\n\n /**\n * Deserialize a readable stream back to the original value\n */\n deserialize(stream: ReadableStream<Uint8Array>): Promise<T>;\n\n /**\n * Optional cleanup method for deserialized payloads that may contain resources\n * Should be called when the payload is no longer needed, especially in error cases\n * @param payload The deserialized payload to clean up\n */\n finalize?(payload: T): Promise<void>;\n\n /**\n * MIME type for this serialization format\n */\n contentType: string;\n}\n\n/**\n * Built-in JSON serializer/deserializer\n * This implementation reads the entire stream into memory for JSON parsing\n */\nexport class JsonTransport<T = unknown> implements Transport<T> {\n readonly contentType = \"application/json\";\n\n serialize(value: T): Buffer {\n return Buffer.from(JSON.stringify(value), \"utf8\");\n }\n\n async deserialize(stream: ReadableStream<Uint8Array>): Promise<T> {\n // JSON requires reading the entire payload to parse\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n // Combine chunks into a single buffer\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const buffer = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.length;\n }\n\n return JSON.parse(Buffer.from(buffer).toString(\"utf8\"));\n }\n}\n\n/**\n * Built-in Buffer serializer/deserializer (reads entire stream into a Buffer)\n */\nexport class BufferTransport implements Transport<Buffer> {\n readonly contentType = \"application/octet-stream\";\n\n serialize(value: Buffer): Buffer {\n return value;\n }\n\n async deserialize(stream: ReadableStream<Uint8Array>): Promise<Buffer> {\n // Buffer transport reads the entire stream into memory\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n // Combine chunks into a single buffer\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const buffer = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.length;\n }\n\n return Buffer.from(buffer);\n }\n}\n\n/**\n * Stream serializer/deserializer (pass-through for streaming binary data)\n * This is ideal for large payloads that don't need to be buffered in memory\n *\n * IMPORTANT: When using StreamTransport, you must call finalize(payload) when done\n * processing the message to prevent resource leaks, especially in error cases.\n * ConsumerGroup handles this automatically, but direct QueueClient usage requires manual cleanup.\n *\n * Example usage:\n * ```typescript\n * const transport = new StreamTransport();\n * try {\n * for await (const message of client.receiveMessages(options, transport)) {\n * // Process the stream...\n * const reader = message.payload.getReader();\n * // ... handle stream data\n * }\n * } catch (error) {\n * // Cleanup is handled automatically by ConsumerGroup\n * // or manually: await transport.finalize(message.payload);\n * }\n */\nexport class StreamTransport implements Transport<ReadableStream<Uint8Array>> {\n readonly contentType = \"application/octet-stream\";\n\n serialize(value: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n // Pass through the stream directly without buffering\n return value;\n }\n\n async deserialize(\n stream: ReadableStream<Uint8Array>,\n ): Promise<ReadableStream<Uint8Array>> {\n // Pass through the stream directly without buffering\n return stream;\n }\n\n async finalize(payload: ReadableStream<Uint8Array>): Promise<void> {\n // Consume any remaining stream data to prevent resource leaks\n const reader = payload.getReader();\n try {\n while (true) {\n const { done } = await reader.read();\n if (done) break;\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n","import { QueueClient } from \"./client\";\nimport type {\n ConsumerGroupOptions,\n MessageHandler,\n Transport,\n Message,\n} from \"./types\";\nimport {\n QueueEmptyError,\n MessageLockedError,\n InvalidLimitError,\n} from \"./types\";\nimport { JsonTransport } from \"./transports\";\n\n/**\n * A ConsumerGroup represents a named group of consumers that process messages from a topic\n */\nexport class ConsumerGroup<T = unknown> {\n private client: QueueClient;\n private topicName: string;\n private consumerGroupName: string;\n private visibilityTimeout: number;\n private refreshInterval: number;\n private transport: Transport<T>;\n\n /**\n * Create a new ConsumerGroup instance\n * @param client QueueClient instance to use for API calls\n * @param topicName Name of the topic to consume from\n * @param consumerGroupName Name of the consumer group\n * @param options Optional configuration\n */\n constructor(\n client: QueueClient,\n topicName: string,\n consumerGroupName: string,\n options: ConsumerGroupOptions<T> = {},\n ) {\n this.client = client;\n this.topicName = topicName;\n this.consumerGroupName = consumerGroupName;\n this.visibilityTimeout = options.visibilityTimeoutSeconds || 30; // 30 seconds default\n this.refreshInterval = options.refreshInterval || 10; // 10 seconds default\n this.transport = options.transport || new JsonTransport<T>();\n }\n\n /**\n * Starts a background loop that periodically extends the visibility timeout for a message.\n * This prevents the message from becoming visible to other consumers while it's being processed.\n *\n * The extension loop runs every `refreshInterval` seconds and updates the message's\n * visibility timeout to `visibilityTimeout` seconds from the current time.\n *\n * @param messageId - The unique identifier of the message to extend visibility for\n * @param ticket - The receipt ticket that proves ownership of the message\n * @returns A function that when called will stop the extension loop\n *\n * @remarks\n * - The first extension attempt occurs after `refreshInterval` seconds, not immediately\n * - If an extension fails, the loop terminates with an error logged to console\n * - The returned stop function is idempotent - calling it multiple times is safe\n * - By default, the stop function returns immediately without waiting for in-flight\n * - Pass `true` to the stop function to wait for any in-flight extension to complete\n */\n private startVisibilityExtension(\n messageId: string,\n ticket: string,\n ): (waitForCompletion?: boolean) => Promise<void> {\n let isRunning = true;\n let resolveLifecycle: () => void;\n let timeoutId: NodeJS.Timeout | null = null;\n\n // Promise that tracks the actual termination of the extension loop\n const lifecyclePromise = new Promise<void>((resolve) => {\n resolveLifecycle = resolve;\n });\n\n const extend = async (): Promise<void> => {\n // Check if we should stop before attempting extension\n if (!isRunning) {\n resolveLifecycle();\n return;\n }\n\n try {\n // Extend the visibility timeout for another period\n await this.client.changeVisibility({\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n messageId,\n ticket,\n visibilityTimeoutSeconds: this.visibilityTimeout,\n });\n\n // Schedule next extension if still running\n if (isRunning) {\n timeoutId = setTimeout(() => extend(), this.refreshInterval * 1000);\n } else {\n // Signal that the loop has terminated after successful extension\n resolveLifecycle();\n }\n } catch (error) {\n // Log error and terminate the loop on failure\n console.error(\n `Failed to extend visibility for message ${messageId}:`,\n error,\n );\n resolveLifecycle();\n }\n };\n\n // Schedule the first extension attempt\n timeoutId = setTimeout(() => extend(), this.refreshInterval * 1000);\n\n // Return a function to stop the extension loop\n return async (waitForCompletion: boolean = false) => {\n // Signal the loop to stop\n isRunning = false;\n\n // Cancel any pending timeout to avoid unnecessary waiting\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n // Only wait for in-flight operations if explicitly requested\n if (waitForCompletion) {\n // Wait for the loop to actually terminate\n // This ensures any in-progress extension completes or fails\n await lifecyclePromise;\n } else {\n // Resolve the lifecycle immediately for any waiting operations\n // This allows immediate return without waiting for in-flight extensions\n resolveLifecycle();\n }\n };\n }\n\n /**\n * Process a single message with the given handler\n * @param message The message to process\n * @param handler Function to process the message\n */\n private async processMessage<TPayload>(\n message: Message<TPayload>,\n handler: MessageHandler<TPayload>,\n ): Promise<void> {\n const stopExtension = this.startVisibilityExtension(\n message.messageId,\n message.ticket,\n );\n\n try {\n const result = await handler(message);\n // Stop extensions immediately - we don't need to wait for in-flight extensions\n // since we're about to delete or update the message visibility anyway\n await stopExtension();\n\n if (result && \"timeoutSeconds\" in result) {\n // Handle timeout request - set new visibility timeout instead of deleting\n await this.client.changeVisibility({\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n messageId: message.messageId,\n ticket: message.ticket,\n visibilityTimeoutSeconds: result.timeoutSeconds,\n });\n } else {\n // Normal completion - delete the message\n await this.client.deleteMessage({\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n messageId: message.messageId,\n ticket: message.ticket,\n });\n }\n } catch (error) {\n // Stop extensions immediately on error - fail fast without waiting\n // for any in-flight extension attempts\n await stopExtension();\n\n // Clean up the message payload if the transport supports it and payload exists\n // Only call finalize for non-void payloads since transport is typed for T, not void\n if (\n this.transport.finalize &&\n message.payload !== undefined &&\n message.payload !== null\n ) {\n try {\n // Safe cast: when processMessage<T> is called, TPayload is T\n // when processMessage<void> is called, payload is undefined so this won't execute\n await this.transport.finalize(message.payload as T);\n } catch (finalizeError) {\n console.warn(\"Failed to finalize message payload:\", finalizeError);\n }\n }\n\n throw error;\n }\n }\n\n /**\n * Start continuous processing of messages from the topic\n * @param signal AbortSignal to control when to stop processing\n * @param handler Function to process each message\n * @param options Processing options\n * @returns Promise that resolves when processing stops (due to signal or error)\n */\n async subscribe(\n signal: AbortSignal,\n handler: MessageHandler<T>,\n options: {\n pollingInterval?: number;\n } = {},\n ): Promise<void> {\n const pollingInterval = options.pollingInterval || 1000; // 1 second default\n\n while (!signal.aborted) {\n try {\n // Use the new streaming API - process messages as they arrive\n for await (const message of this.client.receiveMessages<T>(\n {\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n visibilityTimeoutSeconds: this.visibilityTimeout,\n limit: 1, // Always process one message at a time\n },\n this.transport,\n )) {\n if (signal.aborted) {\n break;\n }\n\n try {\n await this.processMessage<T>(message, handler);\n } catch (error) {\n console.error(\"Error processing message:\", error);\n }\n }\n\n // If we're not aborted, wait before polling again\n if (!signal.aborted) {\n await new Promise<void>((resolve) => {\n const timeoutId = setTimeout(resolve, pollingInterval);\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timeoutId);\n resolve();\n },\n { once: true },\n );\n });\n }\n } catch (error) {\n // Handle empty queue gracefully - just continue polling\n if (error instanceof QueueEmptyError) {\n // Queue is empty, wait before polling again\n if (!signal.aborted) {\n await new Promise<void>((resolve) => {\n const timeoutId = setTimeout(resolve, pollingInterval);\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timeoutId);\n resolve();\n },\n { once: true },\n );\n });\n }\n continue;\n }\n\n // Handle locked queue gracefully - just continue polling\n if (error instanceof MessageLockedError) {\n // FIFO queue is locked (next message in sequence is being processed), wait before polling again\n // Use the retryAfter if provided, otherwise use the polling interval\n const waitTime = error.retryAfter\n ? error.retryAfter * 1000\n : pollingInterval;\n if (!signal.aborted) {\n await new Promise<void>((resolve) => {\n const timeoutId = setTimeout(resolve, waitTime);\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timeoutId);\n resolve();\n },\n { once: true },\n );\n });\n }\n continue;\n }\n\n console.error(\"Error polling topic:\", error);\n throw error;\n }\n }\n }\n\n /**\n * Receive and process a specific message by its ID with full payload\n * @param messageId The ID of the message to receive and process\n * @param handler Function to process the message with full payload\n * @returns Promise that resolves when the message is processed or rejects with specific errors\n * @throws {MessageNotFoundError} When the message doesn't exist (404)\n * @throws {MessageNotAvailableError} When the message exists but isn't available for processing (409)\n * @throws {MessageLockedError} When the message is temporarily locked (423)\n * @throws {FifoOrderingViolationError} When there's a FIFO ordering violation (409 with nextMessageId)\n * @throws {FailedDependencyError} When FIFO ordering is violated (424)\n * @throws {MessageCorruptedError} When the message data is corrupted\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied\n * @throws {InternalServerError} When server encounters an error\n */\n async receiveMessage(\n messageId: string,\n handler: MessageHandler<T>,\n ): Promise<void> {\n const response = await this.client.receiveMessageById(\n {\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n messageId,\n visibilityTimeoutSeconds: this.visibilityTimeout,\n },\n this.transport,\n );\n\n // No null check needed - client throws specific errors for failures\n await this.processMessage<T>(response.message, handler);\n }\n\n /**\n * Receive and process the next available message from the queue\n * @param handler Function to process the message\n * @returns Promise that resolves when the message is processed or rejects with specific errors\n * @throws {QueueEmptyError} When no messages are available in the queue (204)\n * @throws {MessageLockedError} When the next message in a FIFO queue is locked (423)\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied\n * @throws {InternalServerError} When server encounters an error\n */\n async receiveNextMessage(handler: MessageHandler<T>): Promise<void> {\n // Get next available message\n let messageFound = false;\n\n for await (const message of this.client.receiveMessages<T>(\n {\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n visibilityTimeoutSeconds: this.visibilityTimeout,\n limit: 1,\n },\n this.transport,\n )) {\n messageFound = true;\n await this.processMessage<T>(message, handler);\n break; // Process only one message\n }\n\n // If we get here without finding a message, the async generator\n // should have already thrown QueueEmptyError, but just in case\n if (!messageFound) {\n throw new Error(\"No messages available\");\n }\n }\n\n /**\n * Receive and process multiple next available messages from the queue\n * @param limit Number of messages to process (1-10)\n * @param handler Function to process each message\n * @returns Promise that resolves to an array of PromiseSettledResult (same as Promise.allSettled)\n * @throws {InvalidLimitError} When limit parameter is not between 1 and 10\n * @throws {QueueEmptyError} When no messages are available in the queue (204)\n * @throws {MessageLockedError} When the next message in a FIFO queue is locked (423)\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied\n * @throws {InternalServerError} When server encounters an error\n */\n async receiveNextMessages(\n limit: number,\n handler: MessageHandler<T>,\n ): Promise<PromiseSettledResult<void>[]> {\n // Validate limit\n if (limit < 1 || limit > 10) {\n throw new InvalidLimitError(limit);\n }\n\n const processingPromises: Promise<PromiseSettledResult<void>>[] = [];\n let messageCount = 0;\n\n // Consume the iterator naturally, collecting processing promises\n for await (const message of this.client.receiveMessages<T>(\n {\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n visibilityTimeoutSeconds: this.visibilityTimeout,\n limit,\n },\n this.transport,\n )) {\n messageCount++;\n\n // Wrap each processing promise to always resolve with PromiseSettledResult\n // This prevents unhandled promise rejections while preserving error information\n const wrappedPromise = this.processMessage<T>(message, handler).then(\n (value): PromiseFulfilledResult<void> => ({\n status: \"fulfilled\",\n value,\n }),\n (reason): PromiseRejectedResult => ({ status: \"rejected\", reason }),\n );\n\n processingPromises.push(wrappedPromise);\n }\n\n // If no messages were processed, the async generator should have thrown QueueEmptyError\n if (messageCount === 0) {\n throw new Error(\"No messages available\");\n }\n\n // Use Promise.all since all promises are guaranteed to resolve\n const results = await Promise.all(processingPromises);\n\n // Return the settled results array (same as Promise.allSettled would return)\n return results;\n }\n\n /**\n * Handle a specific message by its ID without downloading the payload (metadata only)\n * @param messageId The ID of the message to handle\n * @param handler Function to process the message metadata (payload will be void)\n * @returns Promise that resolves when the message is handled or rejects with specific errors\n * @throws {MessageNotFoundError} When the message doesn't exist (404)\n * @throws {MessageNotAvailableError} When the message exists but isn't available for processing (409)\n * @throws {MessageLockedError} When the message is temporarily locked (423)\n * @throws {FifoOrderingViolationError} When there's a FIFO ordering violation (409 with nextMessageId)\n * @throws {FailedDependencyError} When FIFO ordering is violated (424)\n * @throws {MessageCorruptedError} When the message data is corrupted\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied\n * @throws {InternalServerError} When server encounters an error\n */\n async handleMessage(\n messageId: string,\n handler: MessageHandler<void>,\n ): Promise<void> {\n const response = await this.client.receiveMessageById(\n {\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n messageId,\n visibilityTimeoutSeconds: this.visibilityTimeout,\n skipPayload: true,\n },\n this.transport,\n );\n\n // No null check needed - client throws specific errors for failures\n await this.processMessage<void>(response.message, handler);\n }\n\n /**\n * Get the consumer group name\n */\n get name(): string {\n return this.consumerGroupName;\n }\n\n /**\n * Get the topic name this consumer group is subscribed to\n */\n get topic(): string {\n return this.topicName;\n }\n}\n","import { QueueClient } from \"./client\";\nimport { ConsumerGroup } from \"./consumer-group\";\nimport type { ConsumerGroupOptions, CallbackConfig, Transport } from \"./types\";\nimport { JsonTransport } from \"./transports\";\n\n/**\n * A Topic represents a named channel for publishing messages in a pub/sub pattern\n */\nexport class Topic<T = unknown> {\n private client: QueueClient;\n private topicName: string;\n private transport: Transport<T>;\n\n /**\n * Create a new Topic instance\n * @param client QueueClient instance to use for API calls\n * @param topicName Name of the topic to work with\n * @param transport Optional serializer/deserializer for the payload (defaults to JSON)\n */\n constructor(\n client: QueueClient,\n topicName: string,\n transport?: Transport<T>,\n ) {\n this.client = client;\n this.topicName = topicName;\n this.transport = transport || new JsonTransport<T>();\n }\n\n /**\n * Publish a message to the topic\n * @param payload The data to publish\n * @param options Optional publish options\n * @returns An object containing the message ID\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async publish(\n payload: T,\n options?: {\n idempotencyKey?: string;\n retentionSeconds?: number;\n callbacks?: Record<string, CallbackConfig>;\n },\n ): Promise<{ messageId: string }> {\n const result = await this.client.sendMessage<T>(\n {\n queueName: this.topicName,\n payload,\n idempotencyKey: options?.idempotencyKey,\n retentionSeconds: options?.retentionSeconds,\n callbacks: options?.callbacks,\n },\n this.transport,\n );\n return { messageId: result.messageId };\n }\n\n /**\n * Create a consumer group for this topic\n * @param consumerGroupName Name of the consumer group\n * @param options Optional configuration for the consumer group\n * @returns A ConsumerGroup instance\n */\n consumerGroup<U = T>(\n consumerGroupName: string,\n options?: ConsumerGroupOptions<U>,\n ): ConsumerGroup<U> {\n // If no transport is provided in options, use the topic's transport if types match\n const consumerOptions: ConsumerGroupOptions<U> = {\n ...options,\n transport:\n options?.transport || (this.transport as unknown as Transport<U>),\n };\n\n return new ConsumerGroup<U>(\n this.client,\n this.topicName,\n consumerGroupName,\n consumerOptions,\n );\n }\n\n /**\n * Get the topic name\n */\n get name(): string {\n return this.topicName;\n }\n\n /**\n * Get the transport used by this topic\n */\n get serializer(): Transport<T> {\n return this.transport;\n }\n}\n","import { QueueClient } from \"./client\";\nimport { Topic } from \"./topic\";\nimport type { Transport } from \"./types\";\n\n/**\n * Create a new Topic instance\n * @param client QueueClient instance to use for API calls\n * @param topicName Name of the topic\n * @param transport Optional serializer/deserializer for the payload (defaults to JSON)\n * @returns A Topic instance\n */\nexport function createTopic<T = unknown>(\n client: QueueClient,\n topicName: string,\n transport?: Transport<T>,\n): Topic<T> {\n return new Topic<T>(client, topicName, transport);\n}\n","/**\n * Queue Callback utilities for handling incoming webhook payloads\n */\nimport type { CallbackMessageOptions } from \"./types\";\nimport { InvalidCallbackError } from \"./types\";\n\n/**\n * Parse a queue callback request and extract the required information for receiveMessageById\n *\n * @param request The incoming Request object from the queue callback\n * @returns CallbackMessageOptions that can be used with receiveMessageById\n * @throws {InvalidCallbackError} When required queue headers are missing or invalid\n *\n * @example\n * ```typescript\n * import { parseCallbackRequest } from '@vercel/queue';\n *\n * // In your webhook handler\n * export async function POST(request: Request) {\n * try {\n * const callbackOptions = parseCallbackRequest(request);\n *\n * // Use with receiveMessageById\n * const message = await client.receiveMessageById({\n * ...callbackOptions,\n * visibilityTimeoutSeconds: 30\n * }, transport);\n *\n * // Process the message...\n * } catch (error) {\n * if (error instanceof InvalidCallbackError) {\n * return new Response('Invalid callback', { status: 400 });\n * }\n * throw error;\n * }\n * }\n * ```\n */\nexport function parseCallbackRequest(request: Request): CallbackMessageOptions {\n const headers = request.headers;\n\n // Extract required queue headers\n const messageId = headers.get(\"Vqs-Message-Id\");\n const queueName = headers.get(\"Vqs-Queue-Name\");\n const consumerGroup = headers.get(\"Vqs-Consumer-Group\");\n\n // Validate all required headers are present\n const missingHeaders: string[] = [];\n if (!messageId) missingHeaders.push(\"Vqs-Message-Id\");\n if (!queueName) missingHeaders.push(\"Vqs-Queue-Name\");\n if (!consumerGroup) missingHeaders.push(\"Vqs-Consumer-Group\");\n\n if (missingHeaders.length > 0) {\n throw new InvalidCallbackError(\n `Missing required queue callback headers: ${missingHeaders.join(\", \")}`,\n );\n }\n\n return {\n messageId: messageId!,\n queueName: queueName!,\n consumerGroup: consumerGroup!,\n };\n}\n"],"mappings":";AAAA,eAAsB,qBAAsC;AAC1D,QAAM,yBAAyB,OAAO,IAAI,yBAAyB;AACnE,QAAM,aAAa;AACnB,QAAM,UAAU,WAAW,sBAAsB,GAAG,MAAM,KAAK,CAAC;AAEhE,QAAM,QACJ,QAAQ,UAAU,qBAAqB,KAAK,QAAQ,IAAI;AAE1D,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;;;ACdA,SAAS,4BAA4B;;;ACDrC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AAI,OAAe;AACjB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,aAA2B;AAC7B,WAAO,KAAK;AAAA,EACd;AACF;;;ACvFO,SAAS,YACd,QACA,WACA,WACU;AACV,SAAO,IAAI,MAAS,QAAQ,WAAW,SAAS;AAClD;;;ACqBO,SAAS,qBAAqB,SAA0C;AAC7E,QAAM,UAAU,QAAQ;AAGxB,QAAM,YAAY,QAAQ,IAAI,gBAAgB;AAC9C,QAAM,YAAY,QAAQ,IAAI,gBAAgB;AAC9C,QAAM,gBAAgB,QAAQ,IAAI,oBAAoB;AAGtD,QAAM,iBAA2B,CAAC;AAClC,MAAI,CAAC,UAAW,gBAAe,KAAK,gBAAgB;AACpD,MAAI,CAAC,UAAW,gBAAe,KAAK,gBAAgB;AACpD,MAAI,CAAC,cAAe,gBAAe,KAAK,oBAAoB;AAE5D,MAAI,eAAe,SAAS,GAAG;AAC7B,UAAM,IAAI;AAAA,MACR,4CAA4C,eAAe,KAAK,IAAI,CAAC;AAAA,IACvE;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/client.ts","../src/local.ts","../src/types.ts","../src/transports.ts","../src/consumer-group.ts","../src/topic.ts","../src/factory.ts","../src/callback.ts"],"sourcesContent":["import { getVercelOidcToken } from \"./oidc\";\nimport { parseMultipartStream } from \"mixpart\";\nimport { processDevelopmentCallbacks, fireLocalhostCallbacks } from \"./local\";\nimport {\n FifoOrderingViolationError,\n MessageCorruptedError,\n MessageNotAvailableError,\n MessageNotFoundError,\n QueueEmptyError,\n MessageLockedError,\n UnauthorizedError,\n ForbiddenError,\n BadRequestError,\n FailedDependencyError,\n InternalServerError,\n InvalidLimitError,\n} from \"./types\";\nimport type {\n CallbackConfig,\n ChangeVisibilityOptions,\n ChangeVisibilityResponse,\n DeleteMessageOptions,\n DeleteMessageResponse,\n Message,\n ReceiveMessageByIdOptions,\n ReceiveMessageByIdResponse,\n ReceiveMessagesOptions,\n SendMessageOptions,\n SendMessageResponse,\n Transport,\n QueueClientOptions,\n} from \"./types\";\n\n/**\n * Helper function to consume a ReadableStream to completion\n * This is necessary when we need to drain a stream to let the multipart parser proceed\n */\nasync function consumeStream(\n stream: ReadableStream<Uint8Array>,\n): Promise<void> {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done } = await reader.read();\n if (done) break;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * Helper function to parse queue headers into a partial message object\n * Handles both multipart message headers and HTTP response headers\n */\nfunction parseQueueHeaders(\n headers: Headers,\n): Omit<Message<unknown>, \"payload\"> | null {\n const messageId = headers.get(\"Vqs-Message-Id\");\n const deliveryCountStr = headers.get(\"Vqs-Delivery-Count\") || \"0\";\n const timestamp = headers.get(\"Vqs-Timestamp\");\n const contentType = headers.get(\"Content-Type\") || \"application/octet-stream\";\n const ticket = headers.get(\"Vqs-Ticket\");\n\n if (!messageId || !timestamp || !ticket) {\n return null;\n }\n\n const deliveryCount = parseInt(deliveryCountStr, 10);\n if (isNaN(deliveryCount)) {\n return null;\n }\n\n return {\n messageId,\n deliveryCount,\n timestamp,\n contentType,\n ticket,\n };\n}\n\n/**\n * Client for interacting with the Vercel Queue Service API\n */\nexport class QueueClient {\n private baseUrl: string;\n private token: string;\n\n /**\n * Internal default instance for use by createTopic and other convenience functions\n * @internal\n */\n private static _defaultInstance: QueueClient | null = null;\n\n /**\n * Create a new Vercel Queue Service client\n * @param options Client configuration options (optional - will auto-detect Vercel Function environment)\n */\n constructor(options: QueueClientOptions = {}) {\n this.baseUrl = options.baseUrl || \"https://vqs.vercel.sh\";\n\n if (options.token) {\n this.token = options.token;\n } else {\n // Try to get OIDC token from Vercel Function environment\n const token = this.getVercelOidcTokenSync();\n if (!token) {\n throw new Error(\n \"Failed to get OIDC token from Vercel Functions. \" +\n \"Make sure you are running in a Vercel Function environment, or provide a token explicitly.\\n\\n\" +\n \"To set up your environment:\\n\" +\n \"1. Link your project: 'vercel link'\\n\" +\n \"2. Pull environment variables: 'vercel env pull'\\n\" +\n \"3. Run with environment: 'dotenv -e .env.local -- your-command'\",\n );\n }\n this.token = token;\n }\n }\n\n /**\n * Get the default client instance for internal use by convenience functions\n * @internal\n */\n static _getDefaultInstance(): QueueClient {\n if (!this._defaultInstance) {\n this._defaultInstance = new QueueClient();\n }\n return this._defaultInstance;\n }\n\n /**\n * Synchronously get OIDC token from environment\n * Used internally by constructor - mirrors the logic from getVercelOidcToken but synchronously\n */\n private getVercelOidcTokenSync(): string | null {\n try {\n // Check for OIDC token in request context (same logic as async version)\n const SYMBOL_FOR_REQ_CONTEXT = Symbol.for(\"@vercel/request-context\");\n const fromSymbol = globalThis as any;\n const context = fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};\n\n const token =\n context.headers?.[\"x-vercel-oidc-token\"] ??\n process.env.VERCEL_OIDC_TOKEN;\n\n return token || null;\n } catch {\n return null;\n }\n }\n\n /**\n * Send a message to a queue\n * @param options Send message options\n * @param transport Serializer/deserializer for the payload\n * @returns Promise with the message ID\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async sendMessage<T = unknown>(\n options: SendMessageOptions<T>,\n transport: Transport<T>,\n ): Promise<SendMessageResponse> {\n const { queueName, payload, idempotencyKey, retentionSeconds, callback } =\n options;\n\n const headers = new Headers({\n Authorization: `Bearer ${this.token}`,\n \"Vqs-Queue-Name\": queueName,\n \"Content-Type\": transport.contentType,\n });\n\n if (idempotencyKey) {\n headers.set(\"Vqs-Idempotency-Key\", idempotencyKey);\n }\n\n if (retentionSeconds !== undefined) {\n headers.set(\"Vqs-Retention-Seconds\", retentionSeconds.toString());\n }\n\n // Normalize callback to Record<string, CallbackConfig>\n let normalizedCallbacks: Record<string, CallbackConfig> | undefined;\n if (callback) {\n if (\"url\" in callback && typeof callback.url === \"string\") {\n // Single CallbackConfig - use \"default\" consumer group\n normalizedCallbacks = { default: callback as CallbackConfig };\n } else {\n // Already a Record<string, CallbackConfig>\n normalizedCallbacks = callback as Record<string, CallbackConfig>;\n }\n }\n\n // Handle callbacks based on environment\n let localhostCallbacks: Array<{\n group: string;\n config: CallbackConfig;\n port: number;\n }> = [];\n\n if (normalizedCallbacks) {\n const isDevelopment = process.env.NODE_ENV === \"development\";\n\n if (isDevelopment) {\n // Development mode - process localhost callbacks only\n localhostCallbacks = processDevelopmentCallbacks(normalizedCallbacks);\n } else {\n // Production mode - set normal callback headers for all callbacks\n const endpoints = Object.entries(normalizedCallbacks)\n .map(\n ([group, config]) =>\n `${group}=${Buffer.from(config.url).toString(\"base64\")}`,\n )\n .join(\",\");\n headers.set(\"Vqs-Callback-Url\", endpoints);\n\n const delays = Object.entries(normalizedCallbacks)\n .filter(([, config]) => config.delay !== undefined)\n .map(([group, config]) => `${group}=${config.delay}`)\n .join(\",\");\n if (delays) {\n headers.set(\"Vqs-Callback-Delay\", delays);\n }\n\n const frequencies = Object.entries(normalizedCallbacks)\n .filter(([, config]) => config.frequency !== undefined)\n .map(([group, config]) => `${group}=${config.frequency}`)\n .join(\",\");\n if (frequencies) {\n headers.set(\"Vqs-Callback-Frequency\", frequencies);\n }\n }\n }\n\n // Serialize the payload using the provided transport\n const body = transport.serialize(payload);\n\n const response = await fetch(`${this.baseUrl}/api/v2/messages`, {\n method: \"POST\",\n headers,\n body,\n });\n\n if (!response.ok) {\n if (response.status === 400) {\n const errorText = await response.text();\n throw new BadRequestError(errorText || \"Invalid parameters\");\n }\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n }\n if (response.status === 409) {\n throw new Error(\"Duplicate idempotency key detected\");\n }\n if (response.status >= 500) {\n throw new InternalServerError(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n throw new Error(\n `Failed to send message: ${response.status} ${response.statusText}`,\n );\n }\n\n const responseData = (await response.json()) as SendMessageResponse;\n\n // Fire localhost callbacks in development mode after successful server response\n if (localhostCallbacks.length > 0) {\n fireLocalhostCallbacks(localhostCallbacks, queueName, responseData);\n }\n\n return responseData;\n }\n\n /**\n * Receive messages from a queue\n * @param options Receive messages options\n * @param transport Serializer/deserializer for the payload\n * @returns AsyncGenerator that yields messages as they arrive\n * @throws {InvalidLimitError} When limit parameter is not between 1 and 10\n * @throws {QueueEmptyError} When no messages are available (204)\n * @throws {MessageLockedError} When FIFO queue has locked messages (423)\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async *receiveMessages<T = unknown>(\n options: ReceiveMessagesOptions<T>,\n transport: Transport<T>,\n ): AsyncGenerator<Message<T>, void, unknown> {\n const { queueName, consumerGroup, visibilityTimeoutSeconds, limit } =\n options;\n\n // Validate limit parameter\n if (limit !== undefined && (limit < 1 || limit > 10)) {\n throw new InvalidLimitError(limit);\n }\n\n const headers = new Headers({\n Authorization: `Bearer ${this.token}`,\n \"Vqs-Queue-Name\": queueName,\n \"Vqs-Consumer-Group\": consumerGroup,\n Accept: \"multipart/mixed\",\n });\n\n if (visibilityTimeoutSeconds !== undefined) {\n headers.set(\n \"Vqs-Visibility-Timeout\",\n visibilityTimeoutSeconds.toString(),\n );\n }\n\n if (limit !== undefined) {\n headers.set(\"Vqs-Limit\", limit.toString());\n }\n\n const response = await fetch(`${this.baseUrl}/api/v2/messages`, {\n method: \"GET\",\n headers,\n });\n\n // Check for 204 No Content - queue is empty\n if (response.status === 204) {\n throw new QueueEmptyError(queueName, consumerGroup);\n }\n\n if (!response.ok) {\n if (response.status === 400) {\n const errorText = await response.text();\n throw new BadRequestError(errorText || \"Invalid parameters\");\n }\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n }\n if (response.status === 423) {\n // FIFO queue locked - next message in sequence is being processed\n const retryAfterHeader = response.headers.get(\"Retry-After\");\n let retryAfter: number | undefined;\n if (retryAfterHeader) {\n const parsed = parseInt(retryAfterHeader, 10);\n retryAfter = isNaN(parsed) ? undefined : parsed;\n }\n throw new MessageLockedError(\"next message in FIFO queue\", retryAfter);\n }\n if (response.status >= 500) {\n throw new InternalServerError(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n throw new Error(\n `Failed to receive messages: ${response.status} ${response.statusText}`,\n );\n }\n\n // Stream messages as they arrive from the multipart parser\n // Each message's payload stream must be consumed immediately for the parser to proceed\n for await (const multipartMessage of parseMultipartStream(response)) {\n try {\n // Parse VQS headers using the helper function\n const parsedHeaders = parseQueueHeaders(multipartMessage.headers);\n\n if (!parsedHeaders) {\n console.warn(\"Missing required queue headers in multipart part\");\n // Still need to consume the payload stream to let the parser proceed\n await consumeStream(multipartMessage.payload);\n continue;\n }\n\n // Deserialize using the provided transport (must consume the stream)\n const deserializedPayload = await transport.deserialize(\n multipartMessage.payload,\n );\n\n const message: Message<T> = {\n ...parsedHeaders,\n payload: deserializedPayload,\n };\n\n yield message;\n } catch (error) {\n console.warn(\"Failed to process multipart message:\", error);\n // If deserialization failed, we still need to consume the payload stream\n // to let the multipart parser proceed to the next message\n await consumeStream(multipartMessage.payload);\n }\n }\n }\n\n /**\n * Receive a specific message by its ID from a queue\n * @param options Receive message by ID options\n * @param transport Serializer/deserializer for the payload\n * @returns Promise with the message or null if not found/available\n * @throws {MessageNotFoundError} When the message doesn't exist (404)\n * @throws {MessageLockedError} When the message is temporarily locked (423)\n * @throws {FailedDependencyError} When FIFO ordering is violated (424)\n * @throws {MessageNotAvailableError} When message exists but isn't available (409)\n * @throws {MessageCorruptedError} When message data is corrupted\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async receiveMessageById<T = unknown>(\n options: ReceiveMessageByIdOptions<T> & { skipPayload: true },\n transport?: Transport<T>,\n ): Promise<ReceiveMessageByIdResponse<T, true>>;\n async receiveMessageById<T = unknown>(\n options: ReceiveMessageByIdOptions<T> & { skipPayload?: false | undefined },\n transport: Transport<T>,\n ): Promise<ReceiveMessageByIdResponse<T, false>>;\n async receiveMessageById<T = unknown>(\n options: ReceiveMessageByIdOptions<T>,\n transport?: Transport<T>,\n ): Promise<ReceiveMessageByIdResponse<T, boolean>> {\n const {\n queueName,\n consumerGroup,\n messageId,\n visibilityTimeoutSeconds,\n skipPayload,\n } = options;\n\n const headers = new Headers({\n Authorization: `Bearer ${this.token}`,\n \"Vqs-Queue-Name\": queueName,\n \"Vqs-Consumer-Group\": consumerGroup,\n Accept: \"multipart/mixed\",\n });\n\n if (visibilityTimeoutSeconds !== undefined) {\n headers.set(\n \"Vqs-Visibility-Timeout\",\n visibilityTimeoutSeconds.toString(),\n );\n }\n\n if (skipPayload) {\n headers.set(\"Vqs-Skip-Payload\", \"1\");\n }\n\n const response = await fetch(\n `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,\n {\n method: \"GET\",\n headers,\n },\n );\n\n if (!response.ok) {\n if (response.status === 400) {\n const errorText = await response.text();\n throw new BadRequestError(errorText || \"Invalid parameters\");\n }\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n }\n if (response.status === 404) {\n // Message not found\n throw new MessageNotFoundError(messageId);\n }\n if (response.status === 423) {\n // Message is temporarily locked (FIFO queue)\n const retryAfterHeader = response.headers.get(\"Retry-After\");\n let retryAfter: number | undefined;\n if (retryAfterHeader) {\n const parsed = parseInt(retryAfterHeader, 10);\n retryAfter = isNaN(parsed) ? undefined : parsed;\n }\n throw new MessageLockedError(messageId, retryAfter);\n }\n if (response.status === 424) {\n // Failed dependency - FIFO ordering violation\n throw new FailedDependencyError(messageId);\n }\n if (response.status === 409) {\n // Message not available (wrong state, FIFO ordering violation, or claimed by another consumer)\n throw new MessageNotAvailableError(messageId);\n }\n if (response.status >= 500) {\n throw new InternalServerError(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n throw new Error(\n `Failed to receive message by ID: ${response.status} ${response.statusText}`,\n );\n }\n\n // Handle skipPayload case with 204 response\n if (skipPayload && response.status === 204) {\n const parsedHeaders = parseQueueHeaders(response.headers);\n\n if (!parsedHeaders) {\n throw new MessageCorruptedError(\n messageId,\n \"Missing required queue headers in 204 response\",\n );\n }\n\n const message: Message<void> = {\n ...parsedHeaders,\n payload: undefined as void,\n };\n\n return { message } as ReceiveMessageByIdResponse<T, boolean>;\n }\n\n // Handle regular multipart response\n if (!transport) {\n throw new Error(\"Transport is required when skipPayload is not true\");\n }\n\n // Parse multipart/mixed response using streaming parser\n try {\n for await (const multipartMessage of parseMultipartStream(response)) {\n try {\n // Parse queue headers using the helper function\n const parsedHeaders = parseQueueHeaders(multipartMessage.headers);\n\n if (!parsedHeaders) {\n console.warn(\"Missing required queue headers in multipart part\");\n // Still need to consume the payload stream to let the parser proceed\n await consumeStream(multipartMessage.payload);\n continue;\n }\n\n // Deserialize using the provided transport (must consume the stream)\n const deserializedPayload = await transport.deserialize(\n multipartMessage.payload,\n );\n\n const message: Message<T> = {\n ...parsedHeaders,\n payload: deserializedPayload,\n };\n\n return { message };\n } catch (error) {\n console.warn(\"Failed to deserialize message by ID:\", error);\n // If deserialization failed, we still need to consume the payload stream\n // to let the multipart parser proceed to the next message\n await consumeStream(multipartMessage.payload);\n throw new MessageCorruptedError(\n messageId,\n `Failed to deserialize payload: ${error}`,\n );\n }\n }\n } catch (error) {\n if (error instanceof MessageCorruptedError) {\n throw error; // Re-throw our own errors\n }\n throw new MessageCorruptedError(\n messageId,\n `Failed to parse multipart response: ${error}`,\n );\n }\n\n // If we get here, no message was found in the multipart response\n throw new MessageNotFoundError(messageId);\n }\n\n /**\n * Delete a message (acknowledge processing)\n * @param options Delete message options\n * @returns Promise with delete status\n * @throws {MessageNotFoundError} When the message doesn't exist (404)\n * @throws {MessageNotAvailableError} When message can't be deleted (409)\n * @throws {BadRequestError} When ticket is missing or invalid (400)\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async deleteMessage(\n options: DeleteMessageOptions,\n ): Promise<DeleteMessageResponse> {\n const { queueName, consumerGroup, messageId, ticket } = options;\n\n const response = await fetch(\n `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,\n {\n method: \"DELETE\",\n headers: new Headers({\n Authorization: `Bearer ${this.token}`,\n \"Vqs-Queue-Name\": queueName,\n \"Vqs-Consumer-Group\": consumerGroup,\n \"Vqs-Ticket\": ticket,\n }),\n },\n );\n\n if (!response.ok) {\n if (response.status === 400) {\n throw new BadRequestError(\"Missing or invalid ticket\");\n }\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n }\n if (response.status === 404) {\n throw new MessageNotFoundError(messageId);\n }\n if (response.status === 409) {\n throw new MessageNotAvailableError(\n messageId,\n \"Invalid ticket, message not in correct state, or already processed\",\n );\n }\n if (response.status >= 500) {\n throw new InternalServerError(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n throw new Error(\n `Failed to delete message: ${response.status} ${response.statusText}`,\n );\n }\n\n return { deleted: true };\n }\n\n /**\n * Change the visibility timeout of a message\n * @param options Change visibility options\n * @returns Promise with update status\n * @throws {MessageNotFoundError} When the message doesn't exist (404)\n * @throws {MessageNotAvailableError} When message can't be updated (409)\n * @throws {BadRequestError} When ticket is missing or visibility timeout invalid (400)\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async changeVisibility(\n options: ChangeVisibilityOptions,\n ): Promise<ChangeVisibilityResponse> {\n const {\n queueName,\n consumerGroup,\n messageId,\n ticket,\n visibilityTimeoutSeconds,\n } = options;\n\n const response = await fetch(\n `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,\n {\n method: \"PATCH\",\n headers: new Headers({\n Authorization: `Bearer ${this.token}`,\n \"Vqs-Queue-Name\": queueName,\n \"Vqs-Consumer-Group\": consumerGroup,\n \"Vqs-Ticket\": ticket,\n \"Vqs-Visibility-Timeout\": visibilityTimeoutSeconds.toString(),\n }),\n },\n );\n\n if (!response.ok) {\n if (response.status === 400) {\n throw new BadRequestError(\n \"Missing ticket or invalid visibility timeout\",\n );\n }\n if (response.status === 401) {\n throw new UnauthorizedError();\n }\n if (response.status === 403) {\n throw new ForbiddenError();\n }\n if (response.status === 404) {\n throw new MessageNotFoundError(messageId);\n }\n if (response.status === 409) {\n throw new MessageNotAvailableError(\n messageId,\n \"Invalid ticket, message not in correct state, or already processed\",\n );\n }\n if (response.status >= 500) {\n throw new InternalServerError(\n `Server error: ${response.status} ${response.statusText}`,\n );\n }\n throw new Error(\n `Failed to change visibility: ${response.status} ${response.statusText}`,\n );\n }\n\n return { updated: true };\n }\n}\n","import { spawn } from \"node:child_process\";\nimport type { CallbackConfig, SendMessageResponse } from \"./types\";\n\n/**\n * Helper function to check if a URL is localhost with a non-zero port\n * for development callback handling\n */\nfunction isLocalhostWithPort(url: string): {\n isLocalhost: boolean;\n port?: number;\n} {\n try {\n const parsedUrl = new URL(url);\n const isLocalhost = parsedUrl.hostname === \"localhost\";\n const port = parsedUrl.port ? parseInt(parsedUrl.port, 10) : 0;\n return { isLocalhost, port };\n } catch {\n return { isLocalhost: false };\n }\n}\n\n/**\n * Check if the current platform supports localhost callback handling\n * @returns true if platform supports bash/nc/curl (macOS, Linux), false otherwise\n */\nfunction isSupportedPlatform(): boolean {\n const platform = process.platform;\n return platform === \"darwin\" || platform === \"linux\";\n}\n\n/**\n * Process callbacks for development mode - separates localhost callbacks from others\n * @param callbacks - The callback configurations\n * @returns Array of localhost callbacks to process after server response\n */\nexport function processDevelopmentCallbacks(\n callbacks: Record<string, CallbackConfig>,\n): Array<{\n group: string;\n config: CallbackConfig;\n port: number;\n}> {\n const isDevelopment = process.env.NODE_ENV === \"development\";\n\n if (!isDevelopment) {\n return [];\n }\n\n // Check if platform supports localhost callback handling\n if (!isSupportedPlatform()) {\n const hasLocalhostCallbacks = Object.values(callbacks).some((config) => {\n const { isLocalhost } = isLocalhostWithPort(config.url);\n return isLocalhost;\n });\n\n if (hasLocalhostCallbacks) {\n console.warn(\n `Queue Development Mode: Localhost callbacks are not supported on ${process.platform}. ` +\n `Localhost callback handling requires bash, nc, and curl which are available on macOS and Linux only. ` +\n `Consider using a production callback URL or developing on a supported platform.`,\n );\n }\n return [];\n }\n\n // Development mode - separate localhost callbacks and warn about others\n const localhostCallbacks: Array<{\n group: string;\n config: CallbackConfig;\n port: number;\n }> = [];\n\n Object.entries(callbacks).forEach(([group, config]) => {\n const { isLocalhost, port } = isLocalhostWithPort(config.url);\n if (isLocalhost && port && port > 0) {\n // Store localhost callback for processing after server response\n localhostCallbacks.push({ group, config, port });\n } else {\n // Log warning for non-localhost callbacks in development\n console.warn(\n `Queue Development Mode: Skipping non-localhost callback for group \"${group}\": ${config.url}. Only localhost callbacks with explicit ports are supported in development.`,\n );\n }\n });\n\n return localhostCallbacks;\n}\n\n/**\n * Fire localhost callbacks after successful message send in development mode\n * @param localhostCallbacks - Array of localhost callbacks to process\n * @param queueName - The queue name the message was sent to\n * @param responseData - The response from the server containing the message ID\n */\nexport function fireLocalhostCallbacks(\n localhostCallbacks: Array<{\n group: string;\n config: CallbackConfig;\n port: number;\n }>,\n queueName: string,\n responseData: SendMessageResponse,\n): void {\n localhostCallbacks.forEach(({ group, config, port }) => {\n // Create queue callback headers with real message ID from server response\n const callbackHeaders = new Headers();\n callbackHeaders.set(\"Vqs-Message-Id\", responseData.messageId);\n callbackHeaders.set(\"Vqs-Queue-Name\", queueName);\n callbackHeaders.set(\"Vqs-Consumer-Group\", group);\n\n // Fire-and-forget wait for localhost endpoints\n fireAndForgetWaitForHttpReady(\n config.url,\n port,\n config.delay || 0,\n 3, // Default retry frequency\n callbackHeaders,\n );\n });\n}\n\n/**\n * Fire-and-forget: check if `port` is listening, then that `url` returns 2xx.\n * If the port is closed twice in a row, the subprocess exits nonzero.\n * Otherwise it loops until both conditions succeed, with no further Node logic.\n *\n * Note: Only works on macOS and Linux (requires bash, nc, curl)\n *\n * @param {string} url – Full URL to check (e.g. \"http://localhost:3000/health\")\n * @param {number} port – TCP port to probe (e.g. 3000)\n * @param {number} initialDelaySeconds – How many seconds to sleep before first check\n * @param {number} retryFrequencySeconds – Seconds to wait between each check\n * @param {Headers} headers – Optional headers to include in the HTTP request\n */\nexport function fireAndForgetWaitForHttpReady(\n url: string,\n port: number,\n initialDelaySeconds: number = 0,\n retryFrequencySeconds: number = 3,\n headers?: Headers,\n) {\n // Early return if platform doesn't support bash/nc/curl\n if (!isSupportedPlatform()) {\n console.warn(\n `Queue: fireAndForgetWaitForHttpReady is not supported on ${process.platform}. ` +\n `This function requires bash, nc, and curl which are available on macOS and Linux only.`,\n );\n return;\n }\n // Convert headers to curl header arguments\n let headerArgs = \"\";\n if (headers) {\n const headerArray: string[] = [];\n headers.forEach((value, key) => {\n headerArray.push(`-H '${key}: ${value}'`);\n });\n headerArgs = headerArray.join(\" \");\n }\n\n // This entire loop lives inside a single Bash subprocess:\n const bashScript = `\n # Wait for any initial boot time\n sleep ${initialDelaySeconds}\n\n missed=0\n while true; do\n # 1) Check if TCP port is listening\n if nc -z localhost ${port} 2>/dev/null; then\n missed=0\n # 2) If port is open, try HTTP POST check\n if curl -sSL --fail -o /dev/null -X POST ${headerArgs} \"${url}\"; then\n # Success: port is up AND HTTP returned 2xx (following redirects)\n exit 0\n fi\n else\n # Port was closed—increment miss counter\n ((missed+=1))\n # If closed twice in a row, give up immediately\n if [ \"$missed\" -ge 2 ]; then\n exit 1\n fi\n fi\n # Wait before next cycle\n sleep ${retryFrequencySeconds}\n done\n `;\n\n // Spawn bash; stdio→ignore sends stdout/stderr to /dev/null\n const childProcess = spawn(\"bash\", [\"-c\", bashScript], {\n stdio: \"ignore\",\n detached: true,\n });\n\n // Unref the process so it doesn't keep the parent alive and can survive parent death\n childProcess.unref();\n\n // We do NOT attach any Node-side cleanup. Once spawned, this subprocess\n // lives on its own until it either exits 0 (success) or 1 (port missed twice).\n}\n","/**\n * Vercel Queue Service client types\n */\nimport type { Transport } from \"./transports\";\n\n// Re-export transport interface for convenience\nexport type { Transport };\n\nexport interface QueueClientOptions {\n /**\n * Base URL for the Vercel Queue Service API\n * @default \"https://vqs.vercel.sh\"\n */\n baseUrl?: string;\n /**\n * Vercel function OIDC token\n * Can be obtained from x-vercel-oidc-token header in Vercel Serverless Functions\n * If not provided, will automatically attempt to retrieve from Vercel Function environment\n */\n token?: string;\n}\n\n/**\n * Callback configuration for a consumer group\n */\nexport interface CallbackConfig {\n /**\n * Webhook URL to notify when messages are available\n */\n url: string;\n /**\n * Delay in seconds before sending the first callback\n */\n delay?: number;\n /**\n * Delay in seconds between retry attempts when the callback fails\n */\n frequency?: number;\n}\n\n/**\n * Shared options for publishing messages\n */\nexport interface PublishOptions {\n /**\n * Unique key to prevent duplicate message submissions\n * @default random UUID\n */\n idempotencyKey?: string;\n /**\n * Message retention time in seconds\n * @default 86400 (24 hours)\n * @min 60\n * @max 86400\n */\n retentionSeconds?: number;\n /**\n * Callback configuration\n * - If a single CallbackConfig is provided, it will use the \"default\" consumer group\n * - If an object is provided, keys are consumer group names with their respective callback configs\n */\n callback?: Record<string, CallbackConfig> | CallbackConfig;\n}\n\nexport interface SendMessageOptions<T = unknown> extends PublishOptions {\n /**\n * The queue name to send the message to\n */\n queueName: string;\n /**\n * The message payload\n */\n payload: T;\n}\n\nexport interface SendMessageResponse {\n /**\n * The generated message ID\n */\n messageId: string;\n}\n\nexport interface Message<T = unknown> {\n /**\n * The message ID\n */\n messageId: string;\n /**\n * The deserialized message payload\n * Note: If using streaming transports, ensure proper cleanup by calling transport.finalize(payload)\n * when done processing, especially in error cases\n */\n payload: T;\n /**\n * Number of times this message has been delivered\n */\n deliveryCount: number;\n /**\n * Timestamp when the message was created\n */\n timestamp: string;\n /**\n * MIME type of the message content\n */\n contentType: string;\n /**\n * Unique ticket for this message delivery (required for delete/patch operations)\n */\n ticket: string;\n}\n\nexport interface ReceiveMessagesOptions<T = unknown> {\n /**\n * The queue name to receive messages from\n */\n queueName: string;\n /**\n * Consumer group name\n */\n consumerGroup: string;\n /**\n * Time in seconds that messages will be invisible to other consumers\n * @default 900 (15 minutes)\n */\n visibilityTimeoutSeconds?: number;\n /**\n * Maximum number of messages to retrieve\n * @default 10\n * @max 10\n * @note FIFO queues must use limit=1\n */\n limit?: number;\n}\n\nexport interface DeleteMessageOptions {\n /**\n * The queue name the message belongs to\n */\n queueName: string;\n /**\n * Consumer group name\n */\n consumerGroup: string;\n /**\n * The message ID to delete\n */\n messageId: string;\n /**\n * Ticket received from the message\n */\n ticket: string;\n}\n\nexport interface DeleteMessageResponse {\n /**\n * Whether the message was successfully deleted\n */\n deleted: boolean;\n}\n\nexport interface ChangeVisibilityOptions {\n /**\n * The queue name the message belongs to\n */\n queueName: string;\n /**\n * Consumer group name\n */\n consumerGroup: string;\n /**\n * The message ID to update\n */\n messageId: string;\n /**\n * Ticket received from the message\n */\n ticket: string;\n /**\n * New visibility timeout in seconds\n */\n visibilityTimeoutSeconds: number;\n}\n\nexport interface ChangeVisibilityResponse {\n /**\n * Whether the visibility was successfully updated\n */\n updated: boolean;\n}\n\n/**\n * Result indicating the message should be timed out for retry later\n */\nexport interface MessageTimeoutResult {\n /**\n * Time in seconds before the message becomes visible again\n */\n timeoutSeconds: number;\n}\n\n/**\n * Result returned by message handlers\n */\nexport type MessageHandlerResult = void | MessageTimeoutResult;\n\n/**\n * Message metadata provided to handlers\n */\nexport interface MessageMetadata {\n messageId: string;\n deliveryCount: number;\n timestamp: string;\n}\n\n/**\n * Message handler function type\n */\nexport type MessageHandler<T = unknown> = (\n message: T,\n metadata: MessageMetadata,\n) => Promise<MessageHandlerResult> | MessageHandlerResult;\n\n/**\n * Options for creating a ConsumerGroup instance\n */\nexport interface ConsumerGroupOptions<T = unknown> {\n /**\n * Serializer/deserializer for the payload\n * @default JsonTransport instance\n */\n transport?: Transport<T>;\n /**\n * Time in seconds that messages will be invisible to other consumers\n * @default 30\n */\n visibilityTimeoutSeconds?: number;\n /**\n * How often to refresh the visibility timeout during processing (in seconds)\n * @default 10\n */\n refreshInterval?: number;\n}\n\nexport interface ReceiveMessageByIdOptions<T = unknown> {\n /**\n * The queue name to receive the message from\n */\n queueName: string;\n /**\n * Consumer group name\n */\n consumerGroup: string;\n /**\n * The message ID to retrieve\n */\n messageId: string;\n /**\n * Time in seconds that the message will be invisible to other consumers\n * @default 900 (15 minutes)\n */\n visibilityTimeoutSeconds?: number;\n /**\n * Skip payload content and only return message metadata\n * When true, the server returns a 204 status with headers containing message metadata\n * @default false\n */\n skipPayload?: boolean;\n}\n\n// Response type that always contains a message (errors are thrown for failures)\nexport interface ReceiveMessageByIdResponse<\n T = unknown,\n TSkipPayload extends boolean = false,\n> {\n message: TSkipPayload extends true ? Message<void> : Message<T>;\n}\n\n/**\n * Error thrown when a message is not found (404)\n */\nexport class MessageNotFoundError extends Error {\n constructor(messageId: string) {\n super(`Message ${messageId} not found`);\n this.name = \"MessageNotFoundError\";\n }\n}\n\n/**\n * Error thrown when a message is not available for processing (409)\n * This can happen when the message is in the wrong state, already claimed, etc.\n */\nexport class MessageNotAvailableError extends Error {\n constructor(messageId: string, reason?: string) {\n super(\n `Message ${messageId} not available for processing${reason ? `: ${reason}` : \"\"}`,\n );\n this.name = \"MessageNotAvailableError\";\n }\n}\n\n/**\n * Error thrown when there's a FIFO ordering violation (409)\n */\nexport class FifoOrderingViolationError extends Error {\n constructor(messageId: string, reason: string) {\n super(`FIFO ordering violation for message ${messageId}: ${reason}`);\n this.name = \"FifoOrderingViolationError\";\n }\n}\n\n/**\n * Error thrown when message data is corrupted or can't be parsed\n */\nexport class MessageCorruptedError extends Error {\n constructor(messageId: string, reason: string) {\n super(`Message ${messageId} is corrupted: ${reason}`);\n this.name = \"MessageCorruptedError\";\n }\n}\n\n/**\n * Error thrown when there are no messages available in the queue (204)\n */\nexport class QueueEmptyError extends Error {\n constructor(queueName: string, consumerGroup: string) {\n super(\n `No messages available in queue \"${queueName}\" for consumer group \"${consumerGroup}\"`,\n );\n this.name = \"QueueEmptyError\";\n }\n}\n\n/**\n * Error thrown when a message is temporarily locked in a FIFO queue (423)\n */\nexport class MessageLockedError extends Error {\n public readonly retryAfter?: number;\n\n constructor(messageId: string, retryAfter?: number) {\n const retryMessage = retryAfter\n ? ` Retry after ${retryAfter} seconds.`\n : \" Try again later.\";\n super(`Message ${messageId} is temporarily locked.${retryMessage}`);\n this.name = \"MessageLockedError\";\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Error thrown when authentication fails (401)\n */\nexport class UnauthorizedError extends Error {\n constructor(message: string = \"Missing or invalid authentication token\") {\n super(message);\n this.name = \"UnauthorizedError\";\n }\n}\n\n/**\n * Error thrown when access is forbidden (403)\n */\nexport class ForbiddenError extends Error {\n constructor(\n message: string = \"Queue environment doesn't match token environment\",\n ) {\n super(message);\n this.name = \"ForbiddenError\";\n }\n}\n\n/**\n * Error thrown for bad requests (400)\n */\nexport class BadRequestError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BadRequestError\";\n }\n}\n\n/**\n * Error thrown when there's a failed dependency (424) - FIFO ordering violation in receive by ID\n */\nexport class FailedDependencyError extends Error {\n constructor(messageId: string) {\n super(\n `Failed dependency: FIFO ordering violation for message ${messageId}`,\n );\n this.name = \"FailedDependencyError\";\n }\n}\n\n/**\n * Error thrown for internal server errors (500)\n */\nexport class InternalServerError extends Error {\n constructor(message: string = \"Unexpected server error\") {\n super(message);\n this.name = \"InternalServerError\";\n }\n}\n\n/**\n * Error thrown when batch limit parameter is invalid\n */\nexport class InvalidLimitError extends Error {\n constructor(limit: number, min: number = 1, max: number = 10) {\n super(`Invalid limit: ${limit}. Limit must be between ${min} and ${max}.`);\n this.name = \"InvalidLimitError\";\n }\n}\n\n/**\n * Options extracted from a queue callback request\n */\nexport interface CallbackMessageOptions {\n /**\n * The queue name extracted from Vqs-Queue-Name header\n */\n queueName: string;\n /**\n * The consumer group extracted from Vqs-Consumer-Group header\n */\n consumerGroup: string;\n /**\n * The message ID extracted from Vqs-Message-Id header\n */\n messageId: string;\n}\n\n/**\n * Error thrown when queue callback headers are missing or invalid\n */\nexport class InvalidCallbackError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidCallbackError\";\n }\n}\n","/**\n * Serializer/Deserializer interface for message payloads\n */\nexport interface Transport<T = unknown> {\n /**\n * Serialize a value to a buffer or stream for transmission\n */\n serialize(value: T): Buffer | ReadableStream<Uint8Array>;\n\n /**\n * Deserialize a readable stream back to the original value\n */\n deserialize(stream: ReadableStream<Uint8Array>): Promise<T>;\n\n /**\n * Optional cleanup method for deserialized payloads that may contain resources\n * Should be called when the payload is no longer needed, especially in error cases\n * @param payload The deserialized payload to clean up\n */\n finalize?(payload: T): Promise<void>;\n\n /**\n * MIME type for this serialization format\n */\n contentType: string;\n}\n\n/**\n * Built-in JSON serializer/deserializer\n * This implementation reads the entire stream into memory for JSON parsing\n */\nexport class JsonTransport<T = unknown> implements Transport<T> {\n readonly contentType = \"application/json\";\n\n serialize(value: T): Buffer {\n return Buffer.from(JSON.stringify(value), \"utf8\");\n }\n\n async deserialize(stream: ReadableStream<Uint8Array>): Promise<T> {\n // JSON requires reading the entire payload to parse\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n // Combine chunks into a single buffer\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const buffer = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.length;\n }\n\n return JSON.parse(Buffer.from(buffer).toString(\"utf8\"));\n }\n}\n\n/**\n * Built-in Buffer serializer/deserializer (reads entire stream into a Buffer)\n */\nexport class BufferTransport implements Transport<Buffer> {\n readonly contentType = \"application/octet-stream\";\n\n serialize(value: Buffer): Buffer {\n return value;\n }\n\n async deserialize(stream: ReadableStream<Uint8Array>): Promise<Buffer> {\n // Buffer transport reads the entire stream into memory\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n // Combine chunks into a single buffer\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const buffer = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n buffer.set(chunk, offset);\n offset += chunk.length;\n }\n\n return Buffer.from(buffer);\n }\n}\n\n/**\n * Stream serializer/deserializer (pass-through for streaming binary data)\n * This is ideal for large payloads that don't need to be buffered in memory\n *\n * IMPORTANT: When using StreamTransport, you must call finalize(payload) when done\n * processing the message to prevent resource leaks, especially in error cases.\n * ConsumerGroup handles this automatically, but direct QueueClient usage requires manual cleanup.\n *\n * Example usage:\n * ```typescript\n * const transport = new StreamTransport();\n * try {\n * for await (const message of client.receiveMessages(options, transport)) {\n * // Process the stream...\n * const reader = message.payload.getReader();\n * // ... handle stream data\n * }\n * } catch (error) {\n * // Cleanup is handled automatically by ConsumerGroup\n * // or manually: await transport.finalize(message.payload);\n * }\n */\nexport class StreamTransport implements Transport<ReadableStream<Uint8Array>> {\n readonly contentType = \"application/octet-stream\";\n\n serialize(value: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {\n // Pass through the stream directly without buffering\n return value;\n }\n\n async deserialize(\n stream: ReadableStream<Uint8Array>,\n ): Promise<ReadableStream<Uint8Array>> {\n // Pass through the stream directly without buffering\n return stream;\n }\n\n async finalize(payload: ReadableStream<Uint8Array>): Promise<void> {\n // Consume any remaining stream data to prevent resource leaks\n const reader = payload.getReader();\n try {\n while (true) {\n const { done } = await reader.read();\n if (done) break;\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n","import { QueueClient } from \"./client\";\nimport type {\n ConsumerGroupOptions,\n MessageHandler,\n Transport,\n Message,\n} from \"./types\";\nimport { QueueEmptyError, MessageLockedError } from \"./types\";\nimport { JsonTransport } from \"./transports\";\n\n/**\n * Options for the consume method\n */\nexport interface ConsumeOptions {\n /** The specific message ID to consume (if not provided, consumes next available message) */\n messageId?: string;\n /** Whether to skip downloading the payload (only allowed when messageId is provided) */\n skipPayload?: boolean;\n}\n\n/**\n * A ConsumerGroup represents a named group of consumers that process messages from a topic\n */\nexport class ConsumerGroup<T = unknown> {\n private client: QueueClient;\n private topicName: string;\n private consumerGroupName: string;\n private visibilityTimeout: number;\n private refreshInterval: number;\n private transport: Transport<T>;\n\n /**\n * Create a new ConsumerGroup instance\n * @param client QueueClient instance to use for API calls\n * @param topicName Name of the topic to consume from\n * @param consumerGroupName Name of the consumer group\n * @param options Optional configuration\n */\n constructor(\n client: QueueClient,\n topicName: string,\n consumerGroupName: string,\n options: ConsumerGroupOptions<T> = {},\n ) {\n this.client = client;\n this.topicName = topicName;\n this.consumerGroupName = consumerGroupName;\n this.visibilityTimeout = options.visibilityTimeoutSeconds || 30; // 30 seconds default\n this.refreshInterval = options.refreshInterval || 10; // 10 seconds default\n this.transport = options.transport || new JsonTransport<T>();\n }\n\n /**\n * Starts a background loop that periodically extends the visibility timeout for a message.\n * This prevents the message from becoming visible to other consumers while it's being processed.\n *\n * The extension loop runs every `refreshInterval` seconds and updates the message's\n * visibility timeout to `visibilityTimeout` seconds from the current time.\n *\n * @param messageId - The unique identifier of the message to extend visibility for\n * @param ticket - The receipt ticket that proves ownership of the message\n * @returns A function that when called will stop the extension loop\n *\n * @remarks\n * - The first extension attempt occurs after `refreshInterval` seconds, not immediately\n * - If an extension fails, the loop terminates with an error logged to console\n * - The returned stop function is idempotent - calling it multiple times is safe\n * - By default, the stop function returns immediately without waiting for in-flight\n * - Pass `true` to the stop function to wait for any in-flight extension to complete\n */\n private startVisibilityExtension(\n messageId: string,\n ticket: string,\n ): (waitForCompletion?: boolean) => Promise<void> {\n let isRunning = true;\n let resolveLifecycle: () => void;\n let timeoutId: NodeJS.Timeout | null = null;\n\n // Promise that tracks the actual termination of the extension loop\n const lifecyclePromise = new Promise<void>((resolve) => {\n resolveLifecycle = resolve;\n });\n\n const extend = async (): Promise<void> => {\n // Check if we should stop before attempting extension\n if (!isRunning) {\n resolveLifecycle();\n return;\n }\n\n try {\n // Extend the visibility timeout for another period\n await this.client.changeVisibility({\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n messageId,\n ticket,\n visibilityTimeoutSeconds: this.visibilityTimeout,\n });\n\n // Schedule next extension if still running\n if (isRunning) {\n timeoutId = setTimeout(() => extend(), this.refreshInterval * 1000);\n } else {\n // Signal that the loop has terminated after successful extension\n resolveLifecycle();\n }\n } catch (error) {\n // Log error and terminate the loop on failure\n console.error(\n `Failed to extend visibility for message ${messageId}:`,\n error,\n );\n resolveLifecycle();\n }\n };\n\n // Schedule the first extension attempt\n timeoutId = setTimeout(() => extend(), this.refreshInterval * 1000);\n\n // Return a function to stop the extension loop\n return async (waitForCompletion: boolean = false) => {\n // Signal the loop to stop\n isRunning = false;\n\n // Cancel any pending timeout to avoid unnecessary waiting\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n // Only wait for in-flight operations if explicitly requested\n if (waitForCompletion) {\n // Wait for the loop to actually terminate\n // This ensures any in-progress extension completes or fails\n await lifecyclePromise;\n } else {\n // Resolve the lifecycle immediately for any waiting operations\n // This allows immediate return without waiting for in-flight extensions\n resolveLifecycle();\n }\n };\n }\n\n /**\n * Process a single message with the given handler\n * @param message The message to process\n * @param handler Function to process the message\n */\n private async processMessage<TPayload>(\n message: Message<TPayload>,\n handler: MessageHandler<TPayload>,\n ): Promise<void> {\n const stopExtension = this.startVisibilityExtension(\n message.messageId,\n message.ticket,\n );\n\n try {\n const result = await handler(message.payload, {\n messageId: message.messageId,\n deliveryCount: message.deliveryCount,\n timestamp: message.timestamp,\n });\n // Stop extensions immediately - we don't need to wait for in-flight extensions\n // since we're about to delete or update the message visibility anyway\n await stopExtension();\n\n if (result && \"timeoutSeconds\" in result) {\n // Handle timeout request - set new visibility timeout instead of deleting\n await this.client.changeVisibility({\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n messageId: message.messageId,\n ticket: message.ticket,\n visibilityTimeoutSeconds: result.timeoutSeconds,\n });\n } else {\n // Normal completion - delete the message\n await this.client.deleteMessage({\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n messageId: message.messageId,\n ticket: message.ticket,\n });\n }\n } catch (error) {\n // Stop extensions immediately on error - fail fast without waiting\n // for any in-flight extension attempts\n await stopExtension();\n\n // Clean up the message payload if the transport supports it and payload exists\n // Only call finalize for non-void payloads since transport is typed for T, not void\n if (\n this.transport.finalize &&\n message.payload !== undefined &&\n message.payload !== null\n ) {\n try {\n // Safe cast: when processMessage<T> is called, TPayload is T\n // when processMessage<void> is called, payload is undefined so this won't execute\n await this.transport.finalize(message.payload as T);\n } catch (finalizeError) {\n console.warn(\"Failed to finalize message payload:\", finalizeError);\n }\n }\n\n throw error;\n }\n }\n\n /**\n * Consume the next available message from the queue\n * @param handler Function to process the message\n * @returns Promise that resolves when the message is processed\n * @throws All the same errors as the underlying client methods\n */\n async consume(handler: MessageHandler<T>): Promise<void>;\n\n /**\n * Consume a specific message by its ID with full payload\n * @param handler Function to process the message\n * @param options Consume options with messageId specified\n * @returns Promise that resolves when the message is processed\n * @throws All the same errors as the underlying client methods\n */\n async consume(\n handler: MessageHandler<T>,\n options: { messageId: string; skipPayload?: false | undefined },\n ): Promise<void>;\n\n /**\n * Consume a specific message by its ID without downloading the payload (metadata only)\n * @param handler Function to process the message metadata (payload will be void)\n * @param options Consume options with messageId and skipPayload specified\n * @returns Promise that resolves when the message is processed\n * @throws All the same errors as the underlying client methods\n */\n async consume(\n handler: MessageHandler<void>,\n options: { messageId: string; skipPayload: true },\n ): Promise<void>;\n\n async consume(\n handler: MessageHandler<T> | MessageHandler<void>,\n options?: ConsumeOptions,\n ): Promise<void> {\n if (options?.messageId) {\n // Specific message mode\n if (options.skipPayload) {\n // Skip payload - like old handleMessage\n const response = await this.client.receiveMessageById(\n {\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n messageId: options.messageId,\n visibilityTimeoutSeconds: this.visibilityTimeout,\n skipPayload: true,\n },\n this.transport,\n );\n await this.processMessage<void>(\n response.message,\n handler as MessageHandler<void>,\n );\n } else {\n // With payload - like old receiveMessage\n const response = await this.client.receiveMessageById(\n {\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n messageId: options.messageId,\n visibilityTimeoutSeconds: this.visibilityTimeout,\n },\n this.transport,\n );\n await this.processMessage<T>(\n response.message,\n handler as MessageHandler<T>,\n );\n }\n } else {\n // Next message mode - like old receiveNextMessage\n let messageFound = false;\n\n for await (const message of this.client.receiveMessages<T>(\n {\n queueName: this.topicName,\n consumerGroup: this.consumerGroupName,\n visibilityTimeoutSeconds: this.visibilityTimeout,\n limit: 1,\n },\n this.transport,\n )) {\n messageFound = true;\n await this.processMessage<T>(message, handler as MessageHandler<T>);\n break; // Process only one message\n }\n\n // If we get here without finding a message, the async generator\n // should have already thrown QueueEmptyError, but just in case\n if (!messageFound) {\n throw new Error(\"No messages available\");\n }\n }\n }\n\n /**\n * Get the consumer group name\n */\n get name(): string {\n return this.consumerGroupName;\n }\n\n /**\n * Get the topic name this consumer group is subscribed to\n */\n get topic(): string {\n return this.topicName;\n }\n}\n","import { QueueClient } from \"./client\";\nimport { ConsumerGroup } from \"./consumer-group\";\nimport type {\n ConsumerGroupOptions,\n PublishOptions,\n Transport,\n CallbackConfig,\n} from \"./types\";\nimport { JsonTransport } from \"./transports\";\n\n/**\n * A Topic represents a named channel for publishing messages in a pub/sub pattern\n */\nexport class Topic<T = unknown> {\n private client: QueueClient;\n private topicName: string;\n private transport: Transport<T>;\n\n /**\n * Create a new Topic instance\n * @param client QueueClient instance to use for API calls\n * @param topicName Name of the topic to work with\n * @param transport Optional serializer/deserializer for the payload (defaults to JSON)\n */\n constructor(\n client: QueueClient,\n topicName: string,\n transport?: Transport<T>,\n ) {\n this.client = client;\n this.topicName = topicName;\n this.transport = transport || new JsonTransport<T>();\n }\n\n /**\n * Publish a message to the topic\n * @param payload The data to publish\n * @param options Optional publish options\n * @returns An object containing the message ID\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\n async publish(\n payload: T,\n options?: PublishOptions,\n ): Promise<{ messageId: string }> {\n const result = await this.client.sendMessage<T>(\n {\n queueName: this.topicName,\n payload,\n idempotencyKey: options?.idempotencyKey,\n retentionSeconds: options?.retentionSeconds,\n callback: options?.callback,\n },\n this.transport,\n );\n return { messageId: result.messageId };\n }\n\n /**\n * Create a consumer group for this topic\n * @param consumerGroupName Name of the consumer group\n * @param options Optional configuration for the consumer group\n * @returns A ConsumerGroup instance\n */\n consumerGroup<U = T>(\n consumerGroupName: string,\n options?: ConsumerGroupOptions<U>,\n ): ConsumerGroup<U> {\n // If no transport is provided in options, use the topic's transport if types match\n const consumerOptions: ConsumerGroupOptions<U> = {\n ...options,\n transport:\n options?.transport || (this.transport as unknown as Transport<U>),\n };\n\n return new ConsumerGroup<U>(\n this.client,\n this.topicName,\n consumerGroupName,\n consumerOptions,\n );\n }\n\n /**\n * Get the topic name\n */\n get name(): string {\n return this.topicName;\n }\n\n /**\n * Get the transport used by this topic\n */\n get serializer(): Transport<T> {\n return this.transport;\n }\n}\n","import { QueueClient } from \"./client\";\nimport { Topic } from \"./topic\";\nimport { JsonTransport } from \"./transports\";\nimport type {\n Transport,\n PublishOptions,\n MessageHandler,\n ConsumerGroupOptions,\n} from \"./types\";\nimport type { ConsumeOptions } from \"./consumer-group\";\n\n/**\n * Create a new Topic instance using the default QueueClient\n * For custom client configuration, use `new Topic(customClient, topicName, transport)` directly\n * @param topicName Name of the topic\n * @param transport Optional serializer/deserializer for the payload (defaults to JSON)\n * @returns A Topic instance\n */\nexport function createTopic<T = unknown>(\n topicName: string,\n transport?: Transport<T>,\n): Topic<T> {\n const client = QueueClient._getDefaultInstance();\n return new Topic<T>(client, topicName, transport);\n}\n\n/**\n * Options for the send function\n */\nexport interface SendOptions<T = unknown> extends PublishOptions {\n /**\n * Serializer/deserializer for the payload\n * @default JsonTransport instance\n */\n transport?: Transport<T>;\n}\n\n/**\n * Send a message to a topic (shorthand for topic creation and publishing)\n * Uses the default QueueClient with automatic OIDC token detection\n * @param topicName Name of the topic to send to\n * @param payload The data to send\n * @param options Optional send options including transport and publish settings\n * @returns Promise with the message ID\n * @throws {BadRequestError} When request parameters are invalid\n * @throws {UnauthorizedError} When authentication fails\n * @throws {ForbiddenError} When access is denied (environment mismatch)\n * @throws {InternalServerError} When server encounters an error\n */\nexport async function send<T = unknown>(\n topicName: string,\n payload: T,\n options?: SendOptions<T>,\n): Promise<{ messageId: string }> {\n const transport = options?.transport || new JsonTransport<T>();\n const client = QueueClient._getDefaultInstance();\n\n const result = await client.sendMessage<T>(\n {\n queueName: topicName,\n payload,\n idempotencyKey: options?.idempotencyKey,\n retentionSeconds: options?.retentionSeconds,\n callback: options?.callback,\n },\n transport,\n );\n\n return { messageId: result.messageId };\n}\n\n/**\n * Options for the receive function\n */\nexport interface ReceiveOptions<T = unknown>\n extends ConsumerGroupOptions<T>,\n ConsumeOptions {}\n\n/**\n * Receive a message from a topic (shorthand for topic and consumer group creation)\n * Uses the default QueueClient with automatic OIDC token detection\n * @param topicName Name of the topic to receive from\n * @param consumerGroup Name of the consumer group\n * @param handler Function to process the message\n * @returns Promise that resolves when the message is processed\n * @throws All the same errors as the underlying client methods\n */\nexport async function receive<T = unknown>(\n topicName: string,\n consumerGroup: string,\n handler: MessageHandler<T>,\n options?: ReceiveOptions<T>,\n): Promise<void>;\n\n/**\n * Receive a specific message by its ID with full payload\n * @param topicName Name of the topic to receive from\n * @param consumerGroup Name of the consumer group\n * @param handler Function to process the message\n * @param options Receive options with messageId specified\n * @returns Promise that resolves when the message is processed\n * @throws All the same errors as the underlying client methods\n */\nexport async function receive<T = unknown>(\n topicName: string,\n consumerGroup: string,\n handler: MessageHandler<T>,\n options: ReceiveOptions<T> & {\n messageId: string;\n skipPayload?: false | undefined;\n },\n): Promise<void>;\n\n/**\n * Receive a specific message by its ID without downloading the payload (metadata only)\n * @param topicName Name of the topic to receive from\n * @param consumerGroup Name of the consumer group\n * @param handler Function to process the message metadata (payload will be void)\n * @param options Receive options with messageId and skipPayload specified\n * @returns Promise that resolves when the message is processed\n * @throws All the same errors as the underlying client methods\n */\nexport async function receive<T = unknown>(\n topicName: string,\n consumerGroup: string,\n handler: MessageHandler<void>,\n options: ReceiveOptions<T> & { messageId: string; skipPayload: true },\n): Promise<void>;\n\nexport async function receive<T = unknown>(\n topicName: string,\n consumerGroup: string,\n handler: MessageHandler<T> | MessageHandler<void>,\n options?: ReceiveOptions<T>,\n): Promise<void> {\n const transport = options?.transport || new JsonTransport<T>();\n\n // Create topic with transport\n const topic = createTopic<T>(topicName, transport);\n\n // Create consumer group with options (excluding consume-specific options)\n const { messageId, skipPayload, ...consumerGroupOptions } = options || {};\n const consumer = topic.consumerGroup(consumerGroup, consumerGroupOptions);\n\n // Call consume with the appropriate overload based on options\n if (messageId) {\n if (skipPayload) {\n // skipPayload: true case\n return consumer.consume(handler as MessageHandler<void>, {\n messageId,\n skipPayload: true,\n });\n } else {\n // messageId with payload case\n return consumer.consume(handler as MessageHandler<T>, { messageId });\n }\n } else {\n // No options case - next available message\n return consumer.consume(handler as MessageHandler<T>);\n }\n}\n","/**\n * Queue Callback utilities for handling incoming webhook payloads\n */\nimport type { CallbackMessageOptions, MessageHandler } from \"./types\";\nimport { InvalidCallbackError } from \"./types\";\nimport { QueueClient } from \"./client\";\nimport { Topic } from \"./topic\";\n\n/**\n * Parse a queue callback request and extract the required information for receiveMessageById\n *\n * @param request The incoming Request object from the queue callback\n * @returns CallbackMessageOptions that can be used with receiveMessageById\n * @throws {InvalidCallbackError} When required queue headers are missing or invalid\n *\n * @example\n * ```typescript\n * import { parseCallbackRequest } from '@vercel/queue';\n *\n * // In your webhook handler\n * export async function POST(request: Request) {\n * try {\n * const callbackOptions = parseCallbackRequest(request);\n *\n * // Use with receiveMessageById\n * const message = await client.receiveMessageById({\n * ...callbackOptions,\n * visibilityTimeoutSeconds: 30\n * }, transport);\n *\n * // Process the message...\n * } catch (error) {\n * if (error instanceof InvalidCallbackError) {\n * return new Response('Invalid callback', { status: 400 });\n * }\n * throw error;\n * }\n * }\n * ```\n */\nexport function parseCallbackRequest(request: Request): CallbackMessageOptions {\n const headers = request.headers;\n\n // Extract required queue headers\n const messageId = headers.get(\"Vqs-Message-Id\");\n const queueName = headers.get(\"Vqs-Queue-Name\");\n const consumerGroup = headers.get(\"Vqs-Consumer-Group\");\n\n // Validate all required headers are present\n const missingHeaders: string[] = [];\n if (!messageId) missingHeaders.push(\"Vqs-Message-Id\");\n if (!queueName) missingHeaders.push(\"Vqs-Queue-Name\");\n if (!consumerGroup) missingHeaders.push(\"Vqs-Consumer-Group\");\n\n if (missingHeaders.length > 0) {\n throw new InvalidCallbackError(\n `Missing required queue callback headers: ${missingHeaders.join(\", \")}`,\n );\n }\n\n return {\n messageId: messageId!,\n queueName: queueName!,\n consumerGroup: consumerGroup!,\n };\n}\n\n/**\n * Configuration object with handlers for different topics\n * Each topic can have either:\n * - A single handler function (uses 'default' consumer group)\n * - An object with handlers for specific consumer groups\n */\ntype CallbackHandlers = {\n [topicName: string]:\n | MessageHandler\n | {\n [consumerGroup: string]: MessageHandler;\n };\n};\n\n/**\n * Simplified queue callback handler for NextJS route handlers\n *\n * @param handlers Object with topic-specific handlers\n * @returns A NextJS route handler function\n *\n * @example\n * ```typescript\n * // Topic handler (uses 'default' consumer group)\n * export const POST = handleCallback({\n * \"new-users\": (message, metadata) => {\n * console.log(`New user event:`, message, metadata);\n * }\n * });\n *\n * // Consumer group specific handlers\n * export const POST = handleCallback({\n * \"image-processing\": {\n * \"compress\": (message, metadata) => console.log(\"Compressing image\", message),\n * \"resize\": (message, metadata) => console.log(\"Resizing image\", message),\n * }\n * });\n * ```\n */\nexport function handleCallback(\n handlers: CallbackHandlers,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n try {\n // Parse the queue callback information\n const { queueName, consumerGroup, messageId } =\n parseCallbackRequest(request);\n\n // Find the topic handler\n const topicHandler = handlers[queueName];\n\n if (!topicHandler) {\n throw new Error(`No handler found for topic: ${queueName}`);\n }\n\n let actualHandler: MessageHandler;\n\n if (typeof topicHandler === \"function\") {\n // Single handler function - only works with 'default' consumer group\n if (consumerGroup !== \"default\") {\n throw new Error(\n `Topic \"${queueName}\" has a single handler but received consumer group \"${consumerGroup}\". Expected \"default\".`,\n );\n }\n actualHandler = topicHandler;\n } else {\n // Object with consumer group handlers\n const consumerGroupHandler = topicHandler[consumerGroup];\n\n if (!consumerGroupHandler) {\n const availableGroups = Object.keys(topicHandler).join(\", \");\n throw new Error(\n `No handler found for consumer group \"${consumerGroup}\" in topic \"${queueName}\". Available groups: ${availableGroups}`,\n );\n }\n actualHandler = consumerGroupHandler;\n }\n\n // Create client and process the message\n const client = new QueueClient();\n const topic = new Topic(client, queueName);\n const cg = topic.consumerGroup(consumerGroup);\n\n await cg.consume(actualHandler, { messageId });\n\n return Response.json({ status: \"success\" });\n } catch (error) {\n console.error(\"Callback error:\", error);\n\n if (error instanceof InvalidCallbackError) {\n return Response.json(\n { error: \"Invalid callback request\" },\n { status: 400 },\n );\n }\n\n return Response.json(\n { error: \"Failed to process callback\" },\n { status: 500 },\n );\n }\n };\n}\n"],"mappings":";AACA,SAAS,4BAA4B;;;ACDrC,SAAS,aAAa;AAOtB,SAAS,oBAAoB,KAG3B;AACA,MAAI;AACF,UAAM,YAAY,IAAI,IAAI,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AC5C,SAAS,OAAO;AACd,cAAQ,MAAM,mBAAmB,KAAK;AAEtC,UAAI,iBAAiB,sBAAsB;AACzC,eAAO,SAAS;AAAA,UACd,EAAE,OAAO,2BAA2B;AAAA,UACpC,EAAE,QAAQ,IAAI;AAAA,QAChB;AAAA,MACF;AAEA,aAAO,SAAS;AAAA,QACd,EAAE,OAAO,6BAA6B;AAAA,QACtC,EAAE,QAAQ,IAAI;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vercel/queue",
3
- "version": "0.0.0-alpha.2",
3
+ "version": "0.0.0-alpha.4",
4
4
  "access": "restricted",
5
5
  "description": "A Node.js library for interacting with the Vercel Queue Service API",
6
6
  "main": "dist/index.js",