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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,90 +1,130 @@
1
- // src/transports.ts
2
- var JsonTransport = class {
3
- contentType = "application/json";
4
- serialize(value) {
5
- return Buffer.from(JSON.stringify(value), "utf8");
6
- }
7
- async deserialize(stream) {
8
- const reader = stream.getReader();
9
- let totalLength = 0;
10
- const chunks = [];
11
- try {
12
- while (true) {
13
- const { done, value } = await reader.read();
14
- if (done) break;
15
- chunks.push(value);
16
- totalLength += value.length;
17
- }
18
- } finally {
19
- reader.releaseLock();
20
- }
21
- const buffer = Buffer.concat(chunks, totalLength);
22
- return JSON.parse(buffer.toString("utf8"));
23
- }
24
- };
25
- var BufferTransport = class {
26
- contentType = "application/octet-stream";
27
- serialize(value) {
28
- return value;
29
- }
30
- async deserialize(stream) {
31
- const reader = stream.getReader();
32
- const chunks = [];
33
- try {
34
- while (true) {
35
- const { done, value } = await reader.read();
36
- if (done) break;
37
- chunks.push(value);
38
- }
39
- } finally {
40
- reader.releaseLock();
41
- }
42
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
43
- const buffer = new Uint8Array(totalLength);
44
- let offset = 0;
45
- for (const chunk of chunks) {
46
- buffer.set(chunk, offset);
47
- offset += chunk.length;
48
- }
49
- return Buffer.from(buffer);
50
- }
51
- };
52
- var StreamTransport = class {
53
- contentType = "application/octet-stream";
54
- serialize(value) {
55
- return value;
56
- }
57
- async deserialize(stream) {
58
- return stream;
59
- }
60
- async finalize(payload) {
61
- const reader = payload.getReader();
62
- try {
63
- while (true) {
64
- const { done } = await reader.read();
65
- if (done) break;
66
- }
67
- } finally {
68
- reader.releaseLock();
69
- }
70
- }
71
- };
72
-
73
- // src/client.ts
74
- import { parseMultipartStream } from "mixpart";
75
-
76
1
  // src/oidc.ts
