@vercel/queue 0.0.0-alpha.39 → 0.0.0-alpha.40

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,1401 +0,0 @@
1
- // src/client.ts
2
- import { parseMultipartStream } from "mixpart";
3
-
4
- // src/dev.ts
5
- import * as fs from "fs";
6
- import * as path from "path";
7
-
8
- // src/types.ts
9
- var MessageNotFoundError = class extends Error {
10
- constructor(messageId) {
11
- super(`Message ${messageId} not found`);
12
- this.name = "MessageNotFoundError";
13
- }
14
- };
15
- var MessageNotAvailableError = class extends Error {
16
- constructor(messageId, reason) {
17
- super(
18
- `Message ${messageId} not available for processing${reason ? `: ${reason}` : ""}`
19
- );
20
- this.name = "MessageNotAvailableError";
21
- }
22
- };
23
- var MessageCorruptedError = class extends Error {
24
- constructor(messageId, reason) {
25
- super(`Message ${messageId} is corrupted: ${reason}`);
26
- this.name = "MessageCorruptedError";
27
- }
28
- };
29
- var UnauthorizedError = class extends Error {
30
- constructor(message = "Missing or invalid authentication token") {
31
- super(message);
32
- this.name = "UnauthorizedError";
33
- }
34
- };
35
- var ForbiddenError = class extends Error {
36
- constructor(message = "Queue environment doesn't match token environment") {
37
- super(message);
38
- this.name = "ForbiddenError";
39
- }
40
- };
41
- var BadRequestError = class extends Error {
42
- constructor(message) {
43
- super(message);
44
- this.name = "BadRequestError";
45
- }
46
- };
47
- var InternalServerError = class extends Error {
48
- constructor(message = "Unexpected server error") {
49
- super(message);
50
- this.name = "InternalServerError";
51
- }
52
- };
53
- var InvalidLimitError = class extends Error {
54
- constructor(limit, min = 1, max = 10) {
55
- super(`Invalid limit: ${limit}. Limit must be between ${min} and ${max}.`);
56
- this.name = "InvalidLimitError";
57
- }
58
- };
59
- var MessageAlreadyProcessedError = class extends Error {
60
- constructor(messageId) {
61
- super(`Message ${messageId} has already been processed`);
62
- this.name = "MessageAlreadyProcessedError";
63
- }
64
- };
65
- var DuplicateMessageError = class extends Error {
66
- idempotencyKey;
67
- constructor(message, idempotencyKey) {
68
- super(message);
69
- this.name = "DuplicateMessageError";
70
- this.idempotencyKey = idempotencyKey;
71
- }
72
- };
73
- var ConsumerDiscoveryError = class extends Error {
74
- deploymentId;
75
- constructor(message, deploymentId) {
76
- super(message);
77
- this.name = "ConsumerDiscoveryError";
78
- this.deploymentId = deploymentId;
79
- }
80
- };
81
- var ConsumerRegistryNotConfiguredError = class extends Error {
82
- constructor(message = "Consumer registry not configured") {
83
- super(message);
84
- this.name = "ConsumerRegistryNotConfiguredError";
85
- }
86
- };
87
-
88
- // src/dev.ts
89
- var ROUTE_MAPPINGS_KEY = Symbol.for("@vercel/queue.devRouteMappings");
90
- function filePathToUrlPath(filePath) {
91
- let urlPath = filePath.replace(/^app\//, "/").replace(/^pages\//, "/").replace(/\/route\.(ts|mts|js|mjs|tsx|jsx)$/, "").replace(/\.(ts|mts|js|mjs|tsx|jsx)$/, "");
92
- if (!urlPath.startsWith("/")) {
93
- urlPath = "/" + urlPath;
94
- }
95
- return urlPath;
96
- }
97
- function filePathToConsumerGroup(filePath) {
98
- return filePath.replace(/_/g, "__").replace(/\//g, "_S").replace(/\./g, "_D");
99
- }
100
- function getDevRouteMappings() {
101
- const g = globalThis;
102
- if (ROUTE_MAPPINGS_KEY in g) {
103
- return g[ROUTE_MAPPINGS_KEY] ?? null;
104
- }
105
- try {
106
- const vercelJsonPath = path.join(process.cwd(), "vercel.json");
107
- if (!fs.existsSync(vercelJsonPath)) {
108
- g[ROUTE_MAPPINGS_KEY] = null;
109
- return null;
110
- }
111
- const vercelJson = JSON.parse(fs.readFileSync(vercelJsonPath, "utf-8"));
112
- if (!vercelJson.functions) {
113
- g[ROUTE_MAPPINGS_KEY] = null;
114
- return null;
115
- }
116
- const mappings = [];
117
- for (const [filePath, config] of Object.entries(vercelJson.functions)) {
118
- if (!config.experimentalTriggers) continue;
119
- for (const trigger of config.experimentalTriggers) {
120
- if (trigger.type?.startsWith("queue/") && trigger.topic) {
121
- mappings.push({
122
- urlPath: filePathToUrlPath(filePath),
123
- topic: trigger.topic,
124
- consumer: filePathToConsumerGroup(filePath)
125
- });
126
- }
127
- }
128
- }
129
- g[ROUTE_MAPPINGS_KEY] = mappings.length > 0 ? mappings : null;
130
- return g[ROUTE_MAPPINGS_KEY];
131
- } catch (error) {
132
- console.warn("[Dev Mode] Failed to read vercel.json:", error);
133
- g[ROUTE_MAPPINGS_KEY] = null;
134
- return null;
135
- }
136
- }
137
- function findMatchingRoutes(topicName) {
138
- const mappings = getDevRouteMappings();
139
- if (!mappings) {
140
- return [];
141
- }
142
- return mappings.filter((mapping) => {
143
- if (mapping.topic.includes("*")) {
144
- return matchesWildcardPattern(topicName, mapping.topic);
145
- }
146
- return mapping.topic === topicName;
147
- });
148
- }
149
- function isDevMode() {
150
- return process.env.NODE_ENV === "development";
151
- }
152
- var DEV_VISIBILITY_POLL_INTERVAL = 50;
153
- var DEV_VISIBILITY_MAX_WAIT = 5e3;
154
- var DEV_VISIBILITY_BACKOFF_MULTIPLIER = 2;
155
- async function waitForMessageVisibility(topicName, consumerGroup, messageId) {
156
- const client = new QueueClient();
157
- let elapsed = 0;
158
- let interval = DEV_VISIBILITY_POLL_INTERVAL;
159
- while (elapsed < DEV_VISIBILITY_MAX_WAIT) {
160
- try {
161
- await client.receiveMessageById({
162
- queueName: topicName,
163
- consumerGroup,
164
- messageId,
165
- visibilityTimeoutSeconds: 0
166
- });
167
- return true;
168
- } catch (error) {
169
- if (error instanceof MessageNotFoundError) {
170
- await new Promise((resolve) => setTimeout(resolve, interval));
171
- elapsed += interval;
172
- interval = Math.min(
173
- interval * DEV_VISIBILITY_BACKOFF_MULTIPLIER,
174
- DEV_VISIBILITY_MAX_WAIT - elapsed
175
- );
176
- continue;
177
- }
178
- if (error instanceof MessageAlreadyProcessedError) {
179
- console.log(
180
- `[Dev Mode] Message already processed: topic="${topicName}" messageId="${messageId}"`
181
- );
182
- return false;
183
- }
184
- console.error(
185
- `[Dev Mode] Error polling for message visibility: topic="${topicName}" messageId="${messageId}"`,
186
- error
187
- );
188
- return false;
189
- }
190
- }
191
- console.warn(
192
- `[Dev Mode] Message visibility timeout after ${DEV_VISIBILITY_MAX_WAIT}ms: topic="${topicName}" messageId="${messageId}"`
193
- );
194
- return false;
195
- }
196
- function triggerDevCallbacks(topicName, messageId, delaySeconds) {
197
- if (delaySeconds && delaySeconds > 0) {
198
- console.log(
199
- `[Dev Mode] Message sent with delay: topic="${topicName}" messageId="${messageId}" delay=${delaySeconds}s`
200
- );
201
- setTimeout(() => {
202
- triggerDevCallbacks(topicName, messageId);
203
- }, delaySeconds * 1e3);
204
- return;
205
- }
206
- console.log(
207
- `[Dev Mode] Message sent: topic="${topicName}" messageId="${messageId}"`
208
- );
209
- const matchingRoutes = findMatchingRoutes(topicName);
210
- if (matchingRoutes.length === 0) {
211
- console.log(
212
- `[Dev Mode] No matching routes in vercel.json for topic "${topicName}"`
213
- );
214
- return;
215
- }
216
- const consumerGroups = matchingRoutes.map((r) => r.consumer);
217
- console.log(
218
- `[Dev Mode] Scheduling callbacks for topic="${topicName}" messageId="${messageId}" \u2192 consumers: [${consumerGroups.join(", ")}]`
219
- );
220
- (async () => {
221
- const firstRoute = matchingRoutes[0];
222
- const isVisible = await waitForMessageVisibility(
223
- topicName,
224
- firstRoute.consumer,
225
- messageId
226
- );
227
- if (!isVisible) {
228
- console.warn(
229
- `[Dev Mode] Skipping callbacks - message not visible: topic="${topicName}" messageId="${messageId}"`
230
- );
231
- return;
232
- }
233
- const port = process.env.PORT || 3e3;
234
- const baseUrl = `http://localhost:${port}`;
235
- for (const route of matchingRoutes) {
236
- const url = `${baseUrl}${route.urlPath}`;
237
- console.log(
238
- `[Dev Mode] Invoking handler: topic="${topicName}" consumer="${route.consumer}" messageId="${messageId}" url="${url}"`
239
- );
240
- try {
241
- const response = await fetch(url, {
242
- method: "POST",
243
- headers: {
244
- "ce-type": CLOUD_EVENT_TYPE_V2BETA,
245
- "ce-vqsqueuename": topicName,
246
- "ce-vqsconsumergroup": route.consumer,
247
- "ce-vqsmessageid": messageId
248
- }
249
- });
250
- if (response.ok) {
251
- try {
252
- const responseData = await response.json();
253
- if (responseData.status === "success") {
254
- console.log(
255
- `[Dev Mode] \u2713 Message processed successfully: topic="${topicName}" consumer="${route.consumer}" messageId="${messageId}"`
256
- );
257
- }
258
- } catch {
259
- console.warn(
260
- `[Dev Mode] Handler returned OK but response was not JSON: topic="${topicName}" consumer="${route.consumer}"`
261
- );
262
- }
263
- } else {
264
- try {
265
- const errorData = await response.json();
266
- console.error(
267
- `[Dev Mode] \u2717 Handler failed: topic="${topicName}" consumer="${route.consumer}" messageId="${messageId}" error="${errorData.error || response.statusText}"`
268
- );
269
- } catch {
270
- console.error(
271
- `[Dev Mode] \u2717 Handler failed: topic="${topicName}" consumer="${route.consumer}" messageId="${messageId}" status=${response.status}`
272
- );
273
- }
274
- }
275
- } catch (error) {
276
- console.error(
277
- `[Dev Mode] \u2717 HTTP request failed: topic="${topicName}" consumer="${route.consumer}" messageId="${messageId}" url="${url}"`,
278
- error
279
- );
280
- }
281
- }
282
- })();
283
- }
284
- function clearDevRouteMappings() {
285
- const g = globalThis;
286
- delete g[ROUTE_MAPPINGS_KEY];
287
- }
288
- if (process.env.NODE_ENV === "test" || process.env.VITEST) {
289
- globalThis.__clearDevRouteMappings = clearDevRouteMappings;
290
- }
291
-
292
- // src/oidc.ts
293
- import { getVercelOidcToken } from "@vercel/oidc";
294
-
295
- // src/transports.ts
296
- async function streamToBuffer(stream) {
297
- let totalLength = 0;
298
- const reader = stream.getReader();
299
- const chunks = [];
300
- try {
301
- while (true) {
302
- const { done, value } = await reader.read();
303
- if (done) break;
304
- chunks.push(value);
305
- totalLength += value.length;
306
- }
307
- } finally {
308
- reader.releaseLock();
309
- }
310
- return Buffer.concat(chunks, totalLength);
311
- }
312
- var JsonTransport = class {
313
- contentType = "application/json";
314
- replacer;
315
- reviver;
316
- /**
317
- * Create a new JsonTransport.
318
- * @param options - Optional JSON serialization options
319
- * @param options.replacer - Custom replacer for JSON.stringify
320
- * @param options.reviver - Custom reviver for JSON.parse
321
- */
322
- constructor(options = {}) {
323
- this.replacer = options.replacer;
324
- this.reviver = options.reviver;
325
- }
326
- serialize(value) {
327
- return Buffer.from(JSON.stringify(value, this.replacer), "utf8");
328
- }
329
- async deserialize(stream) {
330
- const buffer = await streamToBuffer(stream);
331
- return JSON.parse(buffer.toString("utf8"), this.reviver);
332
- }
333
- };
334
-
335
- // src/client.ts
336
- function isDebugEnabled() {
337
- return process.env.VERCEL_QUEUE_DEBUG === "1" || process.env.VERCEL_QUEUE_DEBUG === "true";
338
- }
339
- async function consumeStream(stream) {
340
- const reader = stream.getReader();
341
- try {
342
- while (true) {
343
- const { done } = await reader.read();
344
- if (done) break;
345
- }
346
- } finally {
347
- reader.releaseLock();
348
- }
349
- }
350
- function throwCommonHttpError(status, statusText, errorText, operation, badRequestDefault = "Invalid parameters") {
351
- if (status === 400) {
352
- throw new BadRequestError(errorText || badRequestDefault);
353
- }
354
- if (status === 401) {
355
- throw new UnauthorizedError(errorText || void 0);
356
- }
357
- if (status === 403) {
358
- throw new ForbiddenError(errorText || void 0);
359
- }
360
- if (status >= 500) {
361
- throw new InternalServerError(
362
- errorText || `Server error: ${status} ${statusText}`
363
- );
364
- }
365
- throw new Error(`Failed to ${operation}: ${status} ${statusText}`);
366
- }
367
- function parseQueueHeaders(headers) {
368
- const messageId = headers.get("Vqs-Message-Id");
369
- const deliveryCountStr = headers.get("Vqs-Delivery-Count") || "0";
370
- const timestamp = headers.get("Vqs-Timestamp");
371
- const contentType = headers.get("Content-Type") || "application/octet-stream";
372
- const receiptHandle = headers.get("Vqs-Receipt-Handle");
373
- if (!messageId || !timestamp || !receiptHandle) {
374
- return null;
375
- }
376
- const deliveryCount = parseInt(deliveryCountStr, 10);
377
- if (Number.isNaN(deliveryCount)) {
378
- return null;
379
- }
380
- return {
381
- messageId,
382
- deliveryCount,
383
- createdAt: new Date(timestamp),
384
- contentType,
385
- receiptHandle
386
- };
387
- }
388
- var QueueClient = class {
389
- baseUrl;
390
- basePath;
391
- customHeaders;
392
- providedToken;
393
- defaultDeploymentId;
394
- pinToDeployment;
395
- transport;
396
- constructor(options = {}) {
397
- this.baseUrl = options.baseUrl || process.env.VERCEL_QUEUE_BASE_URL || "https://vercel-queue.com";
398
- this.basePath = options.basePath || process.env.VERCEL_QUEUE_BASE_PATH || "/api/v3/topic";
399
- this.customHeaders = options.headers || {};
400
- this.providedToken = options.token;
401
- this.defaultDeploymentId = options.deploymentId || process.env.VERCEL_DEPLOYMENT_ID;
402
- this.pinToDeployment = options.pinToDeployment ?? true;
403
- this.transport = options.transport || new JsonTransport();
404
- }
405
- getTransport() {
406
- return this.transport;
407
- }
408
- getSendDeploymentId() {
409
- if (isDevMode()) {
410
- return void 0;
411
- }
412
- if (this.pinToDeployment) {
413
- return this.defaultDeploymentId;
414
- }
415
- return void 0;
416
- }
417
- getConsumeDeploymentId() {
418
- if (isDevMode()) {
419
- return void 0;
420
- }
421
- return this.defaultDeploymentId;
422
- }
423
- async getToken() {
424
- if (this.providedToken) {
425
- return this.providedToken;
426
- }
427
- const token = await getVercelOidcToken();
428
- if (!token) {
429
- throw new Error(
430
- "Failed to get OIDC token from Vercel Functions. Make sure you are running in a Vercel Function environment, or provide a token explicitly.\n\nTo set up your environment:\n1. Link your project: 'vercel link'\n2. Pull environment variables: 'vercel env pull'\n3. Run with environment: 'dotenv -e .env.local -- your-command'"
431
- );
432
- }
433
- return token;
434
- }
435
- buildUrl(queueName, ...pathSegments) {
436
- const encodedQueue = encodeURIComponent(queueName);
437
- const segments = pathSegments.map((s) => encodeURIComponent(s));
438
- const path2 = segments.length > 0 ? "/" + segments.join("/") : "";
439
- return `${this.baseUrl}${this.basePath}/${encodedQueue}${path2}`;
440
- }
441
- async fetch(url, init) {
442
- const method = init.method || "GET";
443
- if (isDebugEnabled()) {
444
- const logData = {
445
- method,
446
- url,
447
- headers: init.headers
448
- };
449
- const body = init.body;
450
- if (body !== void 0 && body !== null) {
451
- if (body instanceof ArrayBuffer) {
452
- logData.bodySize = body.byteLength;
453
- } else if (body instanceof Uint8Array) {
454
- logData.bodySize = body.byteLength;
455
- } else if (typeof body === "string") {
456
- logData.bodySize = body.length;
457
- } else {
458
- logData.bodyType = typeof body;
459
- }
460
- }
461
- console.debug("[VQS Debug] Request:", JSON.stringify(logData, null, 2));
462
- }
463
- init.headers.set("User-Agent", `@vercel/queue/${"0.0.0-alpha.39"}`);
464
- init.headers.set("Vqs-Client-Ts", (/* @__PURE__ */ new Date()).toISOString());
465
- const response = await fetch(url, init);
466
- if (isDebugEnabled()) {
467
- const logData = {
468
- method,
469
- url,
470
- status: response.status,
471
- statusText: response.statusText,
472
- headers: response.headers
473
- };
474
- console.debug("[VQS Debug] Response:", JSON.stringify(logData, null, 2));
475
- }
476
- return response;
477
- }
478
- /**
479
- * Send a message to a topic.
480
- *
481
- * @param options - Message options including queue name, payload, and optional settings
482
- * @param options.queueName - Topic name (pattern: `[A-Za-z0-9_-]+`)
483
- * @param options.payload - Message payload
484
- * @param options.idempotencyKey - Optional deduplication key (dedup window: min(retention, 24h))
485
- * @param options.retentionSeconds - Message TTL (default: 86400, min: 60, max: 86400)
486
- * @param options.delaySeconds - Delivery delay (default: 0, max: retentionSeconds)
487
- * @returns Promise with the generated messageId
488
- * @throws {DuplicateMessageError} When idempotency key was already used
489
- * @throws {ConsumerDiscoveryError} When consumer discovery fails
490
- * @throws {ConsumerRegistryNotConfiguredError} When registry not configured
491
- * @throws {BadRequestError} When parameters are invalid
492
- * @throws {UnauthorizedError} When authentication fails
493
- * @throws {ForbiddenError} When access is denied
494
- * @throws {InternalServerError} When server encounters an error
495
- */
496
- async sendMessage(options) {
497
- const transport = this.transport;
498
- const {
499
- queueName,
500
- payload,
501
- idempotencyKey,
502
- retentionSeconds,
503
- delaySeconds,
504
- headers: optionHeaders
505
- } = options;
506
- const headers = new Headers();
507
- if (this.customHeaders) {
508
- for (const [name, value] of Object.entries(this.customHeaders)) {
509
- headers.append(name, value);
510
- }
511
- }
512
- if (optionHeaders) {
513
- const protectedHeaderNames = /* @__PURE__ */ new Set(["authorization", "content-type"]);
514
- const isProtectedHeader = (name) => {
515
- const lower = name.toLowerCase();
516
- if (protectedHeaderNames.has(lower)) return true;
517
- return lower.startsWith("vqs-");
518
- };
519
- for (const [name, value] of Object.entries(optionHeaders)) {
520
- if (!isProtectedHeader(name) && value !== void 0) {
521
- headers.append(name, value);
522
- }
523
- }
524
- }
525
- headers.set("Authorization", `Bearer ${await this.getToken()}`);
526
- headers.set("Content-Type", transport.contentType);
527
- const deploymentId = this.getSendDeploymentId();
528
- if (deploymentId) {
529
- headers.set("Vqs-Deployment-Id", deploymentId);
530
- }
531
- if (idempotencyKey) {
532
- headers.set("Vqs-Idempotency-Key", idempotencyKey);
533
- }
534
- if (retentionSeconds !== void 0) {
535
- headers.set("Vqs-Retention-Seconds", retentionSeconds.toString());
536
- }
537
- if (delaySeconds !== void 0) {
538
- headers.set("Vqs-Delay-Seconds", delaySeconds.toString());
539
- }
540
- const serialized = transport.serialize(payload);
541
- const body = Buffer.isBuffer(serialized) ? new Uint8Array(serialized) : serialized;
542
- const response = await this.fetch(this.buildUrl(queueName), {
543
- method: "POST",
544
- body,
545
- headers
546
- });
547
- if (!response.ok) {
548
- const errorText = await response.text();
549
- if (response.status === 409) {
550
- throw new DuplicateMessageError(
551
- errorText || "Duplicate idempotency key detected",
552
- idempotencyKey
553
- );
554
- }
555
- if (response.status === 502) {
556
- throw new ConsumerDiscoveryError(
557
- errorText || "Consumer discovery failed",
558
- deploymentId
559
- );
560
- }
561
- if (response.status === 503) {
562
- throw new ConsumerRegistryNotConfiguredError(
563
- errorText || "Consumer registry not configured"
564
- );
565
- }
566
- throwCommonHttpError(
567
- response.status,
568
- response.statusText,
569
- errorText,
570
- "send message"
571
- );
572
- }
573
- const responseData = await response.json();
574
- return responseData;
575
- }
576
- /**
577
- * Receive messages from a topic as an async generator.
578
- *
579
- * When the queue is empty, the generator completes without yielding any
580
- * messages. Callers should handle the case where no messages are yielded.
581
- *
582
- * @param options - Receive options
583
- * @param options.queueName - Topic name (pattern: `[A-Za-z0-9_-]+`)
584
- * @param options.consumerGroup - Consumer group name (pattern: `[A-Za-z0-9_-]+`)
585
- * @param options.visibilityTimeoutSeconds - Lock duration (default: 30, min: 0, max: 3600)
586
- * @param options.limit - Max messages to retrieve (default: 1, min: 1, max: 10)
587
- * @yields Message objects with payload, messageId, receiptHandle, etc.
588
- * Yields nothing if queue is empty.
589
- * @throws {InvalidLimitError} When limit is outside 1-10 range
590
- * @throws {BadRequestError} When parameters are invalid
591
- * @throws {UnauthorizedError} When authentication fails
592
- * @throws {ForbiddenError} When access is denied
593
- * @throws {InternalServerError} When server encounters an error
594
- */
595
- async *receiveMessages(options) {
596
- const transport = this.transport;
597
- const { queueName, consumerGroup, visibilityTimeoutSeconds, limit } = options;
598
- if (limit !== void 0 && (limit < 1 || limit > 10)) {
599
- throw new InvalidLimitError(limit);
600
- }
601
- const headers = new Headers({
602
- Authorization: `Bearer ${await this.getToken()}`,
603
- Accept: "multipart/mixed",
604
- ...this.customHeaders
605
- });
606
- if (visibilityTimeoutSeconds !== void 0) {
607
- headers.set(
608
- "Vqs-Visibility-Timeout-Seconds",
609
- visibilityTimeoutSeconds.toString()
610
- );
611
- }
612
- if (limit !== void 0) {
613
- headers.set("Vqs-Max-Messages", limit.toString());
614
- }
615
- const effectiveDeploymentId = this.getConsumeDeploymentId();
616
- if (effectiveDeploymentId) {
617
- headers.set("Vqs-Deployment-Id", effectiveDeploymentId);
618
- }
619
- const response = await this.fetch(
620
- this.buildUrl(queueName, "consumer", consumerGroup),
621
- {
622
- method: "POST",
623
- headers
624
- }
625
- );
626
- if (response.status === 204) {
627
- return;
628
- }
629
- if (!response.ok) {
630
- const errorText = await response.text();
631
- throwCommonHttpError(
632
- response.status,
633
- response.statusText,
634
- errorText,
635
- "receive messages"
636
- );
637
- }
638
- for await (const multipartMessage of parseMultipartStream(response)) {
639
- try {
640
- const parsedHeaders = parseQueueHeaders(multipartMessage.headers);
641
- if (!parsedHeaders) {
642
- console.warn("Missing required queue headers in multipart part");
643
- await consumeStream(multipartMessage.payload);
644
- continue;
645
- }
646
- const deserializedPayload = await transport.deserialize(
647
- multipartMessage.payload
648
- );
649
- const message = {
650
- ...parsedHeaders,
651
- payload: deserializedPayload
652
- };
653
- yield message;
654
- } catch (error) {
655
- console.warn("Failed to process multipart message:", error);
656
- await consumeStream(multipartMessage.payload);
657
- }
658
- }
659
- }
660
- /**
661
- * Receive a specific message by its ID.
662
- *
663
- * @param options - Receive options
664
- * @param options.queueName - Topic name (pattern: `[A-Za-z0-9_-]+`)
665
- * @param options.consumerGroup - Consumer group name (pattern: `[A-Za-z0-9_-]+`)
666
- * @param options.messageId - Message ID to retrieve
667
- * @param options.visibilityTimeoutSeconds - Lock duration (default: 30, min: 0, max: 3600)
668
- * @returns Promise with the message
669
- * @throws {MessageNotFoundError} When message doesn't exist
670
- * @throws {MessageNotAvailableError} When message is in wrong state or was a duplicate
671
- * @throws {MessageAlreadyProcessedError} When message was already processed
672
- * @throws {BadRequestError} When parameters are invalid
673
- * @throws {UnauthorizedError} When authentication fails
674
- * @throws {ForbiddenError} When access is denied
675
- * @throws {InternalServerError} When server encounters an error
676
- */
677
- async receiveMessageById(options) {
678
- const transport = this.transport;
679
- const { queueName, consumerGroup, messageId, visibilityTimeoutSeconds } = options;
680
- const headers = new Headers({
681
- Authorization: `Bearer ${await this.getToken()}`,
682
- Accept: "multipart/mixed",
683
- ...this.customHeaders
684
- });
685
- if (visibilityTimeoutSeconds !== void 0) {
686
- headers.set(
687
- "Vqs-Visibility-Timeout-Seconds",
688
- visibilityTimeoutSeconds.toString()
689
- );
690
- }
691
- const effectiveDeploymentId = this.getConsumeDeploymentId();
692
- if (effectiveDeploymentId) {
693
- headers.set("Vqs-Deployment-Id", effectiveDeploymentId);
694
- }
695
- const response = await this.fetch(
696
- this.buildUrl(queueName, "consumer", consumerGroup, "id", messageId),
697
- {
698
- method: "POST",
699
- headers
700
- }
701
- );
702
- if (!response.ok) {
703
- const errorText = await response.text();
704
- if (response.status === 404) {
705
- throw new MessageNotFoundError(messageId);
706
- }
707
- if (response.status === 409) {
708
- let errorData = {};
709
- try {
710
- errorData = JSON.parse(errorText);
711
- } catch {
712
- }
713
- if (errorData.originalMessageId) {
714
- throw new MessageNotAvailableError(
715
- messageId,
716
- `This message was a duplicate - use originalMessageId: ${errorData.originalMessageId}`
717
- );
718
- }
719
- throw new MessageNotAvailableError(messageId);
720
- }
721
- if (response.status === 410) {
722
- throw new MessageAlreadyProcessedError(messageId);
723
- }
724
- throwCommonHttpError(
725
- response.status,
726
- response.statusText,
727
- errorText,
728
- "receive message by ID"
729
- );
730
- }
731
- for await (const multipartMessage of parseMultipartStream(response)) {
732
- const parsedHeaders = parseQueueHeaders(multipartMessage.headers);
733
- if (!parsedHeaders) {
734
- await consumeStream(multipartMessage.payload);
735
- throw new MessageCorruptedError(
736
- messageId,
737
- "Missing required queue headers in response"
738
- );
739
- }
740
- const deserializedPayload = await transport.deserialize(
741
- multipartMessage.payload
742
- );
743
- const message = {
744
- ...parsedHeaders,
745
- payload: deserializedPayload
746
- };
747
- return { message };
748
- }
749
- throw new MessageNotFoundError(messageId);
750
- }
751
- /**
752
- * Delete (acknowledge) a message after successful processing.
753
- *
754
- * @param options - Delete options
755
- * @param options.queueName - Topic name
756
- * @param options.consumerGroup - Consumer group name
757
- * @param options.receiptHandle - Receipt handle from the received message (must use same deployment ID as receive)
758
- * @returns Promise indicating deletion success
759
- * @throws {MessageNotFoundError} When receipt handle not found
760
- * @throws {MessageNotAvailableError} When receipt handle invalid or message already processed
761
- * @throws {BadRequestError} When parameters are invalid
762
- * @throws {UnauthorizedError} When authentication fails
763
- * @throws {ForbiddenError} When access is denied
764
- * @throws {InternalServerError} When server encounters an error
765
- */
766
- async deleteMessage(options) {
767
- const { queueName, consumerGroup, receiptHandle } = options;
768
- const headers = new Headers({
769
- Authorization: `Bearer ${await this.getToken()}`,
770
- ...this.customHeaders
771
- });
772
- const effectiveDeploymentId = this.getConsumeDeploymentId();
773
- if (effectiveDeploymentId) {
774
- headers.set("Vqs-Deployment-Id", effectiveDeploymentId);
775
- }
776
- const response = await this.fetch(
777
- this.buildUrl(
778
- queueName,
779
- "consumer",
780
- consumerGroup,
781
- "lease",
782
- receiptHandle
783
- ),
784
- {
785
- method: "DELETE",
786
- headers
787
- }
788
- );
789
- if (!response.ok) {
790
- const errorText = await response.text();
791
- if (response.status === 404) {
792
- throw new MessageNotFoundError(receiptHandle);
793
- }
794
- if (response.status === 409) {
795
- throw new MessageNotAvailableError(
796
- receiptHandle,
797
- errorText || "Invalid receipt handle, message not in correct state, or already processed"
798
- );
799
- }
800
- throwCommonHttpError(
801
- response.status,
802
- response.statusText,
803
- errorText,
804
- "delete message",
805
- "Missing or invalid receipt handle"
806
- );
807
- }
808
- return { deleted: true };
809
- }
810
- /**
811
- * Extend or change the visibility timeout of a message.
812
- * Used to prevent message redelivery while still processing.
813
- *
814
- * @param options - Visibility options
815
- * @param options.queueName - Topic name
816
- * @param options.consumerGroup - Consumer group name
817
- * @param options.receiptHandle - Receipt handle from the received message (must use same deployment ID as receive)
818
- * @param options.visibilityTimeoutSeconds - New timeout (min: 0, max: 3600, cannot exceed message expiration)
819
- * @returns Promise indicating success
820
- * @throws {MessageNotFoundError} When receipt handle not found
821
- * @throws {MessageNotAvailableError} When receipt handle invalid or message already processed
822
- * @throws {BadRequestError} When parameters are invalid
823
- * @throws {UnauthorizedError} When authentication fails
824
- * @throws {ForbiddenError} When access is denied
825
- * @throws {InternalServerError} When server encounters an error
826
- */
827
- async changeVisibility(options) {
828
- const {
829
- queueName,
830
- consumerGroup,
831
- receiptHandle,
832
- visibilityTimeoutSeconds
833
- } = options;
834
- const headers = new Headers({
835
- Authorization: `Bearer ${await this.getToken()}`,
836
- "Content-Type": "application/json",
837
- ...this.customHeaders
838
- });
839
- const effectiveDeploymentId = this.getConsumeDeploymentId();
840
- if (effectiveDeploymentId) {
841
- headers.set("Vqs-Deployment-Id", effectiveDeploymentId);
842
- }
843
- const response = await this.fetch(
844
- this.buildUrl(
845
- queueName,
846
- "consumer",
847
- consumerGroup,
848
- "lease",
849
- receiptHandle
850
- ),
851
- {
852
- method: "PATCH",
853
- headers,
854
- body: JSON.stringify({ visibilityTimeoutSeconds })
855
- }
856
- );
857
- if (!response.ok) {
858
- const errorText = await response.text();
859
- if (response.status === 404) {
860
- throw new MessageNotFoundError(receiptHandle);
861
- }
862
- if (response.status === 409) {
863
- throw new MessageNotAvailableError(
864
- receiptHandle,
865
- errorText || "Invalid receipt handle, message not in correct state, or already processed"
866
- );
867
- }
868
- throwCommonHttpError(
869
- response.status,
870
- response.statusText,
871
- errorText,
872
- "change visibility",
873
- "Missing receipt handle or invalid visibility timeout"
874
- );
875
- }
876
- return { success: true };
877
- }
878
- /**
879
- * Alternative endpoint for changing message visibility timeout.
880
- * Uses the /visibility path suffix and expects visibilityTimeoutSeconds in the body.
881
- * Functionally equivalent to changeVisibility but follows an alternative API pattern.
882
- *
883
- * @param options - Options for changing visibility
884
- * @returns Promise resolving to change visibility response
885
- */
886
- async changeVisibilityAlt(options) {
887
- const {
888
- queueName,
889
- consumerGroup,
890
- receiptHandle,
891
- visibilityTimeoutSeconds
892
- } = options;
893
- const headers = new Headers({
894
- Authorization: `Bearer ${await this.getToken()}`,
895
- "Content-Type": "application/json",
896
- ...this.customHeaders
897
- });
898
- const effectiveDeploymentId = this.getConsumeDeploymentId();
899
- if (effectiveDeploymentId) {
900
- headers.set("Vqs-Deployment-Id", effectiveDeploymentId);
901
- }
902
- const response = await this.fetch(
903
- this.buildUrl(
904
- queueName,
905
- "consumer",
906
- consumerGroup,
907
- "lease",
908
- receiptHandle,
909
- "visibility"
910
- ),
911
- {
912
- method: "PATCH",
913
- headers,
914
- body: JSON.stringify({ visibilityTimeoutSeconds })
915
- }
916
- );
917
- if (!response.ok) {
918
- const errorText = await response.text();
919
- if (response.status === 404) {
920
- throw new MessageNotFoundError(receiptHandle);
921
- }
922
- if (response.status === 409) {
923
- throw new MessageNotAvailableError(
924
- receiptHandle,
925
- errorText || "Invalid receipt handle, message not in correct state, or already processed"
926
- );
927
- }
928
- throwCommonHttpError(
929
- response.status,
930
- response.statusText,
931
- errorText,
932
- "change visibility (alt)",
933
- "Missing receipt handle or invalid visibility timeout"
934
- );
935
- }
936
- return { success: true };
937
- }
938
- };
939
-
940
- // src/consumer-group.ts
941
- var DEFAULT_VISIBILITY_TIMEOUT_SECONDS = 300;
942
- var MIN_VISIBILITY_TIMEOUT_SECONDS = 30;
943
- var MAX_RENEWAL_INTERVAL_SECONDS = 60;
944
- var MIN_RENEWAL_INTERVAL_SECONDS = 10;
945
- var RETRY_INTERVAL_MS = 3e3;
946
- function calculateRenewalInterval(visibilityTimeoutSeconds) {
947
- return Math.min(
948
- MAX_RENEWAL_INTERVAL_SECONDS,
949
- Math.max(MIN_RENEWAL_INTERVAL_SECONDS, visibilityTimeoutSeconds / 5)
950
- );
951
- }
952
- var ConsumerGroup = class {
953
- client;
954
- topicName;
955
- consumerGroupName;
956
- visibilityTimeout;
957
- /**
958
- * Create a new ConsumerGroup instance.
959
- *
960
- * @param client - QueueClient instance to use for API calls (transport is configured on the client)
961
- * @param topicName - Name of the topic to consume from (pattern: `[A-Za-z0-9_-]+`)
962
- * @param consumerGroupName - Name of the consumer group (pattern: `[A-Za-z0-9_-]+`)
963
- * @param options - Optional configuration
964
- * @param options.visibilityTimeoutSeconds - Message lock duration (default: 300, max: 3600)
965
- */
966
- constructor(client, topicName, consumerGroupName, options = {}) {
967
- this.client = client;
968
- this.topicName = topicName;
969
- this.consumerGroupName = consumerGroupName;
970
- this.visibilityTimeout = Math.max(
971
- MIN_VISIBILITY_TIMEOUT_SECONDS,
972
- options.visibilityTimeoutSeconds ?? DEFAULT_VISIBILITY_TIMEOUT_SECONDS
973
- );
974
- }
975
- /**
976
- * Check if an error is a 4xx client error that should stop retries.
977
- * 4xx errors indicate the request is fundamentally invalid and retrying won't help.
978
- * - 409: Ticket mismatch (lost ownership to another consumer)
979
- * - 404: Message/receipt handle not found
980
- * - 400, 401, 403: Other client errors
981
- */
982
- isClientError(error) {
983
- return error instanceof MessageNotAvailableError || // 409 - ticket mismatch, lost ownership
984
- error instanceof MessageNotFoundError || // 404 - receipt handle not found
985
- error instanceof BadRequestError || // 400 - invalid parameters
986
- error instanceof UnauthorizedError || // 401 - auth failed
987
- error instanceof ForbiddenError;
988
- }
989
- /**
990
- * Starts a background loop that periodically extends the visibility timeout for a message.
991
- *
992
- * Timing strategy:
993
- * - Renewal interval: min(60s, max(10s, visibilityTimeout/5))
994
- * - Extensions request the same duration as the initial visibility timeout
995
- * - When `visibilityDeadline` is provided (binary mode small body), the first
996
- * extension delay is calculated from the time remaining until the deadline
997
- * using the same renewal formula, ensuring the first extension fires before
998
- * the server-assigned lease expires. Subsequent renewals use the standard interval.
999
- *
1000
- * Retry strategy:
1001
- * - On transient failures (5xx, network errors): retry every 3 seconds
1002
- * - On 4xx client errors: stop retrying (the lease is lost or invalid)
1003
- *
1004
- * @param receiptHandle - The receipt handle to extend visibility for
1005
- * @param options - Optional configuration
1006
- * @param options.visibilityDeadline - Absolute deadline (from server's `ce-vqsvisibilitydeadline`)
1007
- * when the current visibility timeout expires. Used to calculate the first extension delay.
1008
- */
1009
- startVisibilityExtension(receiptHandle, options) {
1010
- let isRunning = true;
1011
- let isResolved = false;
1012
- let resolveLifecycle;
1013
- let timeoutId = null;
1014
- const renewalIntervalMs = calculateRenewalInterval(this.visibilityTimeout) * 1e3;
1015
- let firstDelayMs = renewalIntervalMs;
1016
- if (options?.visibilityDeadline) {
1017
- const timeRemainingMs = options.visibilityDeadline.getTime() - Date.now();
1018
- if (timeRemainingMs > 0) {
1019
- const timeRemainingSeconds = timeRemainingMs / 1e3;
1020
- firstDelayMs = calculateRenewalInterval(timeRemainingSeconds) * 1e3;
1021
- } else {
1022
- firstDelayMs = 0;
1023
- }
1024
- }
1025
- const lifecyclePromise = new Promise((resolve) => {
1026
- resolveLifecycle = resolve;
1027
- });
1028
- const safeResolve = () => {
1029
- if (!isResolved) {
1030
- isResolved = true;
1031
- resolveLifecycle();
1032
- }
1033
- };
1034
- const extend = async () => {
1035
- if (!isRunning) {
1036
- safeResolve();
1037
- return;
1038
- }
1039
- try {
1040
- await this.client.changeVisibility({
1041
- queueName: this.topicName,
1042
- consumerGroup: this.consumerGroupName,
1043
- receiptHandle,
1044
- visibilityTimeoutSeconds: this.visibilityTimeout
1045
- });
1046
- if (isRunning) {
1047
- timeoutId = setTimeout(() => extend(), renewalIntervalMs);
1048
- } else {
1049
- safeResolve();
1050
- }
1051
- } catch (error) {
1052
- if (this.isClientError(error)) {
1053
- console.error(
1054
- `Visibility extension failed with client error for receipt handle ${receiptHandle} (stopping retries):`,
1055
- error
1056
- );
1057
- safeResolve();
1058
- return;
1059
- }
1060
- console.error(
1061
- `Failed to extend visibility for receipt handle ${receiptHandle} (will retry in ${RETRY_INTERVAL_MS / 1e3}s):`,
1062
- error
1063
- );
1064
- if (isRunning) {
1065
- timeoutId = setTimeout(() => extend(), RETRY_INTERVAL_MS);
1066
- } else {
1067
- safeResolve();
1068
- }
1069
- }
1070
- };
1071
- timeoutId = setTimeout(() => extend(), firstDelayMs);
1072
- return async (waitForCompletion = false) => {
1073
- isRunning = false;
1074
- if (timeoutId) {
1075
- clearTimeout(timeoutId);
1076
- timeoutId = null;
1077
- }
1078
- if (waitForCompletion) {
1079
- await lifecyclePromise;
1080
- } else {
1081
- safeResolve();
1082
- }
1083
- };
1084
- }
1085
- async processMessage(message, handler, options) {
1086
- const stopExtension = this.startVisibilityExtension(
1087
- message.receiptHandle,
1088
- options
1089
- );
1090
- try {
1091
- await handler(message.payload, {
1092
- messageId: message.messageId,
1093
- deliveryCount: message.deliveryCount,
1094
- createdAt: message.createdAt,
1095
- topicName: this.topicName,
1096
- consumerGroup: this.consumerGroupName
1097
- });
1098
- await stopExtension();
1099
- await this.client.deleteMessage({
1100
- queueName: this.topicName,
1101
- consumerGroup: this.consumerGroupName,
1102
- receiptHandle: message.receiptHandle
1103
- });
1104
- } catch (error) {
1105
- await stopExtension();
1106
- const transport = this.client.getTransport();
1107
- if (transport.finalize && message.payload !== void 0 && message.payload !== null) {
1108
- try {
1109
- await transport.finalize(message.payload);
1110
- } catch (finalizeError) {
1111
- console.warn("Failed to finalize message payload:", finalizeError);
1112
- }
1113
- }
1114
- throw error;
1115
- }
1116
- }
1117
- /**
1118
- * Process a pre-fetched message directly, without calling `receiveMessageById`.
1119
- *
1120
- * Used by the binary mode (v2beta) small body fast path, where the server
1121
- * pushes the full message payload in the callback request. The message is
1122
- * processed with the same lifecycle guarantees as `consume()`:
1123
- * - Visibility timeout is extended periodically during processing
1124
- * - Message is deleted on successful handler completion
1125
- * - Payload is finalized on error if the transport supports it
1126
- *
1127
- * @param handler - Function to process the message payload and metadata
1128
- * @param message - The complete message including payload and receipt handle
1129
- * @param options - Optional configuration
1130
- * @param options.visibilityDeadline - Absolute deadline when the server-assigned
1131
- * visibility timeout expires (from `ce-vqsvisibilitydeadline`). Used to
1132
- * schedule the first visibility extension before the lease expires.
1133
- */
1134
- async consumeMessage(handler, message, options) {
1135
- await this.processMessage(message, handler, options);
1136
- }
1137
- async consume(handler, options) {
1138
- if (options && "messageId" in options) {
1139
- const response = await this.client.receiveMessageById({
1140
- queueName: this.topicName,
1141
- consumerGroup: this.consumerGroupName,
1142
- messageId: options.messageId,
1143
- visibilityTimeoutSeconds: this.visibilityTimeout
1144
- });
1145
- await this.processMessage(response.message, handler);
1146
- } else {
1147
- const limit = options && "limit" in options ? options.limit : 1;
1148
- let messageFound = false;
1149
- for await (const message of this.client.receiveMessages({
1150
- queueName: this.topicName,
1151
- consumerGroup: this.consumerGroupName,
1152
- visibilityTimeoutSeconds: this.visibilityTimeout,
1153
- limit
1154
- })) {
1155
- messageFound = true;
1156
- await this.processMessage(message, handler);
1157
- }
1158
- if (!messageFound) {
1159
- await handler(null, null);
1160
- }
1161
- }
1162
- }
1163
- /**
1164
- * Get the consumer group name
1165
- */
1166
- get name() {
1167
- return this.consumerGroupName;
1168
- }
1169
- /**
1170
- * Get the topic name this consumer group is subscribed to
1171
- */
1172
- get topic() {
1173
- return this.topicName;
1174
- }
1175
- };
1176
-
1177
- // src/topic.ts
1178
- var Topic = class {
1179
- client;
1180
- topicName;
1181
- /**
1182
- * Create a new Topic instance
1183
- * @param client QueueClient instance to use for API calls (transport is configured on the client)
1184
- * @param topicName Name of the topic to work with
1185
- */
1186
- constructor(client, topicName) {
1187
- this.client = client;
1188
- this.topicName = topicName;
1189
- }
1190
- /**
1191
- * Publish a message to the topic
1192
- * @param payload The data to publish
1193
- * @param options Optional publish options
1194
- * @returns An object containing the message ID
1195
- * @throws {BadRequestError} When request parameters are invalid
1196
- * @throws {UnauthorizedError} When authentication fails
1197
- * @throws {ForbiddenError} When access is denied (environment mismatch)
1198
- * @throws {InternalServerError} When server encounters an error
1199
- */
1200
- async publish(payload, options) {
1201
- const result = await this.client.sendMessage({
1202
- queueName: this.topicName,
1203
- payload,
1204
- idempotencyKey: options?.idempotencyKey,
1205
- retentionSeconds: options?.retentionSeconds,
1206
- delaySeconds: options?.delaySeconds,
1207
- headers: options?.headers
1208
- });
1209
- if (isDevMode()) {
1210
- triggerDevCallbacks(this.topicName, result.messageId);
1211
- }
1212
- return { messageId: result.messageId };
1213
- }
1214
- /**
1215
- * Create a consumer group for this topic
1216
- * @param consumerGroupName Name of the consumer group
1217
- * @param options Optional configuration for the consumer group
1218
- * @returns A ConsumerGroup instance
1219
- */
1220
- consumerGroup(consumerGroupName, options) {
1221
- return new ConsumerGroup(
1222
- this.client,
1223
- this.topicName,
1224
- consumerGroupName,
1225
- options
1226
- );
1227
- }
1228
- /**
1229
- * Get the topic name
1230
- */
1231
- get name() {
1232
- return this.topicName;
1233
- }
1234
- };
1235
-
1236
- // src/callback.ts
1237
- var CLOUD_EVENT_TYPE_V1BETA = "com.vercel.queue.v1beta";
1238
- var CLOUD_EVENT_TYPE_V2BETA = "com.vercel.queue.v2beta";
1239
- function matchesWildcardPattern(topicName, pattern) {
1240
- const prefix = pattern.slice(0, -1);
1241
- return topicName.startsWith(prefix);
1242
- }
1243
- function isRecord(value) {
1244
- return typeof value === "object" && value !== null;
1245
- }
1246
- function parseV1StructuredBody(body, contentType) {
1247
- if (!contentType || !contentType.includes("application/cloudevents+json")) {
1248
- throw new Error(
1249
- "Invalid content type: expected 'application/cloudevents+json'"
1250
- );
1251
- }
1252
- if (!isRecord(body) || !body.type || !body.source || !body.id || !isRecord(body.data)) {
1253
- throw new Error("Invalid CloudEvent: missing required fields");
1254
- }
1255
- if (body.type !== CLOUD_EVENT_TYPE_V1BETA) {
1256
- throw new Error(
1257
- `Invalid CloudEvent type: expected '${CLOUD_EVENT_TYPE_V1BETA}', got '${String(body.type)}'`
1258
- );
1259
- }
1260
- const { data } = body;
1261
- const missingFields = [];
1262
- if (!("queueName" in data)) missingFields.push("queueName");
1263
- if (!("consumerGroup" in data)) missingFields.push("consumerGroup");
1264
- if (!("messageId" in data)) missingFields.push("messageId");
1265
- if (missingFields.length > 0) {
1266
- throw new Error(
1267
- `Missing required CloudEvent data fields: ${missingFields.join(", ")}`
1268
- );
1269
- }
1270
- return {
1271
- queueName: String(data.queueName),
1272
- consumerGroup: String(data.consumerGroup),
1273
- messageId: String(data.messageId)
1274
- };
1275
- }
1276
- function getHeader(headers, name) {
1277
- if (headers instanceof Headers) {
1278
- return headers.get(name);
1279
- }
1280
- const value = headers[name];
1281
- if (Array.isArray(value)) return value[0] ?? null;
1282
- return value ?? null;
1283
- }
1284
- function parseBinaryHeaders(headers) {
1285
- const ceType = getHeader(headers, "ce-type");
1286
- if (ceType !== CLOUD_EVENT_TYPE_V2BETA) {
1287
- throw new Error(
1288
- `Invalid CloudEvent type: expected '${CLOUD_EVENT_TYPE_V2BETA}', got '${ceType}'`
1289
- );
1290
- }
1291
- const queueName = getHeader(headers, "ce-vqsqueuename");
1292
- const consumerGroup = getHeader(headers, "ce-vqsconsumergroup");
1293
- const messageId = getHeader(headers, "ce-vqsmessageid");
1294
- const missingFields = [];
1295
- if (!queueName) missingFields.push("ce-vqsqueuename");
1296
- if (!consumerGroup) missingFields.push("ce-vqsconsumergroup");
1297
- if (!messageId) missingFields.push("ce-vqsmessageid");
1298
- if (missingFields.length > 0) {
1299
- throw new Error(
1300
- `Missing required CloudEvent headers: ${missingFields.join(", ")}`
1301
- );
1302
- }
1303
- const base = {
1304
- queueName,
1305
- consumerGroup,
1306
- messageId
1307
- };
1308
- const receiptHandle = getHeader(headers, "ce-vqsreceipthandle");
1309
- if (!receiptHandle) {
1310
- return base;
1311
- }
1312
- const result = { ...base, receiptHandle };
1313
- const deliveryCount = getHeader(headers, "ce-vqsdeliverycount");
1314
- if (deliveryCount) {
1315
- result.deliveryCount = parseInt(deliveryCount, 10);
1316
- }
1317
- const createdAt = getHeader(headers, "ce-vqscreatedat");
1318
- if (createdAt) {
1319
- result.createdAt = createdAt;
1320
- }
1321
- const contentType = getHeader(headers, "content-type");
1322
- if (contentType) {
1323
- result.contentType = contentType;
1324
- }
1325
- const visibilityDeadline = getHeader(headers, "ce-vqsvisibilitydeadline");
1326
- if (visibilityDeadline) {
1327
- result.visibilityDeadline = visibilityDeadline;
1328
- }
1329
- return result;
1330
- }
1331
- function parseRawCallback(body, headers) {
1332
- const ceType = getHeader(headers, "ce-type");
1333
- if (ceType === CLOUD_EVENT_TYPE_V2BETA) {
1334
- const result = parseBinaryHeaders(headers);
1335
- if ("receiptHandle" in result) {
1336
- result.parsedPayload = body;
1337
- }
1338
- return result;
1339
- }
1340
- return parseV1StructuredBody(body, getHeader(headers, "content-type"));
1341
- }
1342
- async function handleCallback(handler, request, options) {
1343
- const { queueName, consumerGroup, messageId } = request;
1344
- const client = options?.client || new QueueClient();
1345
- const topic = new Topic(client, queueName);
1346
- const cg = topic.consumerGroup(
1347
- consumerGroup,
1348
- options?.visibilityTimeoutSeconds !== void 0 ? { visibilityTimeoutSeconds: options.visibilityTimeoutSeconds } : void 0
1349
- );
1350
- if ("receiptHandle" in request) {
1351
- const transport = client.getTransport();
1352
- let payload;
1353
- if (request.rawBody) {
1354
- payload = await transport.deserialize(request.rawBody);
1355
- } else if (request.parsedPayload !== void 0) {
1356
- payload = request.parsedPayload;
1357
- } else {
1358
- throw new Error(
1359
- "Binary mode callback with receipt handle is missing payload"
1360
- );
1361
- }
1362
- const message = {
1363
- messageId,
1364
- payload,
1365
- deliveryCount: request.deliveryCount ?? 1,
1366
- createdAt: request.createdAt ? new Date(request.createdAt) : /* @__PURE__ */ new Date(),
1367
- contentType: request.contentType ?? transport.contentType,
1368
- receiptHandle: request.receiptHandle
1369
- };
1370
- const visibilityDeadline = request.visibilityDeadline ? new Date(request.visibilityDeadline) : void 0;
1371
- await cg.consumeMessage(handler, message, { visibilityDeadline });
1372
- } else {
1373
- await cg.consume(handler, { messageId });
1374
- }
1375
- }
1376
-
1377
- // src/nextjs-pages.ts
1378
- function handleCallback2(handler, options) {
1379
- return async (req, res) => {
1380
- if (req.method !== "POST") {
1381
- res.status(200).end();
1382
- return;
1383
- }
1384
- try {
1385
- const parsed = parseRawCallback(req.body, req.headers);
1386
- await handleCallback(handler, parsed, options);
1387
- res.status(200).json({ status: "success" });
1388
- } catch (error) {
1389
- console.error("Queue callback error:", error);
1390
- if (error instanceof Error && (error.message.includes("Invalid content type") || error.message.includes("Invalid CloudEvent") || error.message.includes("Missing required CloudEvent") || error.message.includes("Failed to parse CloudEvent") || error.message.includes("Binary mode callback"))) {
1391
- res.status(400).json({ error: error.message });
1392
- return;
1393
- }
1394
- res.status(500).json({ error: "Failed to process queue message" });
1395
- }
1396
- };
1397
- }
1398
- export {
1399
- handleCallback2 as handleCallback
1400
- };
1401
- //# sourceMappingURL=nextjs-pages.mjs.map