@vercel/queue 0.0.0-alpha.12 → 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://vercel-queue.com";
200
- this.basePath = options.basePath || "/api/v2/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,13 +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
- topicName: this.topicName,
706
- consumerGroup: this.consumerGroupName
707
- });
900
+ const result = await handler(message);
708
901
  await stopExtension();
709
902
  if (result && "timeoutSeconds" in result) {
710
903
  await this.client.changeVisibility({
@@ -734,58 +927,219 @@ var ConsumerGroup = class {
734
927
  throw error;
735
928
  }
736
929
  }
737
- async consume(handler, options) {
738
- if (options?.messageId) {
739
- if (options.skipPayload) {
740
- 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(
741
942
  {
742
943
  queueName: this.topicName,
743
944
  consumerGroup: this.consumerGroupName,
744
- messageId: options.messageId,
745
945
  visibilityTimeoutSeconds: this.visibilityTimeout,
746
- skipPayload: true
946
+ limit: 1
947
+ // Always process one message at a time
747
948
  },
748
949
  this.transport
749
- );
750
- await this.processMessage(
751
- response.message,
752
- handler
753
- );
754
- } else {
755
- const response = await this.client.receiveMessageById(
756
- {
757
- queueName: this.topicName,
758
- consumerGroup: this.consumerGroupName,
759
- messageId: options.messageId,
760
- visibilityTimeoutSeconds: this.visibilityTimeout
761
- },
762
- this.transport
763
- );
764
- await this.processMessage(
765
- response.message,
766
- handler
767
- );
768
- }
769
- } else {
770
- let messageFound = false;
771
- for await (const message of this.client.receiveMessages(
772
- {
773
- queueName: this.topicName,
774
- consumerGroup: this.consumerGroupName,
775
- visibilityTimeoutSeconds: this.visibilityTimeout,
776
- limit: 1
777
- },
778
- this.transport
779
- )) {
780
- messageFound = true;
781
- await this.processMessage(message, handler);
782
- break;
783
- }
784
- if (!messageFound) {
785
- 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;
786
1009
  }
787
1010
  }
788
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
+ }
789
1143
  /**
790
1144
  * Get the consumer group name
791
1145
  */
@@ -832,7 +1186,8 @@ var Topic = class {
832
1186
  queueName: this.topicName,
833
1187
  payload,
834
1188
  idempotencyKey: options?.idempotencyKey,
835
- retentionSeconds: options?.retentionSeconds
1189
+ retentionSeconds: options?.retentionSeconds,
1190
+ callbacks: options?.callbacks
836
1191
  },
837
1192
  this.transport
838
1193
  );
@@ -871,178 +1226,53 @@ var Topic = class {
871
1226
  };
872
1227
 
873
1228
  // src/factory.ts
874
- async function send(topicName, payload, options) {
875
- const transport = options?.transport || new JsonTransport();
876
- const client = new QueueClient();
877
- const result = await client.sendMessage(
878
- {
879
- queueName: topicName,
880
- payload,
881
- idempotencyKey: options?.idempotencyKey,
882
- retentionSeconds: options?.retentionSeconds
883
- },
884
- transport
885
- );
886
- return { messageId: result.messageId };
887
- }
888
- async function receive(topicName, consumerGroup, handler, options) {
889
- const transport = options?.transport || new JsonTransport();
890
- const client = new QueueClient();
891
- const topic = new Topic(client, topicName, transport);
892
- const { messageId, skipPayload, ...consumerGroupOptions } = options || {};
893
- const consumer = topic.consumerGroup(consumerGroup, consumerGroupOptions);
894
- if (messageId) {
895
- if (skipPayload) {
896
- return consumer.consume(handler, {
897
- messageId,
898
- skipPayload: true
899
- });
900
- } else {
901
- return consumer.consume(handler, { messageId });
902
- }
903
- } else {
904
- return consumer.consume(handler);
905
- }
1229
+ function createTopic(client, topicName, transport) {
1230
+ return new Topic(client, topicName, transport);
906
1231
  }
907
1232
 
908
1233
  // src/callback.ts
909
- function validateWildcardPattern(pattern) {
910
- const firstIndex = pattern.indexOf("*");
911
- const lastIndex = pattern.lastIndexOf("*");
912
- if (firstIndex !== lastIndex) {
913
- return false;
914
- }
915
- if (firstIndex === -1) {
916
- return false;
917
- }
918
- if (firstIndex !== pattern.length - 1) {
919
- return false;
920
- }
921
- return true;
922
- }
923
- function matchesWildcardPattern(topicName, pattern) {
924
- const prefix = pattern.slice(0, -1);
925
- return topicName.startsWith(prefix);
926
- }
927
- function findTopicHandler(queueName, handlers) {
928
- const exactHandler = handlers[queueName];
929
- if (exactHandler) {
930
- return exactHandler;
931
- }
932
- for (const pattern in handlers) {
933
- if (pattern.includes("*") && matchesWildcardPattern(queueName, pattern)) {
934
- return handlers[pattern];
935
- }
936
- }
937
- return null;
938
- }
939
- async function parseCallback(request) {
940
- const contentType = request.headers.get("content-type");
941
- if (!contentType || !contentType.includes("application/cloudevents+json")) {
942
- throw new Error(
943
- "Invalid content type: expected 'application/cloudevents+json'"
944
- );
945
- }
946
- let cloudEvent;
947
- try {
948
- cloudEvent = await request.json();
949
- } catch (error) {
950
- throw new Error("Failed to parse CloudEvent from request body");
951
- }
952
- if (!cloudEvent.type || !cloudEvent.source || !cloudEvent.id || typeof cloudEvent.data !== "object" || cloudEvent.data == null) {
953
- throw new Error("Invalid CloudEvent: missing required fields");
954
- }
955
- if (cloudEvent.type !== "com.vercel.queue.v1beta") {
956
- throw new Error(
957
- `Invalid CloudEvent type: expected 'com.vercel.queue.v1beta', got '${cloudEvent.type}'`
958
- );
959
- }
960
- const missingFields = [];
961
- if (!("queueName" in cloudEvent.data)) missingFields.push("queueName");
962
- if (!("consumerGroup" in cloudEvent.data))
963
- missingFields.push("consumerGroup");
964
- if (!("messageId" in cloudEvent.data)) missingFields.push("messageId");
965
- if (missingFields.length > 0) {
966
- throw new Error(
967
- `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(", ")}`
968
1246
  );
969
1247
  }
970
- const { messageId, queueName, consumerGroup } = cloudEvent.data;
971
1248
  return {
1249
+ messageId,
972
1250
  queueName,
973
- consumerGroup,
974
- messageId
975
- };
976
- }
977
- function handleCallback(handlers) {
978
- for (const topicPattern in handlers) {
979
- if (topicPattern.includes("*")) {
980
- if (!validateWildcardPattern(topicPattern)) {
981
- throw new Error(
982
- `Invalid wildcard pattern "${topicPattern}": * may only appear once and must be at the end of the topic name`
983
- );
984
- }
985
- }
986
- }
987
- return async (request) => {
988
- try {
989
- const { queueName, consumerGroup, messageId } = await parseCallback(request);
990
- const topicHandler = findTopicHandler(queueName, handlers);
991
- if (!topicHandler) {
992
- const availableTopics = Object.keys(handlers).join(", ");
993
- return Response.json(
994
- {
995
- error: `No handler found for topic: ${queueName}`,
996
- availableTopics
997
- },
998
- { status: 404 }
999
- );
1000
- }
1001
- const consumerGroupHandler = topicHandler[consumerGroup];
1002
- if (!consumerGroupHandler) {
1003
- const availableGroups = Object.keys(topicHandler).join(", ");
1004
- return Response.json(
1005
- {
1006
- error: `No handler found for consumer group "${consumerGroup}" in topic "${queueName}".`,
1007
- availableGroups
1008
- },
1009
- { status: 404 }
1010
- );
1011
- }
1012
- const client = new QueueClient();
1013
- const topic = new Topic(client, queueName);
1014
- const cg = topic.consumerGroup(consumerGroup);
1015
- await cg.consume(consumerGroupHandler, { messageId });
1016
- return Response.json({ status: "success" });
1017
- } catch (error) {
1018
- console.error("Queue callback error:", error);
1019
- 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"))) {
1020
- return Response.json({ error: error.message }, { status: 400 });
1021
- }
1022
- return Response.json(
1023
- { error: "Failed to process queue message" },
1024
- { status: 500 }
1025
- );
1026
- }
1251
+ consumerGroup
1027
1252
  };
1028
1253
  }
1029
1254
  export {
1030
1255
  BadRequestError,
1031
1256
  BufferTransport,
1257
+ ConsumerGroup,
1258
+ FailedDependencyError,
1259
+ FifoOrderingViolationError,
1032
1260
  ForbiddenError,
1033
1261
  InternalServerError,
1262
+ InvalidCallbackError,
1034
1263
  InvalidLimitError,
1035
1264
  JsonTransport,
1036
1265
  MessageCorruptedError,
1037
1266
  MessageLockedError,
1038
1267
  MessageNotAvailableError,
1039
1268
  MessageNotFoundError,
1269
+ QueueClient,
1040
1270
  QueueEmptyError,
1041
1271
  StreamTransport,
1272
+ Topic,
1042
1273
  UnauthorizedError,
1043
- handleCallback,
1044
- parseCallback,
1045
- receive,
1046
- send
1274
+ createTopic,
1275
+ getVercelOidcToken,
1276
+ parseCallbackRequest
1047
1277
  };
1048
1278
  //# sourceMappingURL=index.mjs.map