77
- function getVercelOidcToken() {
2
+ async function getVercelOidcToken() {
78
3
  const SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context");
79
4
  const fromSymbol = globalThis;
80
5
  const context = fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
81
6
  const token = context.headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
82
7
  if (!token) {
83
- return null;
8
+ throw new Error(
9
+ `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
10
+ );
84
11
  }
85
12
  return token;
86
13
  }
87
14
 
15
+ // src/client.ts
16
+ import { parseMultipartStream } from "mixpart";
17
+
18
+ // src/local.ts
19
+ import { spawn } from "child_process";
20
+ function isLocalhostWithPort(url) {
21
+ try {
22
+ const parsedUrl = new URL(url);
23
+ const isLocalhost = parsedUrl.hostname === "localhost";
24
+ const port = parsedUrl.port ? parseInt(parsedUrl.port, 10) : 0;
25
+ return { isLocalhost, port };
26
+ } catch {
27
+ return { isLocalhost: false };
28
+ }
29
+ }
30
+ function isSupportedPlatform() {
31
+ const platform = process.platform;
32
+ return platform === "darwin" || platform === "linux";
33
+ }
34
+ function processDevelopmentCallbacks(callbacks) {
35
+ const isDevelopment = process.env.NODE_ENV === "development";
36
+ if (!isDevelopment) {
37
+ return [];
38
+ }
39
+ if (!isSupportedPlatform()) {
40
+ const hasLocalhostCallbacks = Object.values(callbacks).some((config) => {
41
+ const { isLocalhost } = isLocalhostWithPort(config.url);
42
+ return isLocalhost;
43
+ });
44
+ if (hasLocalhostCallbacks) {
45
+ console.warn(
46
+ `Queue Development Mode: Localhost callbacks are not supported on ${process.platform}. Localhost callback handling requires bash, nc, and curl which are available on macOS and Linux only. Consider using a production callback URL or developing on a supported platform.`
47
+ );
48
+ }
49
+ return [];
50
+ }
51
+ const localhostCallbacks = [];
52
+ Object.entries(callbacks).forEach(([group, config]) => {
53
+ const { isLocalhost, port } = isLocalhostWithPort(config.url);
54
+ if (isLocalhost && port && port > 0) {
55
+ localhostCallbacks.push({ group, config, port });
56
+ } else {
57
+ console.warn(
58
+ `Queue Development Mode: Skipping non-localhost callback for group "${group}": ${config.url}. Only localhost callbacks with explicit ports are supported in development.`
59
+ );
60
+ }
61
+ });
62
+ return localhostCallbacks;
63
+ }
64
+ function fireLocalhostCallbacks(localhostCallbacks, queueName, responseData) {
65
+ localhostCallbacks.forEach(({ group, config, port }) => {
66
+ const callbackHeaders = new Headers();
67
+ callbackHeaders.set("Vqs-Message-Id", responseData.messageId);
68
+ callbackHeaders.set("Vqs-Queue-Name", queueName);
69
+ callbackHeaders.set("Vqs-Consumer-Group", group);
70
+ fireAndForgetWaitForHttpReady(
71
+ config.url,
72
+ port,
73
+ config.delay || 0,
74
+ 3,
75
+ // Default retry frequency
76
+ callbackHeaders
77
+ );
78
+ });
79
+ }
80
+ function fireAndForgetWaitForHttpReady(url, port, initialDelaySeconds = 0, retryFrequencySeconds = 3, headers) {
81
+ if (!isSupportedPlatform()) {
82
+ console.warn(
83
+ `Queue: fireAndForgetWaitForHttpReady is not supported on ${process.platform}. This function requires bash, nc, and curl which are available on macOS and Linux only.`
84
+ );
85
+ return;
86
+ }
87
+ let headerArgs = "";
88
+ if (headers) {
89
+ const headerArray = [];
90
+ headers.forEach((value, key) => {
91
+ headerArray.push(`-H '${key}: ${value}'`);
92
+ });
93
+ headerArgs = headerArray.join(" ");
94
+ }
95
+ const bashScript = `
96
+ # Wait for any initial boot time
97
+ sleep ${initialDelaySeconds}
98
+
99
+ missed=0
100
+ while true; do
101
+ # 1) Check if TCP port is listening
102
+ if nc -z localhost ${port} 2>/dev/null; then
103
+ missed=0
104
+ # 2) If port is open, try HTTP POST check
105
+ if curl -sSL --fail -o /dev/null -X POST ${headerArgs} "${url}"; then
106
+ # Success: port is up AND HTTP returned 2xx (following redirects)
107
+ exit 0
108
+ fi
109
+ else
110
+ # Port was closed\u2014increment miss counter
111
+ ((missed+=1))
112
+ # If closed twice in a row, give up immediately
113
+ if [ "$missed" -ge 2 ]; then
114
+ exit 1
115
+ fi
116
+ fi
117
+ # Wait before next cycle
118
+ sleep ${retryFrequencySeconds}
119
+ done
120
+ `;
121
+ const childProcess = spawn("bash", ["-c", bashScript], {
122
+ stdio: "ignore",
123
+ detached: true
124
+ });
125
+ childProcess.unref();
126
+ }
127
+
88
128
  // src/types.ts
89
129
  var MessageNotFoundError = class extends Error {
90
130
  constructor(messageId) {
@@ -100,6 +140,16 @@ var MessageNotAvailableError = class extends Error {
100
140
  this.name = "MessageNotAvailableError";
101
141
  }
102
142
  };
143
+ var FifoOrderingViolationError = class extends Error {
144
+ nextMessageId;
145
+ constructor(messageId, nextMessageId, reason) {
146
+ super(
147
+ `FIFO ordering violation for message ${messageId}: ${reason}. Process message ${nextMessageId} first.`
148
+ );
149
+ this.name = "FifoOrderingViolationError";
150
+ this.nextMessageId = nextMessageId;
151
+ }
152
+ };
103
153
  var MessageCorruptedError = class extends Error {
104
154
  constructor(messageId, reason) {
105
155
  super(`Message ${messageId} is corrupted: ${reason}`);
@@ -141,6 +191,16 @@ var BadRequestError = class extends Error {
141
191
  this.name = "BadRequestError";
142
192
  }
143
193
  };
194
+ var FailedDependencyError = class extends Error {
195
+ nextMessageId;
196
+ constructor(messageId, nextMessageId) {
197
+ super(
198
+ `Failed dependency: FIFO ordering violation for message ${messageId}. Must process message ${nextMessageId} first.`
199
+ );
200
+ this.name = "FailedDependencyError";
201
+ this.nextMessageId = nextMessageId;
202
+ }
203
+ };
144
204
  var InternalServerError = class extends Error {
145
205
  constructor(message = "Unexpected server error") {
146
206
  super(message);
@@ -153,6 +213,12 @@ var InvalidLimitError = class extends Error {
153
213
  this.name = "InvalidLimitError";
154
214
  }
155
215
  };
216
+ var InvalidCallbackError = class extends Error {
217
+ constructor(message) {
218
+ super(message);
219
+ this.name = "InvalidCallbackError";
220
+ }
221
+ };
156
222
 
157
223
  // src/client.ts
158
224
  async function consumeStream(stream) {
@@ -182,33 +248,40 @@ function parseQueueHeaders(headers) {
182
248
  return {
183
249
  messageId,
184
250
  deliveryCount,
185
- createdAt: new Date(timestamp),
251
+ timestamp,
186
252
  contentType,
187
253
  ticket
188
254
  };
189
255
  }
190
- var QueueClient = class {
256
+ var QueueClient = class _QueueClient {
191
257
  baseUrl;
192
- basePath;
193
258
  token;
194
259
  /**
195
260
  * Create a new Vercel Queue Service client
196
- * @param options Client configuration options (optional - will auto-detect Vercel Function environment)
261
+ * @param options Client configuration options
197
262
  */
198
- constructor(options = {}) {
199
- this.baseUrl = options.baseUrl || "https://api.vercel.com";
200
- this.basePath = options.basePath || "/v1/queues/messages";
201
- if (options.token) {
202
- this.token = options.token;
203
- } else {
204
- const token = getVercelOidcToken();
205
- if (!token) {
206
- throw new Error(
207
- "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'"
208
- );
209
- }
210
- this.token = token;
263
+ constructor(options) {
264
+ this.baseUrl = options.baseUrl || "https://vqs.vercel.sh";
265
+ this.token = options.token;
266
+ }
267
+ /**
268
+ * Create a QueueClient automatically configured for Vercel Functions
269
+ * This method automatically retrieves the OIDC token from the Vercel Function environment
270
+ * Always creates a fresh instance since OIDC tokens expire after 15 minutes
271
+ * @param baseUrl Optional base URL override
272
+ * @returns Promise resolving to a new QueueClient instance
273
+ */
274
+ static async fromVercelFunction(baseUrl) {
275
+ const token = await getVercelOidcToken();
276
+ if (!token) {
277
+ throw new Error(
278
+ "Failed to get OIDC token from Vercel Functions. Make sure you are running in a Vercel Function environment."
279
+ );
211
280
  }
281
+ return new _QueueClient({
282
+ token,
283
+ baseUrl
284
+ });
212
285
  }
213
286
  /**
214
287
  * Send a message to a queue
@@ -221,23 +294,40 @@ var QueueClient = class {
221
294
  * @throws {InternalServerError} When server encounters an error
222
295
  */
223
296
  async sendMessage(options, transport) {
224
- const { queueName, payload, idempotencyKey, retentionSeconds } = options;
297
+ const { queueName, payload, idempotencyKey, retentionSeconds, callbacks } = options;
225
298
  const headers = new Headers({
226
299
  Authorization: `Bearer ${this.token}`,
227
300
  "Vqs-Queue-Name": queueName,
228
301
  "Content-Type": transport.contentType
229
302
  });
230
- if (process.env.VERCEL_DEPLOYMENT_ID) {
231
- headers.set("Vqs-Deployment-Id", process.env.VERCEL_DEPLOYMENT_ID);
232
- }
233
303
  if (idempotencyKey) {
234
304
  headers.set("Vqs-Idempotency-Key", idempotencyKey);
235
305
  }
236
306
  if (retentionSeconds !== void 0) {
237
307
  headers.set("Vqs-Retention-Seconds", retentionSeconds.toString());
238
308
  }
309
+ let localhostCallbacks = [];
310
+ if (callbacks) {
311
+ const isDevelopment = process.env.NODE_ENV === "development";
312
+ if (isDevelopment) {
313
+ localhostCallbacks = processDevelopmentCallbacks(callbacks);
314
+ } else {
315
+ const endpoints = Object.entries(callbacks).map(
316
+ ([group, config]) => `${group}=${Buffer.from(config.url).toString("base64")}`
317
+ ).join(",");
318
+ headers.set("Vqs-Callback-Url", endpoints);
319
+ const delays = Object.entries(callbacks).filter(([, config]) => config.delay !== void 0).map(([group, config]) => `${group}=${config.delay}`).join(",");
320
+ if (delays) {
321
+ headers.set("Vqs-Callback-Delay", delays);
322
+ }
323
+ const frequencies = Object.entries(callbacks).filter(([, config]) => config.frequency !== void 0).map(([group, config]) => `${group}=${config.frequency}`).join(",");
324
+ if (frequencies) {
325
+ headers.set("Vqs-Callback-Frequency", frequencies);
326
+ }
327
+ }
328
+ }
239
329
  const body = transport.serialize(payload);
240
- const response = await fetch(`${this.baseUrl}${this.basePath}`, {
330
+ const response = await fetch(`${this.baseUrl}/api/v2/messages`, {
241
331
  method: "POST",
242
332
  headers,
243
333
  body
@@ -266,6 +356,9 @@ var QueueClient = class {
266
356
  );
267
357
  }
268
358
  const responseData = await response.json();
359
+ if (localhostCallbacks.length > 0) {
360
+ fireLocalhostCallbacks(localhostCallbacks, queueName, responseData);
361
+ }
269
362
  return responseData;
270
363
  }
271
364
  /**
@@ -275,7 +368,7 @@ var QueueClient = class {
275
368
  * @returns AsyncGenerator that yields messages as they arrive
276
369
  * @throws {InvalidLimitError} When limit parameter is not between 1 and 10
277
370
  * @throws {QueueEmptyError} When no messages are available (204)
278
- * @throws {MessageLockedError} When messages are temporarily locked (423)
371
+ * @throws {MessageLockedError} When FIFO queue has locked messages (423)
279
372
  * @throws {BadRequestError} When request parameters are invalid
280
373
  * @throws {UnauthorizedError} When authentication fails
281
374
  * @throws {ForbiddenError} When access is denied (environment mismatch)
@@ -301,7 +394,7 @@ var QueueClient = class {
301
394
  if (limit !== void 0) {
302
395
  headers.set("Vqs-Limit", limit.toString());
303
396
  }
304
- const response = await fetch(`${this.baseUrl}${this.basePath}`, {
397
+ const response = await fetch(`${this.baseUrl}/api/v2/messages`, {
305
398
  method: "GET",
306
399
  headers
307
400
  });
@@ -326,7 +419,7 @@ var QueueClient = class {
326
419
  const parsed = parseInt(retryAfterHeader, 10);
327
420
  retryAfter = isNaN(parsed) ? void 0 : parsed;
328
421
  }
329
- throw new MessageLockedError("next message", retryAfter);
422
+ throw new MessageLockedError("next message in FIFO queue", retryAfter);
330
423
  }
331
424
  if (response.status >= 500) {
332
425
  throw new InternalServerError(
@@ -383,7 +476,7 @@ var QueueClient = class {
383
476
  headers.set("Vqs-Skip-Payload", "1");
384
477
  }
385
478
  const response = await fetch(
386
- `${this.baseUrl}${this.basePath}/${encodeURIComponent(messageId)}`,
479
+ `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,
387
480
  {
388
481
  method: "GET",
389
482
  headers
@@ -412,7 +505,37 @@ var QueueClient = class {
412
505
  }
413
506
  throw new MessageLockedError(messageId, retryAfter);
414
507
  }
508
+ if (response.status === 424) {
509
+ try {
510
+ const errorData = await response.json();
511
+ if (errorData.meta?.nextMessageId) {
512
+ throw new FailedDependencyError(
513
+ messageId,
514
+ errorData.meta.nextMessageId
515
+ );
516
+ }
517
+ } catch (parseError) {
518
+ if (parseError instanceof FailedDependencyError) {
519
+ throw parseError;
520
+ }
521
+ }
522
+ throw new MessageNotAvailableError(
523
+ messageId,
524
+ "FIFO ordering violation"
525
+ );
526
+ }
415
527
  if (response.status === 409) {
528
+ try {
529
+ const errorData = await response.json();
530
+ if (errorData.nextMessageId) {
531
+ throw new FifoOrderingViolationError(
532
+ messageId,
533
+ errorData.nextMessageId,
534
+ errorData.error
535
+ );
536
+ }
537
+ } catch (parseError) {
538
+ }
416
539
  throw new MessageNotAvailableError(messageId);
417
540
  }
418
541
  if (response.status >= 500) {
@@ -492,7 +615,7 @@ var QueueClient = class {
492
615
  async deleteMessage(options) {
493
616
  const { queueName, consumerGroup, messageId, ticket } = options;
494
617
  const response = await fetch(
495
- `${this.baseUrl}${this.basePath}/${encodeURIComponent(messageId)}`,
618
+ `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,
496
619
  {
497
620
  method: "DELETE",
498
621
  headers: new Headers({
@@ -553,7 +676,7 @@ var QueueClient = class {
553
676
  visibilityTimeoutSeconds
554
677
  } = options;
555
678
  const response = await fetch(
556
- `${this.baseUrl}${this.basePath}/${encodeURIComponent(messageId)}`,
679
+ `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,
557
680
  {
558
681
  method: "PATCH",
559
682
  headers: new Headers({
@@ -599,6 +722,82 @@ var QueueClient = class {
599
722
  }
600
723
  };
601
724
 
725
+ // src/transports.ts
726
+ var JsonTransport = class {
727
+ contentType = "application/json";
728
+ serialize(value) {
729
+ return Buffer.from(JSON.stringify(value), "utf8");
730
+ }
731
+ async deserialize(stream) {
732
+ const reader = stream.getReader();
733
+ const chunks = [];
734
+ try {
735
+ while (true) {
736
+ const { done, value } = await reader.read();
737
+ if (done) break;
738
+ chunks.push(value);
739
+ }
740
+ } finally {
741
+ reader.releaseLock();
742
+ }
743
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
744
+ const buffer = new Uint8Array(totalLength);
745
+ let offset = 0;
746
+ for (const chunk of chunks) {
747
+ buffer.set(chunk, offset);
748
+ offset += chunk.length;
749
+ }
750
+ return JSON.parse(Buffer.from(buffer).toString("utf8"));
751
+ }
752
+ };
753
+ var BufferTransport = class {
754
+ contentType = "application/octet-stream";
755
+ serialize(value) {
756
+ return value;
757
+ }
758
+ async deserialize(stream) {
759
+ const reader = stream.getReader();
760
+ const chunks = [];
761
+ try {
762
+ while (true) {
763
+ const { done, value } = await reader.read();
764
+ if (done) break;
765
+ chunks.push(value);
766
+ }
767
+ } finally {
768
+ reader.releaseLock();
769
+ }
770
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
771
+ const buffer = new Uint8Array(totalLength);
772
+ let offset = 0;
773
+ for (const chunk of chunks) {
774
+ buffer.set(chunk, offset);
775
+ offset += chunk.length;
776
+ }
777
+ return Buffer.from(buffer);
778
+ }
779
+ };
780
+ var StreamTransport = class {
781
+ contentType = "application/octet-stream";
782
+ serialize(value) {
783
+ return value;
784
+ }
785
+ async deserialize(stream) {
786
+ return stream;
787
+ }
788
+ async finalize(payload) {
789
+ const reader = payload.getReader();
790
+ try {
791
+ while (true) {
792
+ const { done } = await reader.read();
793
+ if (done) break;
794
+ }
795
+ } finally {
796
+ reader.releaseLock();
797
+ }
798
+ }
799
+ };
800
+
602
801
  // src/consumer-group.ts
603
802
  var ConsumerGroup = class {
604
803
  client;
@@ -698,11 +897,7 @@ var ConsumerGroup = class {
698
897
  message.ticket
699
898
  );
700
899
  try {
701
- const result = await handler(message.payload, {
702
- messageId: message.messageId,
703
- deliveryCount: message.deliveryCount,
704
- createdAt: message.createdAt
705
- });
900
+ const result = await handler(message);
706
901
  await stopExtension();
707
902
  if (result && "timeoutSeconds" in result) {
708
903
  await this.client.changeVisibility({
@@ -732,58 +927,219 @@ var ConsumerGroup = class {
732
927
  throw error;
733
928
  }
734
929
  }
735
- async consume(handler, options) {
736
- if (options?.messageId) {
737
- if (options.skipPayload) {
738
- const response = await this.client.receiveMessageById(
930
+ /**
931
+ * Start continuous processing of messages from the topic
932
+ * @param signal AbortSignal to control when to stop processing
933
+ * @param handler Function to process each message
934
+ * @param options Processing options
935
+ * @returns Promise that resolves when processing stops (due to signal or error)
936
+ */
937
+ async subscribe(signal, handler, options = {}) {
938
+ const pollingInterval = options.pollingInterval || 1e3;
939
+ while (!signal.aborted) {
940
+ try {
941
+ for await (const message of this.client.receiveMessages(
739
942
  {
740
943
  queueName: this.topicName,
741
944
  consumerGroup: this.consumerGroupName,
742
- messageId: options.messageId,
743
945
  visibilityTimeoutSeconds: this.visibilityTimeout,
744
- skipPayload: true
946
+ limit: 1
947
+ // Always process one message at a time
745
948
  },
746
949
  this.transport
747
- );
748
- await this.processMessage(
749
- response.message,
750
- handler
751
- );
752
- } else {
753
- const response = await this.client.receiveMessageById(
754
- {
755
- queueName: this.topicName,
756
- consumerGroup: this.consumerGroupName,
757
- messageId: options.messageId,
758
- visibilityTimeoutSeconds: this.visibilityTimeout
759
- },
760
- this.transport
761
- );
762
- await this.processMessage(
763
- response.message,
764
- handler
765
- );
766
- }
767
- } else {
768
- let messageFound = false;
769
- for await (const message of this.client.receiveMessages(
770
- {
771
- queueName: this.topicName,
772
- consumerGroup: this.consumerGroupName,
773
- visibilityTimeoutSeconds: this.visibilityTimeout,
774
- limit: 1
775
- },
776
- this.transport
777
- )) {
778
- messageFound = true;
779
- await this.processMessage(message, handler);
780
- break;
781
- }
782
- if (!messageFound) {
783
- throw new Error("No messages available");
950
+ )) {
951
+ if (signal.aborted) {
952
+ break;
953
+ }
954
+ try {
955
+ await this.processMessage(message, handler);
956
+ } catch (error) {
957
+ console.error("Error processing message:", error);
958
+ }
959
+ }
960
+ if (!signal.aborted) {
961
+ await new Promise((resolve) => {
962
+ const timeoutId = setTimeout(resolve, pollingInterval);
963
+ signal.addEventListener(
964
+ "abort",
965
+ () => {
966
+ clearTimeout(timeoutId);
967
+ resolve();
968
+ },
969
+ { once: true }
970
+ );
971
+ });
972
+ }
973
+ } catch (error) {
974
+ if (error instanceof QueueEmptyError) {
975
+ if (!signal.aborted) {
976
+ await new Promise((resolve) => {
977
+ const timeoutId = setTimeout(resolve, pollingInterval);
978
+ signal.addEventListener(
979
+ "abort",
980
+ () => {
981
+ clearTimeout(timeoutId);
982
+ resolve();
983
+ },
984
+ { once: true }
985
+ );
986
+ });
987
+ }
988
+ continue;
989
+ }
990
+ if (error instanceof MessageLockedError) {
991
+ const waitTime = error.retryAfter ? error.retryAfter * 1e3 : pollingInterval;
992
+ if (!signal.aborted) {
993
+ await new Promise((resolve) => {
994
+ const timeoutId = setTimeout(resolve, waitTime);
995
+ signal.addEventListener(
996
+ "abort",
997
+ () => {
998
+ clearTimeout(timeoutId);
999
+ resolve();
1000
+ },
1001
+ { once: true }
1002
+ );
1003
+ });
1004
+ }
1005
+ continue;
1006
+ }
1007
+ console.error("Error polling topic:", error);
1008
+ throw error;
784
1009
  }
785
1010
  }
786
1011
  }
1012
+ /**
1013
+ * Receive and process a specific message by its ID with full payload
1014
+ * @param messageId The ID of the message to receive and process
1015
+ * @param handler Function to process the message with full payload
1016
+ * @returns Promise that resolves when the message is processed or rejects with specific errors
1017
+ * @throws {MessageNotFoundError} When the message doesn't exist (404)
1018
+ * @throws {MessageNotAvailableError} When the message exists but isn't available for processing (409)
1019
+ * @throws {MessageLockedError} When the message is temporarily locked (423)
1020
+ * @throws {FifoOrderingViolationError} When there's a FIFO ordering violation (409 with nextMessageId)
1021
+ * @throws {FailedDependencyError} When FIFO ordering is violated (424)
1022
+ * @throws {MessageCorruptedError} When the message data is corrupted
1023
+ * @throws {BadRequestError} When request parameters are invalid
1024
+ * @throws {UnauthorizedError} When authentication fails
1025
+ * @throws {ForbiddenError} When access is denied
1026
+ * @throws {InternalServerError} When server encounters an error
1027
+ */
1028
+ async receiveMessage(messageId, handler) {
1029
+ const response = await this.client.receiveMessageById(
1030
+ {
1031
+ queueName: this.topicName,
1032
+ consumerGroup: this.consumerGroupName,
1033
+ messageId,
1034
+ visibilityTimeoutSeconds: this.visibilityTimeout
1035
+ },
1036
+ this.transport
1037
+ );
1038
+ await this.processMessage(response.message, handler);
1039
+ }
1040
+ /**
1041
+ * Receive and process the next available message from the queue
1042
+ * @param handler Function to process the message
1043
+ * @returns Promise that resolves when the message is processed or rejects with specific errors
1044
+ * @throws {QueueEmptyError} When no messages are available in the queue (204)
1045
+ * @throws {MessageLockedError} When the next message in a FIFO queue is locked (423)
1046
+ * @throws {BadRequestError} When request parameters are invalid
1047
+ * @throws {UnauthorizedError} When authentication fails
1048
+ * @throws {ForbiddenError} When access is denied
1049
+ * @throws {InternalServerError} When server encounters an error
1050
+ */
1051
+ async receiveNextMessage(handler) {
1052
+ let messageFound = false;
1053
+ for await (const message of this.client.receiveMessages(
1054
+ {
1055
+ queueName: this.topicName,
1056
+ consumerGroup: this.consumerGroupName,
1057
+ visibilityTimeoutSeconds: this.visibilityTimeout,
1058
+ limit: 1
1059
+ },
1060
+ this.transport
1061
+ )) {
1062
+ messageFound = true;
1063
+ await this.processMessage(message, handler);
1064
+ break;
1065
+ }
1066
+ if (!messageFound) {
1067
+ throw new Error("No messages available");
1068
+ }
1069
+ }
1070
+ /**
1071
+ * Receive and process multiple next available messages from the queue
1072
+ * @param limit Number of messages to process (1-10)
1073
+ * @param handler Function to process each message
1074
+ * @returns Promise that resolves to an array of PromiseSettledResult (same as Promise.allSettled)
1075
+ * @throws {InvalidLimitError} When limit parameter is not between 1 and 10
1076
+ * @throws {QueueEmptyError} When no messages are available in the queue (204)
1077
+ * @throws {MessageLockedError} When the next message in a FIFO queue is locked (423)
1078
+ * @throws {BadRequestError} When request parameters are invalid
1079
+ * @throws {UnauthorizedError} When authentication fails
1080
+ * @throws {ForbiddenError} When access is denied
1081
+ * @throws {InternalServerError} When server encounters an error
1082
+ */
1083
+ async receiveNextMessages(limit, handler) {
1084
+ if (limit < 1 || limit > 10) {
1085
+ throw new InvalidLimitError(limit);
1086
+ }
1087
+ const processingPromises = [];
1088
+ let messageCount = 0;
1089
+ for await (const message of this.client.receiveMessages(
1090
+ {
1091
+ queueName: this.topicName,
1092
+ consumerGroup: this.consumerGroupName,
1093
+ visibilityTimeoutSeconds: this.visibilityTimeout,
1094
+ limit
1095
+ },
1096
+ this.transport
1097
+ )) {
1098
+ messageCount++;
1099
+ const wrappedPromise = this.processMessage(message, handler).then(
1100
+ (value) => ({
1101
+ status: "fulfilled",
1102
+ value
1103
+ }),
1104
+ (reason) => ({ status: "rejected", reason })
1105
+ );
1106
+ processingPromises.push(wrappedPromise);
1107
+ }
1108
+ if (messageCount === 0) {
1109
+ throw new Error("No messages available");
1110
+ }
1111
+ const results = await Promise.all(processingPromises);
1112
+ return results;
1113
+ }
1114
+ /**
1115
+ * Handle a specific message by its ID without downloading the payload (metadata only)
1116
+ * @param messageId The ID of the message to handle
1117
+ * @param handler Function to process the message metadata (payload will be void)
1118
+ * @returns Promise that resolves when the message is handled or rejects with specific errors
1119
+ * @throws {MessageNotFoundError} When the message doesn't exist (404)
1120
+ * @throws {MessageNotAvailableError} When the message exists but isn't available for processing (409)
1121
+ * @throws {MessageLockedError} When the message is temporarily locked (423)
1122
+ * @throws {FifoOrderingViolationError} When there's a FIFO ordering violation (409 with nextMessageId)
1123
+ * @throws {FailedDependencyError} When FIFO ordering is violated (424)
1124
+ * @throws {MessageCorruptedError} When the message data is corrupted
1125
+ * @throws {BadRequestError} When request parameters are invalid
1126
+ * @throws {UnauthorizedError} When authentication fails
1127
+ * @throws {ForbiddenError} When access is denied
1128
+ * @throws {InternalServerError} When server encounters an error
1129
+ */
1130
+ async handleMessage(messageId, handler) {
1131
+ const response = await this.client.receiveMessageById(
1132
+ {
1133
+ queueName: this.topicName,
1134
+ consumerGroup: this.consumerGroupName,
1135
+ messageId,
1136
+ visibilityTimeoutSeconds: this.visibilityTimeout,
1137
+ skipPayload: true
1138
+ },
1139
+ this.transport
1140
+ );
1141
+ await this.processMessage(response.message, handler);
1142
+ }
787
1143
  /**
788
1144
  * Get the consumer group name
789
1145
  */
@@ -830,7 +1186,8 @@ var Topic = class {
830
1186
  queueName: this.topicName,
831
1187
  payload,
832
1188
  idempotencyKey: options?.idempotencyKey,
833
- retentionSeconds: options?.retentionSeconds
1189
+ retentionSeconds: options?.retentionSeconds,
1190
+ callbacks: options?.callbacks
834
1191
  },
835
1192
  this.transport
836
1193
  );
@@ -869,138 +1226,53 @@ var Topic = class {
869
1226
  };
870
1227
 
871
1228
  // src/factory.ts
872
- async function send(topicName, payload, options) {
873
- const transport = options?.transport || new JsonTransport();
874
- const client = new QueueClient();
875
- const result = await client.sendMessage(
876
- {
877
- queueName: topicName,
878
- payload,
879
- idempotencyKey: options?.idempotencyKey,
880
- retentionSeconds: options?.retentionSeconds
881
- },
882
- transport
883
- );
884
- return { messageId: result.messageId };
885
- }
886
- async function receive(topicName, consumerGroup, handler, options) {
887
- const transport = options?.transport || new JsonTransport();
888
- const client = new QueueClient();
889
- const topic = new Topic(client, topicName, transport);
890
- const { messageId, skipPayload, ...consumerGroupOptions } = options || {};
891
- const consumer = topic.consumerGroup(consumerGroup, consumerGroupOptions);
892
- if (messageId) {
893
- if (skipPayload) {
894
- return consumer.consume(handler, {
895
- messageId,
896
- skipPayload: true
897
- });
898
- } else {
899
- return consumer.consume(handler, { messageId });
900
- }
901
- } else {
902
- return consumer.consume(handler);
903
- }
1229
+ function createTopic(client, topicName, transport) {
1230
+ return new Topic(client, topicName, transport);
904
1231
  }
905
1232
 
906
1233
  // src/callback.ts
907
- async function parseCallbackRequest(request) {
908
- const contentType = request.headers.get("content-type");
909
- if (!contentType || !contentType.includes("application/cloudevents+json")) {
910
- throw new Error(
911
- "Invalid content type: expected 'application/cloudevents+json'"
912
- );
913
- }
914
- let cloudEvent;
915
- try {
916
- cloudEvent = await request.json();
917
- } catch (error) {
918
- throw new Error("Failed to parse CloudEvent from request body");
919
- }
920
- if (!cloudEvent.type || !cloudEvent.source || !cloudEvent.id || typeof cloudEvent.data !== "object" || cloudEvent.data == null) {
921
- throw new Error("Invalid CloudEvent: missing required fields");
922
- }
923
- if (cloudEvent.type !== "com.vercel.queue.v1beta") {
924
- throw new Error(
925
- `Invalid CloudEvent type: expected 'com.vercel.queue.v1beta', got '${cloudEvent.type}'`
926
- );
927
- }
928
- const missingFields = [];
929
- if (!("queueName" in cloudEvent.data)) missingFields.push("queueName");
930
- if (!("consumerGroup" in cloudEvent.data))
931
- missingFields.push("consumerGroup");
932
- if (!("messageId" in cloudEvent.data)) missingFields.push("messageId");
933
- if (missingFields.length > 0) {
934
- throw new Error(
935
- `Missing required CloudEvent data fields: ${missingFields.join(", ")}`
1234
+ function parseCallbackRequest(request) {
1235
+ const headers = request.headers;
1236
+ const messageId = headers.get("Vqs-Message-Id");
1237
+ const queueName = headers.get("Vqs-Queue-Name");
1238
+ const consumerGroup = headers.get("Vqs-Consumer-Group");
1239
+ const missingHeaders = [];
1240
+ if (!messageId) missingHeaders.push("Vqs-Message-Id");
1241
+ if (!queueName) missingHeaders.push("Vqs-Queue-Name");
1242
+ if (!consumerGroup) missingHeaders.push("Vqs-Consumer-Group");
1243
+ if (missingHeaders.length > 0) {
1244
+ throw new InvalidCallbackError(
1245
+ `Missing required queue callback headers: ${missingHeaders.join(", ")}`
936
1246
  );
937
1247
  }
938
- const { messageId, queueName, consumerGroup } = cloudEvent.data;
939
1248
  return {
1249
+ messageId,
940
1250
  queueName,
941
- consumerGroup,
942
- messageId
943
- };
944
- }
945
- function handleCallback(handlers) {
946
- return async (request) => {
947
- try {
948
- const { queueName, consumerGroup, messageId } = await parseCallbackRequest(request);
949
- const topicHandler = handlers[queueName];
950
- if (!topicHandler) {
951
- const availableTopics = Object.keys(handlers).join(", ");
952
- return Response.json(
953
- {
954
- error: `No handler found for topic: ${queueName}`,
955
- availableTopics
956
- },
957
- { status: 404 }
958
- );
959
- }
960
- const consumerGroupHandler = topicHandler[consumerGroup];
961
- if (!consumerGroupHandler) {
962
- const availableGroups = Object.keys(topicHandler).join(", ");
963
- return Response.json(
964
- {
965
- error: `No handler found for consumer group "${consumerGroup}" in topic "${queueName}".`,
966
- availableGroups
967
- },
968
- { status: 404 }
969
- );
970
- }
971
- const client = new QueueClient();
972
- const topic = new Topic(client, queueName);
973
- const cg = topic.consumerGroup(consumerGroup);
974
- await cg.consume(consumerGroupHandler, { messageId });
975
- return Response.json({ status: "success" });
976
- } catch (error) {
977
- console.error("Queue callback error:", error);
978
- 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"))) {
979
- return Response.json({ error: error.message }, { status: 400 });
980
- }
981
- return Response.json(
982
- { error: "Failed to process queue message" },
983
- { status: 500 }
984
- );
985
- }
1251
+ consumerGroup
986
1252
  };
987
1253
  }
988
1254
  export {
989
1255
  BadRequestError,
990
1256
  BufferTransport,
1257
+ ConsumerGroup,
1258
+ FailedDependencyError,
1259
+ FifoOrderingViolationError,
991
1260
  ForbiddenError,
992
1261
  InternalServerError,
1262
+ InvalidCallbackError,
993
1263
  InvalidLimitError,
994
1264
  JsonTransport,
995
1265
  MessageCorruptedError,
996
1266
  MessageLockedError,
997
1267
  MessageNotAvailableError,
998
1268
  MessageNotFoundError,
1269
+ QueueClient,
999
1270
  QueueEmptyError,
1000
1271
  StreamTransport,
1272
+ Topic,
1001
1273
  UnauthorizedError,
1002
- handleCallback,
1003
- receive,
1004
- send
1274
+ createTopic,
1275
+ getVercelOidcToken,
1276
+ parseCallbackRequest
1005
1277
  };
1006
1278
  //# sourceMappingURL=index.mjs.map