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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/pages.js ADDED
@@ -0,0 +1,1250 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/pages.ts
21
+ var pages_exports = {};
22
+ __export(pages_exports, {
23
+ handleCallback: () => handleCallback2
24
+ });
25
+ module.exports = __toCommonJS(pages_exports);
26
+
27
+ // src/client.ts
28
+ var import_mixpart = require("mixpart");
29
+
30
+ // src/oidc.ts
31
+ var import_oidc = require("@vercel/oidc");
32
+
33
+ // src/types.ts
34
+ var MessageNotFoundError = class extends Error {
35
+ constructor(messageId) {
36
+ super(`Message ${messageId} not found`);
37
+ this.name = "MessageNotFoundError";
38
+ }
39
+ };
40
+ var MessageNotAvailableError = class extends Error {
41
+ constructor(messageId, reason) {
42
+ super(
43
+ `Message ${messageId} not available for processing${reason ? `: ${reason}` : ""}`
44
+ );
45
+ this.name = "MessageNotAvailableError";
46
+ }
47
+ };
48
+ var MessageCorruptedError = class extends Error {
49
+ constructor(messageId, reason) {
50
+ super(`Message ${messageId} is corrupted: ${reason}`);
51
+ this.name = "MessageCorruptedError";
52
+ }
53
+ };
54
+ var QueueEmptyError = class extends Error {
55
+ constructor(queueName, consumerGroup) {
56
+ super(
57
+ `No messages available in queue "${queueName}" for consumer group "${consumerGroup}"`
58
+ );
59
+ this.name = "QueueEmptyError";
60
+ }
61
+ };
62
+ var MessageLockedError = class extends Error {
63
+ retryAfter;
64
+ constructor(messageId, retryAfter) {
65
+ const retryMessage = retryAfter ? ` Retry after ${retryAfter} seconds.` : " Try again later.";
66
+ super(`Message ${messageId} is temporarily locked.${retryMessage}`);
67
+ this.name = "MessageLockedError";
68
+ this.retryAfter = retryAfter;
69
+ }
70
+ };
71
+ var UnauthorizedError = class extends Error {
72
+ constructor(message = "Missing or invalid authentication token") {
73
+ super(message);
74
+ this.name = "UnauthorizedError";
75
+ }
76
+ };
77
+ var ForbiddenError = class extends Error {
78
+ constructor(message = "Queue environment doesn't match token environment") {
79
+ super(message);
80
+ this.name = "ForbiddenError";
81
+ }
82
+ };
83
+ var BadRequestError = class extends Error {
84
+ constructor(message) {
85
+ super(message);
86
+ this.name = "BadRequestError";
87
+ }
88
+ };
89
+ var InternalServerError = class extends Error {
90
+ constructor(message = "Unexpected server error") {
91
+ super(message);
92
+ this.name = "InternalServerError";
93
+ }
94
+ };
95
+ var InvalidLimitError = class extends Error {
96
+ constructor(limit, min = 1, max = 10) {
97
+ super(`Invalid limit: ${limit}. Limit must be between ${min} and ${max}.`);
98
+ this.name = "InvalidLimitError";
99
+ }
100
+ };
101
+
102
+ // src/client.ts
103
+ async function consumeStream(stream) {
104
+ const reader = stream.getReader();
105
+ try {
106
+ while (true) {
107
+ const { done } = await reader.read();
108
+ if (done) break;
109
+ }
110
+ } finally {
111
+ reader.releaseLock();
112
+ }
113
+ }
114
+ function parseQueueHeaders(headers) {
115
+ const messageId = headers.get("Vqs-Message-Id");
116
+ const deliveryCountStr = headers.get("Vqs-Delivery-Count") || "0";
117
+ const timestamp = headers.get("Vqs-Timestamp");
118
+ const contentType = headers.get("Content-Type") || "application/octet-stream";
119
+ const ticket = headers.get("Vqs-Ticket");
120
+ if (!messageId || !timestamp || !ticket) {
121
+ return null;
122
+ }
123
+ const deliveryCount = parseInt(deliveryCountStr, 10);
124
+ if (isNaN(deliveryCount)) {
125
+ return null;
126
+ }
127
+ return {
128
+ messageId,
129
+ deliveryCount,
130
+ createdAt: new Date(timestamp),
131
+ contentType,
132
+ ticket
133
+ };
134
+ }
135
+ var QueueClient = class {
136
+ baseUrl;
137
+ basePath;
138
+ customHeaders = {};
139
+ /**
140
+ * Create a new Vercel Queue Service client
141
+ * @param options Client configuration options
142
+ */
143
+ constructor(options = {}) {
144
+ this.baseUrl = options.baseUrl || process.env.VERCEL_QUEUE_BASE_URL || "https://vercel-queue.com";
145
+ this.basePath = options.basePath || process.env.VERCEL_QUEUE_BASE_PATH || "/api/v2/messages";
146
+ const VERCEL_QUEUE_HEADER_PREFIX = "VERCEL_QUEUE_HEADER_";
147
+ this.customHeaders = Object.fromEntries(
148
+ Object.entries(process.env).filter(([key]) => key.startsWith(VERCEL_QUEUE_HEADER_PREFIX)).map(([key, value]) => [
149
+ // This allows headers to use dashes independent of shell used
150
+ key.replace(VERCEL_QUEUE_HEADER_PREFIX, "").replaceAll("__", "-"),
151
+ value || ""
152
+ ])
153
+ );
154
+ }
155
+ async getToken() {
156
+ const token = await (0, import_oidc.getVercelOidcToken)();
157
+ if (!token) {
158
+ throw new Error(
159
+ "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'"
160
+ );
161
+ }
162
+ return token;
163
+ }
164
+ /**
165
+ * Send a message to a queue
166
+ * @param options Send message options
167
+ * @param transport Serializer/deserializer for the payload
168
+ * @returns Promise with the message ID
169
+ * @throws {BadRequestError} When request parameters are invalid
170
+ * @throws {UnauthorizedError} When authentication fails
171
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
172
+ * @throws {InternalServerError} When server encounters an error
173
+ */
174
+ async sendMessage(options, transport) {
175
+ const { queueName, payload, idempotencyKey, retentionSeconds } = options;
176
+ const headers = new Headers({
177
+ Authorization: `Bearer ${await this.getToken()}`,
178
+ "Vqs-Queue-Name": queueName,
179
+ "Content-Type": transport.contentType,
180
+ ...this.customHeaders
181
+ });
182
+ const deploymentId = options.deploymentId || process.env.VERCEL_DEPLOYMENT_ID;
183
+ if (deploymentId) {
184
+ headers.set("Vqs-Deployment-Id", deploymentId);
185
+ }
186
+ if (idempotencyKey) {
187
+ headers.set("Vqs-Idempotency-Key", idempotencyKey);
188
+ }
189
+ if (retentionSeconds !== void 0) {
190
+ headers.set("Vqs-Retention-Seconds", retentionSeconds.toString());
191
+ }
192
+ const body = transport.serialize(payload);
193
+ const response = await fetch(`${this.baseUrl}${this.basePath}`, {
194
+ method: "POST",
195
+ body,
196
+ headers
197
+ });
198
+ if (!response.ok) {
199
+ if (response.status === 400) {
200
+ const errorText = await response.text();
201
+ throw new BadRequestError(errorText || "Invalid parameters");
202
+ }
203
+ if (response.status === 401) {
204
+ throw new UnauthorizedError();
205
+ }
206
+ if (response.status === 403) {
207
+ throw new ForbiddenError();
208
+ }
209
+ if (response.status === 409) {
210
+ throw new Error("Duplicate idempotency key detected");
211
+ }
212
+ if (response.status >= 500) {
213
+ throw new InternalServerError(
214
+ `Server error: ${response.status} ${response.statusText}`
215
+ );
216
+ }
217
+ throw new Error(
218
+ `Failed to send message: ${response.status} ${response.statusText}`
219
+ );
220
+ }
221
+ const responseData = await response.json();
222
+ return responseData;
223
+ }
224
+ /**
225
+ * Receive messages from a queue
226
+ * @param options Receive messages options
227
+ * @param transport Serializer/deserializer for the payload
228
+ * @returns AsyncGenerator that yields messages as they arrive
229
+ * @throws {InvalidLimitError} When limit parameter is not between 1 and 10
230
+ * @throws {QueueEmptyError} When no messages are available (204)
231
+ * @throws {MessageLockedError} When messages are temporarily locked (423)
232
+ * @throws {BadRequestError} When request parameters are invalid
233
+ * @throws {UnauthorizedError} When authentication fails
234
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
235
+ * @throws {InternalServerError} When server encounters an error
236
+ */
237
+ async *receiveMessages(options, transport) {
238
+ const { queueName, consumerGroup, visibilityTimeoutSeconds, limit } = options;
239
+ if (limit !== void 0 && (limit < 1 || limit > 10)) {
240
+ throw new InvalidLimitError(limit);
241
+ }
242
+ const headers = new Headers({
243
+ Authorization: `Bearer ${await this.getToken()}`,
244
+ "Vqs-Queue-Name": queueName,
245
+ "Vqs-Consumer-Group": consumerGroup,
246
+ Accept: "multipart/mixed",
247
+ ...this.customHeaders
248
+ });
249
+ if (visibilityTimeoutSeconds !== void 0) {
250
+ headers.set(
251
+ "Vqs-Visibility-Timeout",
252
+ visibilityTimeoutSeconds.toString()
253
+ );
254
+ }
255
+ if (limit !== void 0) {
256
+ headers.set("Vqs-Limit", limit.toString());
257
+ }
258
+ const response = await fetch(`${this.baseUrl}${this.basePath}`, {
259
+ method: "GET",
260
+ headers
261
+ });
262
+ if (response.status === 204) {
263
+ throw new QueueEmptyError(queueName, consumerGroup);
264
+ }
265
+ if (!response.ok) {
266
+ if (response.status === 400) {
267
+ const errorText = await response.text();
268
+ throw new BadRequestError(errorText || "Invalid parameters");
269
+ }
270
+ if (response.status === 401) {
271
+ throw new UnauthorizedError();
272
+ }
273
+ if (response.status === 403) {
274
+ throw new ForbiddenError();
275
+ }
276
+ if (response.status === 423) {
277
+ const retryAfterHeader = response.headers.get("Retry-After");
278
+ let retryAfter;
279
+ if (retryAfterHeader) {
280
+ const parsed = parseInt(retryAfterHeader, 10);
281
+ retryAfter = isNaN(parsed) ? void 0 : parsed;
282
+ }
283
+ throw new MessageLockedError("next message", retryAfter);
284
+ }
285
+ if (response.status >= 500) {
286
+ throw new InternalServerError(
287
+ `Server error: ${response.status} ${response.statusText}`
288
+ );
289
+ }
290
+ throw new Error(
291
+ `Failed to receive messages: ${response.status} ${response.statusText}`
292
+ );
293
+ }
294
+ for await (const multipartMessage of (0, import_mixpart.parseMultipartStream)(response)) {
295
+ try {
296
+ const parsedHeaders = parseQueueHeaders(multipartMessage.headers);
297
+ if (!parsedHeaders) {
298
+ console.warn("Missing required queue headers in multipart part");
299
+ await consumeStream(multipartMessage.payload);
300
+ continue;
301
+ }
302
+ const deserializedPayload = await transport.deserialize(
303
+ multipartMessage.payload
304
+ );
305
+ const message = {
306
+ ...parsedHeaders,
307
+ payload: deserializedPayload
308
+ };
309
+ yield message;
310
+ } catch (error) {
311
+ console.warn("Failed to process multipart message:", error);
312
+ await consumeStream(multipartMessage.payload);
313
+ }
314
+ }
315
+ }
316
+ async receiveMessageById(options, transport) {
317
+ const {
318
+ queueName,
319
+ consumerGroup,
320
+ messageId,
321
+ visibilityTimeoutSeconds,
322
+ skipPayload
323
+ } = options;
324
+ const headers = new Headers({
325
+ Authorization: `Bearer ${await this.getToken()}`,
326
+ "Vqs-Queue-Name": queueName,
327
+ "Vqs-Consumer-Group": consumerGroup,
328
+ Accept: "multipart/mixed",
329
+ ...this.customHeaders
330
+ });
331
+ if (visibilityTimeoutSeconds !== void 0) {
332
+ headers.set(
333
+ "Vqs-Visibility-Timeout",
334
+ visibilityTimeoutSeconds.toString()
335
+ );
336
+ }
337
+ if (skipPayload) {
338
+ headers.set("Vqs-Skip-Payload", "1");
339
+ }
340
+ const response = await fetch(
341
+ `${this.baseUrl}${this.basePath}/${encodeURIComponent(messageId)}`,
342
+ {
343
+ method: "GET",
344
+ headers
345
+ }
346
+ );
347
+ if (!response.ok) {
348
+ if (response.status === 400) {
349
+ const errorText = await response.text();
350
+ throw new BadRequestError(errorText || "Invalid parameters");
351
+ }
352
+ if (response.status === 401) {
353
+ throw new UnauthorizedError();
354
+ }
355
+ if (response.status === 403) {
356
+ throw new ForbiddenError();
357
+ }
358
+ if (response.status === 404) {
359
+ throw new MessageNotFoundError(messageId);
360
+ }
361
+ if (response.status === 423) {
362
+ const retryAfterHeader = response.headers.get("Retry-After");
363
+ let retryAfter;
364
+ if (retryAfterHeader) {
365
+ const parsed = parseInt(retryAfterHeader, 10);
366
+ retryAfter = isNaN(parsed) ? void 0 : parsed;
367
+ }
368
+ throw new MessageLockedError(messageId, retryAfter);
369
+ }
370
+ if (response.status === 409) {
371
+ throw new MessageNotAvailableError(messageId);
372
+ }
373
+ if (response.status >= 500) {
374
+ throw new InternalServerError(
375
+ `Server error: ${response.status} ${response.statusText}`
376
+ );
377
+ }
378
+ throw new Error(
379
+ `Failed to receive message by ID: ${response.status} ${response.statusText}`
380
+ );
381
+ }
382
+ if (skipPayload && response.status === 204) {
383
+ const parsedHeaders = parseQueueHeaders(response.headers);
384
+ if (!parsedHeaders) {
385
+ throw new MessageCorruptedError(
386
+ messageId,
387
+ "Missing required queue headers in 204 response"
388
+ );
389
+ }
390
+ const message = {
391
+ ...parsedHeaders,
392
+ payload: void 0
393
+ };
394
+ return { message };
395
+ }
396
+ if (!transport) {
397
+ throw new Error("Transport is required when skipPayload is not true");
398
+ }
399
+ try {
400
+ for await (const multipartMessage of (0, import_mixpart.parseMultipartStream)(response)) {
401
+ try {
402
+ const parsedHeaders = parseQueueHeaders(multipartMessage.headers);
403
+ if (!parsedHeaders) {
404
+ console.warn("Missing required queue headers in multipart part");
405
+ await consumeStream(multipartMessage.payload);
406
+ continue;
407
+ }
408
+ const deserializedPayload = await transport.deserialize(
409
+ multipartMessage.payload
410
+ );
411
+ const message = {
412
+ ...parsedHeaders,
413
+ payload: deserializedPayload
414
+ };
415
+ return { message };
416
+ } catch (error) {
417
+ console.warn("Failed to deserialize message by ID:", error);
418
+ await consumeStream(multipartMessage.payload);
419
+ throw new MessageCorruptedError(
420
+ messageId,
421
+ `Failed to deserialize payload: ${error}`
422
+ );
423
+ }
424
+ }
425
+ } catch (error) {
426
+ if (error instanceof MessageCorruptedError) {
427
+ throw error;
428
+ }
429
+ throw new MessageCorruptedError(
430
+ messageId,
431
+ `Failed to parse multipart response: ${error}`
432
+ );
433
+ }
434
+ throw new MessageNotFoundError(messageId);
435
+ }
436
+ /**
437
+ * Delete a message (acknowledge processing)
438
+ * @param options Delete message options
439
+ * @returns Promise with delete status
440
+ * @throws {MessageNotFoundError} When the message doesn't exist (404)
441
+ * @throws {MessageNotAvailableError} When message can't be deleted (409)
442
+ * @throws {BadRequestError} When ticket is missing or invalid (400)
443
+ * @throws {UnauthorizedError} When authentication fails
444
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
445
+ * @throws {InternalServerError} When server encounters an error
446
+ */
447
+ async deleteMessage(options) {
448
+ const { queueName, consumerGroup, messageId, ticket } = options;
449
+ const response = await fetch(
450
+ `${this.baseUrl}${this.basePath}/${encodeURIComponent(messageId)}`,
451
+ {
452
+ method: "DELETE",
453
+ headers: new Headers({
454
+ Authorization: `Bearer ${await this.getToken()}`,
455
+ "Vqs-Queue-Name": queueName,
456
+ "Vqs-Consumer-Group": consumerGroup,
457
+ "Vqs-Ticket": ticket,
458
+ ...this.customHeaders
459
+ })
460
+ }
461
+ );
462
+ if (!response.ok) {
463
+ if (response.status === 400) {
464
+ throw new BadRequestError("Missing or invalid ticket");
465
+ }
466
+ if (response.status === 401) {
467
+ throw new UnauthorizedError();
468
+ }
469
+ if (response.status === 403) {
470
+ throw new ForbiddenError();
471
+ }
472
+ if (response.status === 404) {
473
+ throw new MessageNotFoundError(messageId);
474
+ }
475
+ if (response.status === 409) {
476
+ throw new MessageNotAvailableError(
477
+ messageId,
478
+ "Invalid ticket, message not in correct state, or already processed"
479
+ );
480
+ }
481
+ if (response.status >= 500) {
482
+ throw new InternalServerError(
483
+ `Server error: ${response.status} ${response.statusText}`
484
+ );
485
+ }
486
+ throw new Error(
487
+ `Failed to delete message: ${response.status} ${response.statusText}`
488
+ );
489
+ }
490
+ return { deleted: true };
491
+ }
492
+ /**
493
+ * Change the visibility timeout of a message
494
+ * @param options Change visibility options
495
+ * @returns Promise with update status
496
+ * @throws {MessageNotFoundError} When the message doesn't exist (404)
497
+ * @throws {MessageNotAvailableError} When message can't be updated (409)
498
+ * @throws {BadRequestError} When ticket is missing or visibility timeout invalid (400)
499
+ * @throws {UnauthorizedError} When authentication fails
500
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
501
+ * @throws {InternalServerError} When server encounters an error
502
+ */
503
+ async changeVisibility(options) {
504
+ const {
505
+ queueName,
506
+ consumerGroup,
507
+ messageId,
508
+ ticket,
509
+ visibilityTimeoutSeconds
510
+ } = options;
511
+ const response = await fetch(
512
+ `${this.baseUrl}${this.basePath}/${encodeURIComponent(messageId)}`,
513
+ {
514
+ method: "PATCH",
515
+ headers: new Headers({
516
+ Authorization: `Bearer ${await this.getToken()}`,
517
+ "Vqs-Queue-Name": queueName,
518
+ "Vqs-Consumer-Group": consumerGroup,
519
+ "Vqs-Ticket": ticket,
520
+ "Vqs-Visibility-Timeout": visibilityTimeoutSeconds.toString(),
521
+ ...this.customHeaders
522
+ })
523
+ }
524
+ );
525
+ if (!response.ok) {
526
+ if (response.status === 400) {
527
+ throw new BadRequestError(
528
+ "Missing ticket or invalid visibility timeout"
529
+ );
530
+ }
531
+ if (response.status === 401) {
532
+ throw new UnauthorizedError();
533
+ }
534
+ if (response.status === 403) {
535
+ throw new ForbiddenError();
536
+ }
537
+ if (response.status === 404) {
538
+ throw new MessageNotFoundError(messageId);
539
+ }
540
+ if (response.status === 409) {
541
+ throw new MessageNotAvailableError(
542
+ messageId,
543
+ "Invalid ticket, message not in correct state, or already processed"
544
+ );
545
+ }
546
+ if (response.status >= 500) {
547
+ throw new InternalServerError(
548
+ `Server error: ${response.status} ${response.statusText}`
549
+ );
550
+ }
551
+ throw new Error(
552
+ `Failed to change visibility: ${response.status} ${response.statusText}`
553
+ );
554
+ }
555
+ return { updated: true };
556
+ }
557
+ };
558
+
559
+ // src/transports.ts
560
+ async function streamToBuffer(stream) {
561
+ let totalLength = 0;
562
+ const reader = stream.getReader();
563
+ const chunks = [];
564
+ try {
565
+ while (true) {
566
+ const { done, value } = await reader.read();
567
+ if (done) break;
568
+ chunks.push(value);
569
+ totalLength += value.length;
570
+ }
571
+ } finally {
572
+ reader.releaseLock();
573
+ }
574
+ return Buffer.concat(chunks, totalLength);
575
+ }
576
+ var JsonTransport = class {
577
+ contentType = "application/json";
578
+ replacer;
579
+ reviver;
580
+ constructor(options = {}) {
581
+ this.replacer = options.replacer;
582
+ this.reviver = options.reviver;
583
+ }
584
+ serialize(value) {
585
+ return Buffer.from(JSON.stringify(value, this.replacer), "utf8");
586
+ }
587
+ async deserialize(stream) {
588
+ const buffer = await streamToBuffer(stream);
589
+ return JSON.parse(buffer.toString("utf8"), this.reviver);
590
+ }
591
+ };
592
+
593
+ // src/dev.ts
594
+ var devRouteHandlers = /* @__PURE__ */ new Map();
595
+ var wildcardRouteHandlers = /* @__PURE__ */ new Map();
596
+ function cleanupDeadRefs(key, refs) {
597
+ const aliveRefs = refs.filter((ref) => ref.deref() !== void 0);
598
+ if (aliveRefs.length === 0) {
599
+ wildcardRouteHandlers.delete(key);
600
+ } else if (aliveRefs.length < refs.length) {
601
+ wildcardRouteHandlers.set(key, aliveRefs);
602
+ }
603
+ }
604
+ function isDevMode() {
605
+ return process.env.NODE_ENV === "development";
606
+ }
607
+ function registerDevRouteHandler(routeHandler, handlers) {
608
+ for (const topicName in handlers) {
609
+ for (const consumerGroup in handlers[topicName]) {
610
+ const key = `${topicName}:${consumerGroup}`;
611
+ if (topicName.includes("*")) {
612
+ const existing = wildcardRouteHandlers.get(key) || [];
613
+ cleanupDeadRefs(key, existing);
614
+ const cleanedRefs = wildcardRouteHandlers.get(key) || [];
615
+ const weakRef = new WeakRef(routeHandler);
616
+ cleanedRefs.push(weakRef);
617
+ wildcardRouteHandlers.set(key, cleanedRefs);
618
+ } else {
619
+ devRouteHandlers.set(key, {
620
+ routeHandler,
621
+ topicPattern: topicName
622
+ });
623
+ }
624
+ }
625
+ }
626
+ }
627
+ function findRouteHandlersForTopic(topicName) {
628
+ const handlersMap = /* @__PURE__ */ new Map();
629
+ for (const [
630
+ key,
631
+ { routeHandler, topicPattern }
632
+ ] of devRouteHandlers.entries()) {
633
+ const [_, consumerGroup] = key.split(":");
634
+ if (topicPattern === topicName) {
635
+ if (!handlersMap.has(routeHandler)) {
636
+ handlersMap.set(routeHandler, /* @__PURE__ */ new Set());
637
+ }
638
+ handlersMap.get(routeHandler).add(consumerGroup);
639
+ }
640
+ }
641
+ for (const [key, refs] of wildcardRouteHandlers.entries()) {
642
+ const [pattern, consumerGroup] = key.split(":");
643
+ if (matchesWildcardPattern(topicName, pattern)) {
644
+ cleanupDeadRefs(key, refs);
645
+ const cleanedRefs = wildcardRouteHandlers.get(key) || [];
646
+ for (const ref of cleanedRefs) {
647
+ const routeHandler = ref.deref();
648
+ if (routeHandler) {
649
+ if (!handlersMap.has(routeHandler)) {
650
+ handlersMap.set(routeHandler, /* @__PURE__ */ new Set());
651
+ }
652
+ handlersMap.get(routeHandler).add(consumerGroup);
653
+ }
654
+ }
655
+ }
656
+ }
657
+ return handlersMap;
658
+ }
659
+ function createMockCloudEventRequest(topicName, consumerGroup, messageId) {
660
+ const cloudEvent = {
661
+ type: "com.vercel.queue.v1beta",
662
+ source: `/topic/${topicName}/consumer/${consumerGroup}`,
663
+ id: messageId,
664
+ datacontenttype: "application/json",
665
+ data: {
666
+ messageId,
667
+ queueName: topicName,
668
+ consumerGroup
669
+ },
670
+ time: (/* @__PURE__ */ new Date()).toISOString(),
671
+ specversion: "1.0"
672
+ };
673
+ return new Request("https://localhost/api/queue/callback", {
674
+ method: "POST",
675
+ headers: {
676
+ "Content-Type": "application/cloudevents+json"
677
+ },
678
+ body: JSON.stringify(cloudEvent)
679
+ });
680
+ }
681
+ var DEV_CALLBACK_DELAY = 1e3;
682
+ function scheduleDevTimeout(topicName, messageId, timeoutSeconds) {
683
+ console.log(
684
+ `[Dev Mode] Message ${messageId} timed out for ${timeoutSeconds}s, will re-trigger`
685
+ );
686
+ setTimeout(
687
+ () => {
688
+ console.log(
689
+ `[Dev Mode] Re-triggering callback for timed-out message ${messageId}`
690
+ );
691
+ triggerDevCallbacks(topicName, messageId);
692
+ },
693
+ timeoutSeconds * 1e3 + DEV_CALLBACK_DELAY
694
+ );
695
+ }
696
+ function triggerDevCallbacks(topicName, messageId) {
697
+ const handlersMap = findRouteHandlersForTopic(topicName);
698
+ if (handlersMap.size === 0) {
699
+ return;
700
+ }
701
+ const consumerGroups = Array.from(
702
+ new Set(
703
+ Array.from(handlersMap.values()).flatMap((groups) => Array.from(groups))
704
+ )
705
+ );
706
+ console.log(
707
+ `[Dev Mode] Triggering local callbacks for topic "${topicName}" \u2192 consumers: ${consumerGroups.join(", ")}`
708
+ );
709
+ setTimeout(async () => {
710
+ for (const [routeHandler, consumerGroups2] of handlersMap.entries()) {
711
+ for (const consumerGroup of consumerGroups2) {
712
+ try {
713
+ const request = createMockCloudEventRequest(
714
+ topicName,
715
+ consumerGroup,
716
+ messageId
717
+ );
718
+ const response = await routeHandler(request);
719
+ if (response.ok) {
720
+ try {
721
+ const responseData = await response.json();
722
+ if (responseData.status === "success") {
723
+ console.log(
724
+ `[Dev Mode] Message processed for ${topicName}/${consumerGroup}`
725
+ );
726
+ }
727
+ } catch (jsonError) {
728
+ console.error(
729
+ `[Dev Mode] Failed to parse success response for ${topicName}/${consumerGroup}:`,
730
+ jsonError
731
+ );
732
+ }
733
+ } else {
734
+ try {
735
+ const errorData = await response.json();
736
+ console.error(
737
+ `[Dev Mode] Failed to process message for ${topicName}/${consumerGroup}:`,
738
+ errorData.error || response.statusText
739
+ );
740
+ } catch (jsonError) {
741
+ console.error(
742
+ `[Dev Mode] Failed to process message for ${topicName}/${consumerGroup}:`,
743
+ response.statusText
744
+ );
745
+ }
746
+ }
747
+ } catch (error) {
748
+ console.error(
749
+ `[Dev Mode] Error triggering callback for ${topicName}/${consumerGroup}:`,
750
+ error
751
+ );
752
+ }
753
+ }
754
+ }
755
+ }, DEV_CALLBACK_DELAY);
756
+ }
757
+ function clearDevHandlers() {
758
+ devRouteHandlers.clear();
759
+ wildcardRouteHandlers.clear();
760
+ }
761
+ if (process.env.NODE_ENV === "test" || process.env.VITEST) {
762
+ globalThis.__clearDevHandlers = clearDevHandlers;
763
+ }
764
+
765
+ // src/consumer-group.ts
766
+ var ConsumerGroup = class {
767
+ client;
768
+ topicName;
769
+ consumerGroupName;
770
+ visibilityTimeout;
771
+ refreshInterval;
772
+ transport;
773
+ /**
774
+ * Create a new ConsumerGroup instance
775
+ * @param client QueueClient instance to use for API calls
776
+ * @param topicName Name of the topic to consume from
777
+ * @param consumerGroupName Name of the consumer group
778
+ * @param options Optional configuration
779
+ */
780
+ constructor(client, topicName, consumerGroupName, options = {}) {
781
+ this.client = client;
782
+ this.topicName = topicName;
783
+ this.consumerGroupName = consumerGroupName;
784
+ this.visibilityTimeout = options.visibilityTimeoutSeconds || 30;
785
+ this.refreshInterval = options.refreshInterval || 10;
786
+ this.transport = options.transport || new JsonTransport();
787
+ }
788
+ /**
789
+ * Starts a background loop that periodically extends the visibility timeout for a message.
790
+ * This prevents the message from becoming visible to other consumers while it's being processed.
791
+ *
792
+ * The extension loop runs every `refreshInterval` seconds and updates the message's
793
+ * visibility timeout to `visibilityTimeout` seconds from the current time.
794
+ *
795
+ * @param messageId - The unique identifier of the message to extend visibility for
796
+ * @param ticket - The receipt ticket that proves ownership of the message
797
+ * @returns A function that when called will stop the extension loop
798
+ *
799
+ * @remarks
800
+ * - The first extension attempt occurs after `refreshInterval` seconds, not immediately
801
+ * - If an extension fails, the loop terminates with an error logged to console
802
+ * - The returned stop function is idempotent - calling it multiple times is safe
803
+ * - By default, the stop function returns immediately without waiting for in-flight
804
+ * - Pass `true` to the stop function to wait for any in-flight extension to complete
805
+ */
806
+ startVisibilityExtension(messageId, ticket) {
807
+ let isRunning = true;
808
+ let resolveLifecycle;
809
+ let timeoutId = null;
810
+ const lifecyclePromise = new Promise((resolve) => {
811
+ resolveLifecycle = resolve;
812
+ });
813
+ const extend = async () => {
814
+ if (!isRunning) {
815
+ resolveLifecycle();
816
+ return;
817
+ }
818
+ try {
819
+ await this.client.changeVisibility({
820
+ queueName: this.topicName,
821
+ consumerGroup: this.consumerGroupName,
822
+ messageId,
823
+ ticket,
824
+ visibilityTimeoutSeconds: this.visibilityTimeout
825
+ });
826
+ if (isRunning) {
827
+ timeoutId = setTimeout(() => extend(), this.refreshInterval * 1e3);
828
+ } else {
829
+ resolveLifecycle();
830
+ }
831
+ } catch (error) {
832
+ console.error(
833
+ `Failed to extend visibility for message ${messageId}:`,
834
+ error
835
+ );
836
+ resolveLifecycle();
837
+ }
838
+ };
839
+ timeoutId = setTimeout(() => extend(), this.refreshInterval * 1e3);
840
+ return async (waitForCompletion = false) => {
841
+ isRunning = false;
842
+ if (timeoutId) {
843
+ clearTimeout(timeoutId);
844
+ timeoutId = null;
845
+ }
846
+ if (waitForCompletion) {
847
+ await lifecyclePromise;
848
+ } else {
849
+ resolveLifecycle();
850
+ }
851
+ };
852
+ }
853
+ /**
854
+ * Process a single message with the given handler
855
+ * @param message The message to process
856
+ * @param handler Function to process the message
857
+ */
858
+ async processMessage(message, handler) {
859
+ const stopExtension = this.startVisibilityExtension(
860
+ message.messageId,
861
+ message.ticket
862
+ );
863
+ try {
864
+ const result = await handler(message.payload, {
865
+ messageId: message.messageId,
866
+ deliveryCount: message.deliveryCount,
867
+ createdAt: message.createdAt,
868
+ topicName: this.topicName,
869
+ consumerGroup: this.consumerGroupName
870
+ });
871
+ await stopExtension();
872
+ if (result && "timeoutSeconds" in result) {
873
+ await this.client.changeVisibility({
874
+ queueName: this.topicName,
875
+ consumerGroup: this.consumerGroupName,
876
+ messageId: message.messageId,
877
+ ticket: message.ticket,
878
+ visibilityTimeoutSeconds: result.timeoutSeconds
879
+ });
880
+ if (isDevMode()) {
881
+ scheduleDevTimeout(
882
+ this.topicName,
883
+ message.messageId,
884
+ result.timeoutSeconds
885
+ );
886
+ }
887
+ } else {
888
+ await this.client.deleteMessage({
889
+ queueName: this.topicName,
890
+ consumerGroup: this.consumerGroupName,
891
+ messageId: message.messageId,
892
+ ticket: message.ticket
893
+ });
894
+ }
895
+ } catch (error) {
896
+ await stopExtension();
897
+ if (this.transport.finalize && message.payload !== void 0 && message.payload !== null) {
898
+ try {
899
+ await this.transport.finalize(message.payload);
900
+ } catch (finalizeError) {
901
+ console.warn("Failed to finalize message payload:", finalizeError);
902
+ }
903
+ }
904
+ throw error;
905
+ }
906
+ }
907
+ async consume(handler, options) {
908
+ if (options?.messageId) {
909
+ if (options.skipPayload) {
910
+ const response = await this.client.receiveMessageById(
911
+ {
912
+ queueName: this.topicName,
913
+ consumerGroup: this.consumerGroupName,
914
+ messageId: options.messageId,
915
+ visibilityTimeoutSeconds: this.visibilityTimeout,
916
+ skipPayload: true
917
+ },
918
+ this.transport
919
+ );
920
+ await this.processMessage(
921
+ response.message,
922
+ handler
923
+ );
924
+ } else {
925
+ const response = await this.client.receiveMessageById(
926
+ {
927
+ queueName: this.topicName,
928
+ consumerGroup: this.consumerGroupName,
929
+ messageId: options.messageId,
930
+ visibilityTimeoutSeconds: this.visibilityTimeout
931
+ },
932
+ this.transport
933
+ );
934
+ await this.processMessage(
935
+ response.message,
936
+ handler
937
+ );
938
+ }
939
+ } else {
940
+ let messageFound = false;
941
+ for await (const message of this.client.receiveMessages(
942
+ {
943
+ queueName: this.topicName,
944
+ consumerGroup: this.consumerGroupName,
945
+ visibilityTimeoutSeconds: this.visibilityTimeout,
946
+ limit: 1
947
+ },
948
+ this.transport
949
+ )) {
950
+ messageFound = true;
951
+ await this.processMessage(message, handler);
952
+ break;
953
+ }
954
+ if (!messageFound) {
955
+ throw new Error("No messages available");
956
+ }
957
+ }
958
+ }
959
+ /**
960
+ * Get the consumer group name
961
+ */
962
+ get name() {
963
+ return this.consumerGroupName;
964
+ }
965
+ /**
966
+ * Get the topic name this consumer group is subscribed to
967
+ */
968
+ get topic() {
969
+ return this.topicName;
970
+ }
971
+ };
972
+
973
+ // src/topic.ts
974
+ var Topic = class {
975
+ client;
976
+ topicName;
977
+ transport;
978
+ /**
979
+ * Create a new Topic instance
980
+ * @param client QueueClient instance to use for API calls
981
+ * @param topicName Name of the topic to work with
982
+ * @param transport Optional serializer/deserializer for the payload (defaults to JSON)
983
+ */
984
+ constructor(client, topicName, transport) {
985
+ this.client = client;
986
+ this.topicName = topicName;
987
+ this.transport = transport || new JsonTransport();
988
+ }
989
+ /**
990
+ * Publish a message to the topic
991
+ * @param payload The data to publish
992
+ * @param options Optional publish options
993
+ * @returns An object containing the message ID
994
+ * @throws {BadRequestError} When request parameters are invalid
995
+ * @throws {UnauthorizedError} When authentication fails
996
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
997
+ * @throws {InternalServerError} When server encounters an error
998
+ */
999
+ async publish(payload, options) {
1000
+ const result = await this.client.sendMessage(
1001
+ {
1002
+ queueName: this.topicName,
1003
+ payload,
1004
+ idempotencyKey: options?.idempotencyKey,
1005
+ retentionSeconds: options?.retentionSeconds,
1006
+ deploymentId: options?.deploymentId
1007
+ },
1008
+ this.transport
1009
+ );
1010
+ if (isDevMode()) {
1011
+ triggerDevCallbacks(this.topicName, result.messageId);
1012
+ }
1013
+ return { messageId: result.messageId };
1014
+ }
1015
+ /**
1016
+ * Create a consumer group for this topic
1017
+ * @param consumerGroupName Name of the consumer group
1018
+ * @param options Optional configuration for the consumer group
1019
+ * @returns A ConsumerGroup instance
1020
+ */
1021
+ consumerGroup(consumerGroupName, options) {
1022
+ const consumerOptions = {
1023
+ ...options,
1024
+ transport: options?.transport || this.transport
1025
+ };
1026
+ return new ConsumerGroup(
1027
+ this.client,
1028
+ this.topicName,
1029
+ consumerGroupName,
1030
+ consumerOptions
1031
+ );
1032
+ }
1033
+ /**
1034
+ * Get the topic name
1035
+ */
1036
+ get name() {
1037
+ return this.topicName;
1038
+ }
1039
+ /**
1040
+ * Get the transport used by this topic
1041
+ */
1042
+ get serializer() {
1043
+ return this.transport;
1044
+ }
1045
+ };
1046
+
1047
+ // src/callback.ts
1048
+ function validateWildcardPattern(pattern) {
1049
+ const firstIndex = pattern.indexOf("*");
1050
+ const lastIndex = pattern.lastIndexOf("*");
1051
+ if (firstIndex !== lastIndex) {
1052
+ return false;
1053
+ }
1054
+ if (firstIndex === -1) {
1055
+ return false;
1056
+ }
1057
+ if (firstIndex !== pattern.length - 1) {
1058
+ return false;
1059
+ }
1060
+ return true;
1061
+ }
1062
+ function matchesWildcardPattern(topicName, pattern) {
1063
+ const prefix = pattern.slice(0, -1);
1064
+ return topicName.startsWith(prefix);
1065
+ }
1066
+ function findTopicHandler(queueName, handlers) {
1067
+ const exactHandler = handlers[queueName];
1068
+ if (exactHandler) {
1069
+ return exactHandler;
1070
+ }
1071
+ for (const pattern in handlers) {
1072
+ if (pattern.includes("*") && matchesWildcardPattern(queueName, pattern)) {
1073
+ return handlers[pattern];
1074
+ }
1075
+ }
1076
+ return null;
1077
+ }
1078
+ async function parseCallback(request) {
1079
+ const contentType = request.headers.get("content-type");
1080
+ if (!contentType || !contentType.includes("application/cloudevents+json")) {
1081
+ throw new Error(
1082
+ "Invalid content type: expected 'application/cloudevents+json'"
1083
+ );
1084
+ }
1085
+ let cloudEvent;
1086
+ try {
1087
+ cloudEvent = await request.json();
1088
+ } catch (error) {
1089
+ throw new Error("Failed to parse CloudEvent from request body");
1090
+ }
1091
+ if (!cloudEvent.type || !cloudEvent.source || !cloudEvent.id || typeof cloudEvent.data !== "object" || cloudEvent.data == null) {
1092
+ throw new Error("Invalid CloudEvent: missing required fields");
1093
+ }
1094
+ if (cloudEvent.type !== "com.vercel.queue.v1beta") {
1095
+ throw new Error(
1096
+ `Invalid CloudEvent type: expected 'com.vercel.queue.v1beta', got '${cloudEvent.type}'`
1097
+ );
1098
+ }
1099
+ const missingFields = [];
1100
+ if (!("queueName" in cloudEvent.data)) missingFields.push("queueName");
1101
+ if (!("consumerGroup" in cloudEvent.data))
1102
+ missingFields.push("consumerGroup");
1103
+ if (!("messageId" in cloudEvent.data)) missingFields.push("messageId");
1104
+ if (missingFields.length > 0) {
1105
+ throw new Error(
1106
+ `Missing required CloudEvent data fields: ${missingFields.join(", ")}`
1107
+ );
1108
+ }
1109
+ const { messageId, queueName, consumerGroup } = cloudEvent.data;
1110
+ return {
1111
+ queueName,
1112
+ consumerGroup,
1113
+ messageId
1114
+ };
1115
+ }
1116
+ function handleCallback(handlers) {
1117
+ for (const topicPattern in handlers) {
1118
+ if (topicPattern.includes("*")) {
1119
+ if (!validateWildcardPattern(topicPattern)) {
1120
+ throw new Error(
1121
+ `Invalid wildcard pattern "${topicPattern}": * may only appear once and must be at the end of the topic name`
1122
+ );
1123
+ }
1124
+ }
1125
+ }
1126
+ const routeHandler = async (request) => {
1127
+ try {
1128
+ const { queueName, consumerGroup, messageId } = await parseCallback(request);
1129
+ const topicHandler = findTopicHandler(queueName, handlers);
1130
+ if (!topicHandler) {
1131
+ const availableTopics = Object.keys(handlers).join(", ");
1132
+ return Response.json(
1133
+ {
1134
+ error: `No handler found for topic: ${queueName}`,
1135
+ availableTopics
1136
+ },
1137
+ { status: 404 }
1138
+ );
1139
+ }
1140
+ const consumerGroupHandler = topicHandler[consumerGroup];
1141
+ if (!consumerGroupHandler) {
1142
+ const availableGroups = Object.keys(topicHandler).join(", ");
1143
+ return Response.json(
1144
+ {
1145
+ error: `No handler found for consumer group "${consumerGroup}" in topic "${queueName}".`,
1146
+ availableGroups
1147
+ },
1148
+ { status: 404 }
1149
+ );
1150
+ }
1151
+ const client = new QueueClient();
1152
+ const topic = new Topic(client, queueName);
1153
+ const cg = topic.consumerGroup(consumerGroup);
1154
+ await cg.consume(consumerGroupHandler, { messageId });
1155
+ return Response.json({ status: "success" });
1156
+ } catch (error) {
1157
+ console.error("Queue callback error:", error);
1158
+ if (error instanceof Error && (error.message.includes("Missing required CloudEvent data fields") || error.message.includes("Invalid CloudEvent") || error.message.includes("Invalid CloudEvent type") || error.message.includes("Invalid content type") || error.message.includes("Failed to parse CloudEvent"))) {
1159
+ return Response.json({ error: error.message }, { status: 400 });
1160
+ }
1161
+ return Response.json(
1162
+ { error: "Failed to process queue message" },
1163
+ { status: 500 }
1164
+ );
1165
+ }
1166
+ };
1167
+ if (isDevMode()) {
1168
+ registerDevRouteHandler(routeHandler, handlers);
1169
+ }
1170
+ return routeHandler;
1171
+ }
1172
+
1173
+ // src/pages.ts
1174
+ function getHeader(headers, name) {
1175
+ const value = headers[name];
1176
+ return Array.isArray(value) ? value[0] : value;
1177
+ }
1178
+ function readBody(req) {
1179
+ return new Promise((resolve, reject) => {
1180
+ const chunks = [];
1181
+ req.on("data", (chunk) => chunks.push(chunk));
1182
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
1183
+ req.on("error", reject);
1184
+ });
1185
+ }
1186
+ function getBody(req) {
1187
+ if (req.body === void 0) {
1188
+ return readBody(req);
1189
+ }
1190
+ if (typeof req.body === "string") {
1191
+ return req.body;
1192
+ }
1193
+ return JSON.stringify(req.body);
1194
+ }
1195
+ async function createRequestFromNextApi(req) {
1196
+ const protocol = getHeader(req.headers, "x-forwarded-proto") ?? "https";
1197
+ const host = getHeader(req.headers, "host");
1198
+ if (!host) {
1199
+ throw new Error("Missing host header");
1200
+ }
1201
+ const url = `${protocol}://${host}${req.url}`;
1202
+ const headers = new Headers();
1203
+ for (const [key, value] of Object.entries(req.headers)) {
1204
+ if (value) {
1205
+ if (Array.isArray(value)) {
1206
+ value.forEach((v) => headers.append(key, v));
1207
+ } else {
1208
+ headers.set(key, value);
1209
+ }
1210
+ }
1211
+ }
1212
+ const body = await getBody(req);
1213
+ return new Request(url, {
1214
+ method: req.method || "POST",
1215
+ headers,
1216
+ body
1217
+ });
1218
+ }
1219
+ async function sendResponseToNextApi(response, res) {
1220
+ res.status(response.status);
1221
+ response.headers.forEach((value, key) => {
1222
+ res.setHeader(key, value);
1223
+ });
1224
+ const contentType = response.headers.get("content-type");
1225
+ if (contentType?.includes("application/json")) {
1226
+ const data = await response.json();
1227
+ res.json(data);
1228
+ } else {
1229
+ const text = await response.text();
1230
+ res.send(text);
1231
+ }
1232
+ }
1233
+ function handleCallback2(handlers) {
1234
+ const webHandler = handleCallback(handlers);
1235
+ return async (req, res) => {
1236
+ try {
1237
+ const request = await createRequestFromNextApi(req);
1238
+ const response = await webHandler(request);
1239
+ await sendResponseToNextApi(response, res);
1240
+ } catch (error) {
1241
+ console.error("Pages Router adapter error:", error);
1242
+ res.status(500).json({ error: "Internal server error" });
1243
+ }
1244
+ };
1245
+ }
1246
+ // Annotate the CommonJS export names for ESM import in node:
1247
+ 0 && (module.exports = {
1248
+ handleCallback
1249
+ });
1250
+ //# sourceMappingURL=pages.js.map