@vercel/queue 0.0.0-alpha.1

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 ADDED
@@ -0,0 +1,1278 @@
1
+ // src/oidc.ts
2
+ async function getVercelOidcToken() {
3
+ const SYMBOL_FOR_REQ_CONTEXT = Symbol.for("@vercel/request-context");
4
+ const fromSymbol = globalThis;
5
+ const context = fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
6
+ const token = context.headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
7
+ if (!token) {
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
+ );
11
+ }
12
+ return token;
13
+ }
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
+ `VQS 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
+ `VQS 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
+ `VQS: 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
+
128
+ // src/types.ts
129
+ var MessageNotFoundError = class extends Error {
130
+ constructor(messageId) {
131
+ super(`Message ${messageId} not found`);
132
+ this.name = "MessageNotFoundError";
133
+ }
134
+ };
135
+ var MessageNotAvailableError = class extends Error {
136
+ constructor(messageId, reason) {
137
+ super(
138
+ `Message ${messageId} not available for processing${reason ? `: ${reason}` : ""}`
139
+ );
140
+ this.name = "MessageNotAvailableError";
141
+ }
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
+ };
153
+ var MessageCorruptedError = class extends Error {
154
+ constructor(messageId, reason) {
155
+ super(`Message ${messageId} is corrupted: ${reason}`);
156
+ this.name = "MessageCorruptedError";
157
+ }
158
+ };
159
+ var QueueEmptyError = class extends Error {
160
+ constructor(queueName, consumerGroup) {
161
+ super(
162
+ `No messages available in queue "${queueName}" for consumer group "${consumerGroup}"`
163
+ );
164
+ this.name = "QueueEmptyError";
165
+ }
166
+ };
167
+ var MessageLockedError = class extends Error {
168
+ retryAfter;
169
+ constructor(messageId, retryAfter) {
170
+ const retryMessage = retryAfter ? ` Retry after ${retryAfter} seconds.` : " Try again later.";
171
+ super(`Message ${messageId} is temporarily locked.${retryMessage}`);
172
+ this.name = "MessageLockedError";
173
+ this.retryAfter = retryAfter;
174
+ }
175
+ };
176
+ var UnauthorizedError = class extends Error {
177
+ constructor(message = "Missing or invalid authentication token") {
178
+ super(message);
179
+ this.name = "UnauthorizedError";
180
+ }
181
+ };
182
+ var ForbiddenError = class extends Error {
183
+ constructor(message = "Queue environment doesn't match token environment") {
184
+ super(message);
185
+ this.name = "ForbiddenError";
186
+ }
187
+ };
188
+ var BadRequestError = class extends Error {
189
+ constructor(message) {
190
+ super(message);
191
+ this.name = "BadRequestError";
192
+ }
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
+ };
204
+ var InternalServerError = class extends Error {
205
+ constructor(message = "Unexpected server error") {
206
+ super(message);
207
+ this.name = "InternalServerError";
208
+ }
209
+ };
210
+ var InvalidLimitError = class extends Error {
211
+ constructor(limit, min = 1, max = 10) {
212
+ super(`Invalid limit: ${limit}. Limit must be between ${min} and ${max}.`);
213
+ this.name = "InvalidLimitError";
214
+ }
215
+ };
216
+ var InvalidCallbackError = class extends Error {
217
+ constructor(message) {
218
+ super(message);
219
+ this.name = "InvalidCallbackError";
220
+ }
221
+ };
222
+
223
+ // src/client.ts
224
+ async function consumeStream(stream) {
225
+ const reader = stream.getReader();
226
+ try {
227
+ while (true) {
228
+ const { done } = await reader.read();
229
+ if (done) break;
230
+ }
231
+ } finally {
232
+ reader.releaseLock();
233
+ }
234
+ }
235
+ function parseVQSHeaders(headers) {
236
+ const messageId = headers.get("Vqs-Message-Id");
237
+ const deliveryCountStr = headers.get("Vqs-Delivery-Count") || "0";
238
+ const timestamp = headers.get("Vqs-Timestamp");
239
+ const contentType = headers.get("Content-Type") || "application/octet-stream";
240
+ const ticket = headers.get("Vqs-Ticket");
241
+ if (!messageId || !timestamp || !ticket) {
242
+ return null;
243
+ }
244
+ const deliveryCount = parseInt(deliveryCountStr, 10);
245
+ if (isNaN(deliveryCount)) {
246
+ return null;
247
+ }
248
+ return {
249
+ messageId,
250
+ deliveryCount,
251
+ timestamp,
252
+ contentType,
253
+ ticket
254
+ };
255
+ }
256
+ var VQSClient = class _VQSClient {
257
+ baseUrl;
258
+ token;
259
+ /**
260
+ * Create a new Vercel Queue Service client
261
+ * @param options Client configuration options
262
+ */
263
+ constructor(options) {
264
+ this.baseUrl = options.baseUrl || "https://vqs.vercel.sh";
265
+ this.token = options.token;
266
+ }
267
+ /**
268
+ * Create a VQSClient 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 VQSClient 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
+ );
280
+ }
281
+ return new _VQSClient({
282
+ token,
283
+ baseUrl
284
+ });
285
+ }
286
+ /**
287
+ * Send a message to a queue
288
+ * @param options Send message options
289
+ * @param transport Serializer/deserializer for the payload
290
+ * @returns Promise with the message ID
291
+ * @throws {BadRequestError} When request parameters are invalid
292
+ * @throws {UnauthorizedError} When authentication fails
293
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
294
+ * @throws {InternalServerError} When server encounters an error
295
+ */
296
+ async sendMessage(options, transport) {
297
+ const { queueName, payload, idempotencyKey, retentionSeconds, callbacks } = options;
298
+ const headers = new Headers({
299
+ Authorization: `Bearer ${this.token}`,
300
+ "Vqs-Queue-Name": queueName,
301
+ "Content-Type": transport.contentType
302
+ });
303
+ if (idempotencyKey) {
304
+ headers.set("Vqs-Idempotency-Key", idempotencyKey);
305
+ }
306
+ if (retentionSeconds !== void 0) {
307
+ headers.set("Vqs-Retention-Seconds", retentionSeconds.toString());
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
+ }
329
+ const body = transport.serialize(payload);
330
+ const response = await fetch(`${this.baseUrl}/api/v2/messages`, {
331
+ method: "POST",
332
+ headers,
333
+ body
334
+ });
335
+ if (!response.ok) {
336
+ if (response.status === 400) {
337
+ const errorText = await response.text();
338
+ throw new BadRequestError(errorText || "Invalid parameters");
339
+ }
340
+ if (response.status === 401) {
341
+ throw new UnauthorizedError();
342
+ }
343
+ if (response.status === 403) {
344
+ throw new ForbiddenError();
345
+ }
346
+ if (response.status === 409) {
347
+ throw new Error("Duplicate idempotency key detected");
348
+ }
349
+ if (response.status >= 500) {
350
+ throw new InternalServerError(
351
+ `Server error: ${response.status} ${response.statusText}`
352
+ );
353
+ }
354
+ throw new Error(
355
+ `Failed to send message: ${response.status} ${response.statusText}`
356
+ );
357
+ }
358
+ const responseData = await response.json();
359
+ if (localhostCallbacks.length > 0) {
360
+ fireLocalhostCallbacks(localhostCallbacks, queueName, responseData);
361
+ }
362
+ return responseData;
363
+ }
364
+ /**
365
+ * Receive messages from a queue
366
+ * @param options Receive messages options
367
+ * @param transport Serializer/deserializer for the payload
368
+ * @returns AsyncGenerator that yields messages as they arrive
369
+ * @throws {InvalidLimitError} When limit parameter is not between 1 and 10
370
+ * @throws {QueueEmptyError} When no messages are available (204)
371
+ * @throws {MessageLockedError} When FIFO queue has locked messages (423)
372
+ * @throws {BadRequestError} When request parameters are invalid
373
+ * @throws {UnauthorizedError} When authentication fails
374
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
375
+ * @throws {InternalServerError} When server encounters an error
376
+ */
377
+ async *receiveMessages(options, transport) {
378
+ const { queueName, consumerGroup, visibilityTimeoutSeconds, limit } = options;
379
+ if (limit !== void 0 && (limit < 1 || limit > 10)) {
380
+ throw new InvalidLimitError(limit);
381
+ }
382
+ const headers = new Headers({
383
+ Authorization: `Bearer ${this.token}`,
384
+ "Vqs-Queue-Name": queueName,
385
+ "Vqs-Consumer-Group": consumerGroup,
386
+ Accept: "multipart/mixed"
387
+ });
388
+ if (visibilityTimeoutSeconds !== void 0) {
389
+ headers.set(
390
+ "Vqs-Visibility-Timeout",
391
+ visibilityTimeoutSeconds.toString()
392
+ );
393
+ }
394
+ if (limit !== void 0) {
395
+ headers.set("Vqs-Limit", limit.toString());
396
+ }
397
+ const response = await fetch(`${this.baseUrl}/api/v2/messages`, {
398
+ method: "GET",
399
+ headers
400
+ });
401
+ if (response.status === 204) {
402
+ throw new QueueEmptyError(queueName, consumerGroup);
403
+ }
404
+ if (!response.ok) {
405
+ if (response.status === 400) {
406
+ const errorText = await response.text();
407
+ throw new BadRequestError(errorText || "Invalid parameters");
408
+ }
409
+ if (response.status === 401) {
410
+ throw new UnauthorizedError();
411
+ }
412
+ if (response.status === 403) {
413
+ throw new ForbiddenError();
414
+ }
415
+ if (response.status === 423) {
416
+ const retryAfterHeader = response.headers.get("Retry-After");
417
+ let retryAfter;
418
+ if (retryAfterHeader) {
419
+ const parsed = parseInt(retryAfterHeader, 10);
420
+ retryAfter = isNaN(parsed) ? void 0 : parsed;
421
+ }
422
+ throw new MessageLockedError("next message in FIFO queue", retryAfter);
423
+ }
424
+ if (response.status >= 500) {
425
+ throw new InternalServerError(
426
+ `Server error: ${response.status} ${response.statusText}`
427
+ );
428
+ }
429
+ throw new Error(
430
+ `Failed to receive messages: ${response.status} ${response.statusText}`
431
+ );
432
+ }
433
+ for await (const multipartMessage of parseMultipartStream(response)) {
434
+ try {
435
+ const parsedHeaders = parseVQSHeaders(multipartMessage.headers);
436
+ if (!parsedHeaders) {
437
+ console.warn("Missing required VQS headers in multipart part");
438
+ await consumeStream(multipartMessage.payload);
439
+ continue;
440
+ }
441
+ const deserializedPayload = await transport.deserialize(
442
+ multipartMessage.payload
443
+ );
444
+ const message = {
445
+ ...parsedHeaders,
446
+ payload: deserializedPayload
447
+ };
448
+ yield message;
449
+ } catch (error) {
450
+ console.warn("Failed to process multipart message:", error);
451
+ await consumeStream(multipartMessage.payload);
452
+ }
453
+ }
454
+ }
455
+ async receiveMessageById(options, transport) {
456
+ const {
457
+ queueName,
458
+ consumerGroup,
459
+ messageId,
460
+ visibilityTimeoutSeconds,
461
+ skipPayload
462
+ } = options;
463
+ const headers = new Headers({
464
+ Authorization: `Bearer ${this.token}`,
465
+ "Vqs-Queue-Name": queueName,
466
+ "Vqs-Consumer-Group": consumerGroup,
467
+ Accept: "multipart/mixed"
468
+ });
469
+ if (visibilityTimeoutSeconds !== void 0) {
470
+ headers.set(
471
+ "Vqs-Visibility-Timeout",
472
+ visibilityTimeoutSeconds.toString()
473
+ );
474
+ }
475
+ if (skipPayload) {
476
+ headers.set("Vqs-Skip-Payload", "1");
477
+ }
478
+ const response = await fetch(
479
+ `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,
480
+ {
481
+ method: "GET",
482
+ headers
483
+ }
484
+ );
485
+ if (!response.ok) {
486
+ if (response.status === 400) {
487
+ const errorText = await response.text();
488
+ throw new BadRequestError(errorText || "Invalid parameters");
489
+ }
490
+ if (response.status === 401) {
491
+ throw new UnauthorizedError();
492
+ }
493
+ if (response.status === 403) {
494
+ throw new ForbiddenError();
495
+ }
496
+ if (response.status === 404) {
497
+ throw new MessageNotFoundError(messageId);
498
+ }
499
+ if (response.status === 423) {
500
+ const retryAfterHeader = response.headers.get("Retry-After");
501
+ let retryAfter;
502
+ if (retryAfterHeader) {
503
+ const parsed = parseInt(retryAfterHeader, 10);
504
+ retryAfter = isNaN(parsed) ? void 0 : parsed;
505
+ }
506
+ throw new MessageLockedError(messageId, retryAfter);
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
+ }
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
+ }
539
+ throw new MessageNotAvailableError(messageId);
540
+ }
541
+ if (response.status >= 500) {
542
+ throw new InternalServerError(
543
+ `Server error: ${response.status} ${response.statusText}`
544
+ );
545
+ }
546
+ throw new Error(
547
+ `Failed to receive message by ID: ${response.status} ${response.statusText}`
548
+ );
549
+ }
550
+ if (skipPayload && response.status === 204) {
551
+ const parsedHeaders = parseVQSHeaders(response.headers);
552
+ if (!parsedHeaders) {
553
+ throw new MessageCorruptedError(
554
+ messageId,
555
+ "Missing required VQS headers in 204 response"
556
+ );
557
+ }
558
+ const message = {
559
+ ...parsedHeaders,
560
+ payload: void 0
561
+ };
562
+ return { message };
563
+ }
564
+ if (!transport) {
565
+ throw new Error("Transport is required when skipPayload is not true");
566
+ }
567
+ try {
568
+ for await (const multipartMessage of parseMultipartStream(response)) {
569
+ try {
570
+ const parsedHeaders = parseVQSHeaders(multipartMessage.headers);
571
+ if (!parsedHeaders) {
572
+ console.warn("Missing required VQS headers in multipart part");
573
+ await consumeStream(multipartMessage.payload);
574
+ continue;
575
+ }
576
+ const deserializedPayload = await transport.deserialize(
577
+ multipartMessage.payload
578
+ );
579
+ const message = {
580
+ ...parsedHeaders,
581
+ payload: deserializedPayload
582
+ };
583
+ return { message };
584
+ } catch (error) {
585
+ console.warn("Failed to deserialize message by ID:", error);
586
+ await consumeStream(multipartMessage.payload);
587
+ throw new MessageCorruptedError(
588
+ messageId,
589
+ `Failed to deserialize payload: ${error}`
590
+ );
591
+ }
592
+ }
593
+ } catch (error) {
594
+ if (error instanceof MessageCorruptedError) {
595
+ throw error;
596
+ }
597
+ throw new MessageCorruptedError(
598
+ messageId,
599
+ `Failed to parse multipart response: ${error}`
600
+ );
601
+ }
602
+ throw new MessageNotFoundError(messageId);
603
+ }
604
+ /**
605
+ * Delete a message (acknowledge processing)
606
+ * @param options Delete message options
607
+ * @returns Promise with delete status
608
+ * @throws {MessageNotFoundError} When the message doesn't exist (404)
609
+ * @throws {MessageNotAvailableError} When message can't be deleted (409)
610
+ * @throws {BadRequestError} When ticket is missing or invalid (400)
611
+ * @throws {UnauthorizedError} When authentication fails
612
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
613
+ * @throws {InternalServerError} When server encounters an error
614
+ */
615
+ async deleteMessage(options) {
616
+ const { queueName, consumerGroup, messageId, ticket } = options;
617
+ const response = await fetch(
618
+ `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,
619
+ {
620
+ method: "DELETE",
621
+ headers: new Headers({
622
+ Authorization: `Bearer ${this.token}`,
623
+ "Vqs-Queue-Name": queueName,
624
+ "Vqs-Consumer-Group": consumerGroup,
625
+ "Vqs-Ticket": ticket
626
+ })
627
+ }
628
+ );
629
+ if (!response.ok) {
630
+ if (response.status === 400) {
631
+ throw new BadRequestError("Missing or invalid ticket");
632
+ }
633
+ if (response.status === 401) {
634
+ throw new UnauthorizedError();
635
+ }
636
+ if (response.status === 403) {
637
+ throw new ForbiddenError();
638
+ }
639
+ if (response.status === 404) {
640
+ throw new MessageNotFoundError(messageId);
641
+ }
642
+ if (response.status === 409) {
643
+ throw new MessageNotAvailableError(
644
+ messageId,
645
+ "Invalid ticket, message not in correct state, or already processed"
646
+ );
647
+ }
648
+ if (response.status >= 500) {
649
+ throw new InternalServerError(
650
+ `Server error: ${response.status} ${response.statusText}`
651
+ );
652
+ }
653
+ throw new Error(
654
+ `Failed to delete message: ${response.status} ${response.statusText}`
655
+ );
656
+ }
657
+ return { deleted: true };
658
+ }
659
+ /**
660
+ * Change the visibility timeout of a message
661
+ * @param options Change visibility options
662
+ * @returns Promise with update status
663
+ * @throws {MessageNotFoundError} When the message doesn't exist (404)
664
+ * @throws {MessageNotAvailableError} When message can't be updated (409)
665
+ * @throws {BadRequestError} When ticket is missing or visibility timeout invalid (400)
666
+ * @throws {UnauthorizedError} When authentication fails
667
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
668
+ * @throws {InternalServerError} When server encounters an error
669
+ */
670
+ async changeVisibility(options) {
671
+ const {
672
+ queueName,
673
+ consumerGroup,
674
+ messageId,
675
+ ticket,
676
+ visibilityTimeoutSeconds
677
+ } = options;
678
+ const response = await fetch(
679
+ `${this.baseUrl}/api/v2/messages/${encodeURIComponent(messageId)}`,
680
+ {
681
+ method: "PATCH",
682
+ headers: new Headers({
683
+ Authorization: `Bearer ${this.token}`,
684
+ "Vqs-Queue-Name": queueName,
685
+ "Vqs-Consumer-Group": consumerGroup,
686
+ "Vqs-Ticket": ticket,
687
+ "Vqs-Visibility-Timeout": visibilityTimeoutSeconds.toString()
688
+ })
689
+ }
690
+ );
691
+ if (!response.ok) {
692
+ if (response.status === 400) {
693
+ throw new BadRequestError(
694
+ "Missing ticket or invalid visibility timeout"
695
+ );
696
+ }
697
+ if (response.status === 401) {
698
+ throw new UnauthorizedError();
699
+ }
700
+ if (response.status === 403) {
701
+ throw new ForbiddenError();
702
+ }
703
+ if (response.status === 404) {
704
+ throw new MessageNotFoundError(messageId);
705
+ }
706
+ if (response.status === 409) {
707
+ throw new MessageNotAvailableError(
708
+ messageId,
709
+ "Invalid ticket, message not in correct state, or already processed"
710
+ );
711
+ }
712
+ if (response.status >= 500) {
713
+ throw new InternalServerError(
714
+ `Server error: ${response.status} ${response.statusText}`
715
+ );
716
+ }
717
+ throw new Error(
718
+ `Failed to change visibility: ${response.status} ${response.statusText}`
719
+ );
720
+ }
721
+ return { updated: true };
722
+ }
723
+ };
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
+
801
+ // src/consumer-group.ts
802
+ var ConsumerGroup = class {
803
+ client;
804
+ topicName;
805
+ consumerGroupName;
806
+ visibilityTimeout;
807
+ refreshInterval;
808
+ transport;
809
+ /**
810
+ * Create a new ConsumerGroup instance
811
+ * @param client VQSClient instance to use for API calls
812
+ * @param topicName Name of the topic to consume from
813
+ * @param consumerGroupName Name of the consumer group
814
+ * @param options Optional configuration
815
+ */
816
+ constructor(client, topicName, consumerGroupName, options = {}) {
817
+ this.client = client;
818
+ this.topicName = topicName;
819
+ this.consumerGroupName = consumerGroupName;
820
+ this.visibilityTimeout = options.visibilityTimeoutSeconds || 30;
821
+ this.refreshInterval = options.refreshInterval || 10;
822
+ this.transport = options.transport || new JsonTransport();
823
+ }
824
+ /**
825
+ * Starts a background loop that periodically extends the visibility timeout for a message.
826
+ * This prevents the message from becoming visible to other consumers while it's being processed.
827
+ *
828
+ * The extension loop runs every `refreshInterval` seconds and updates the message's
829
+ * visibility timeout to `visibilityTimeout` seconds from the current time.
830
+ *
831
+ * @param messageId - The unique identifier of the message to extend visibility for
832
+ * @param ticket - The receipt ticket that proves ownership of the message
833
+ * @returns A function that when called will stop the extension loop
834
+ *
835
+ * @remarks
836
+ * - The first extension attempt occurs after `refreshInterval` seconds, not immediately
837
+ * - If an extension fails, the loop terminates with an error logged to console
838
+ * - The returned stop function is idempotent - calling it multiple times is safe
839
+ * - By default, the stop function returns immediately without waiting for in-flight
840
+ * - Pass `true` to the stop function to wait for any in-flight extension to complete
841
+ */
842
+ startVisibilityExtension(messageId, ticket) {
843
+ let isRunning = true;
844
+ let resolveLifecycle;
845
+ let timeoutId = null;
846
+ const lifecyclePromise = new Promise((resolve) => {
847
+ resolveLifecycle = resolve;
848
+ });
849
+ const extend = async () => {
850
+ if (!isRunning) {
851
+ resolveLifecycle();
852
+ return;
853
+ }
854
+ try {
855
+ await this.client.changeVisibility({
856
+ queueName: this.topicName,
857
+ consumerGroup: this.consumerGroupName,
858
+ messageId,
859
+ ticket,
860
+ visibilityTimeoutSeconds: this.visibilityTimeout
861
+ });
862
+ if (isRunning) {
863
+ timeoutId = setTimeout(() => extend(), this.refreshInterval * 1e3);
864
+ } else {
865
+ resolveLifecycle();
866
+ }
867
+ } catch (error) {
868
+ console.error(
869
+ `Failed to extend visibility for message ${messageId}:`,
870
+ error
871
+ );
872
+ resolveLifecycle();
873
+ }
874
+ };
875
+ timeoutId = setTimeout(() => extend(), this.refreshInterval * 1e3);
876
+ return async (waitForCompletion = false) => {
877
+ isRunning = false;
878
+ if (timeoutId) {
879
+ clearTimeout(timeoutId);
880
+ timeoutId = null;
881
+ }
882
+ if (waitForCompletion) {
883
+ await lifecyclePromise;
884
+ } else {
885
+ resolveLifecycle();
886
+ }
887
+ };
888
+ }
889
+ /**
890
+ * Process a single message with the given handler
891
+ * @param message The message to process
892
+ * @param handler Function to process the message
893
+ */
894
+ async processMessage(message, handler) {
895
+ const stopExtension = this.startVisibilityExtension(
896
+ message.messageId,
897
+ message.ticket
898
+ );
899
+ try {
900
+ const result = await handler(message);
901
+ await stopExtension();
902
+ if (result && "timeoutSeconds" in result) {
903
+ await this.client.changeVisibility({
904
+ queueName: this.topicName,
905
+ consumerGroup: this.consumerGroupName,
906
+ messageId: message.messageId,
907
+ ticket: message.ticket,
908
+ visibilityTimeoutSeconds: result.timeoutSeconds
909
+ });
910
+ } else {
911
+ await this.client.deleteMessage({
912
+ queueName: this.topicName,
913
+ consumerGroup: this.consumerGroupName,
914
+ messageId: message.messageId,
915
+ ticket: message.ticket
916
+ });
917
+ }
918
+ } catch (error) {
919
+ await stopExtension();
920
+ if (this.transport.finalize && message.payload !== void 0 && message.payload !== null) {
921
+ try {
922
+ await this.transport.finalize(message.payload);
923
+ } catch (finalizeError) {
924
+ console.warn("Failed to finalize message payload:", finalizeError);
925
+ }
926
+ }
927
+ throw error;
928
+ }
929
+ }
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(
942
+ {
943
+ queueName: this.topicName,
944
+ consumerGroup: this.consumerGroupName,
945
+ visibilityTimeoutSeconds: this.visibilityTimeout,
946
+ limit: 1
947
+ // Always process one message at a time
948
+ },
949
+ this.transport
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;
1009
+ }
1010
+ }
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
+ }
1143
+ /**
1144
+ * Get the consumer group name
1145
+ */
1146
+ get name() {
1147
+ return this.consumerGroupName;
1148
+ }
1149
+ /**
1150
+ * Get the topic name this consumer group is subscribed to
1151
+ */
1152
+ get topic() {
1153
+ return this.topicName;
1154
+ }
1155
+ };
1156
+
1157
+ // src/topic.ts
1158
+ var Topic = class {
1159
+ client;
1160
+ topicName;
1161
+ transport;
1162
+ /**
1163
+ * Create a new Topic instance
1164
+ * @param client VQSClient instance to use for API calls
1165
+ * @param topicName Name of the topic to work with
1166
+ * @param transport Optional serializer/deserializer for the payload (defaults to JSON)
1167
+ */
1168
+ constructor(client, topicName, transport) {
1169
+ this.client = client;
1170
+ this.topicName = topicName;
1171
+ this.transport = transport || new JsonTransport();
1172
+ }
1173
+ /**
1174
+ * Publish a message to the topic
1175
+ * @param payload The data to publish
1176
+ * @param options Optional publish options
1177
+ * @returns An object containing the message ID
1178
+ * @throws {BadRequestError} When request parameters are invalid
1179
+ * @throws {UnauthorizedError} When authentication fails
1180
+ * @throws {ForbiddenError} When access is denied (environment mismatch)
1181
+ * @throws {InternalServerError} When server encounters an error
1182
+ */
1183
+ async publish(payload, options) {
1184
+ const result = await this.client.sendMessage(
1185
+ {
1186
+ queueName: this.topicName,
1187
+ payload,
1188
+ idempotencyKey: options?.idempotencyKey,
1189
+ retentionSeconds: options?.retentionSeconds,
1190
+ callbacks: options?.callbacks
1191
+ },
1192
+ this.transport
1193
+ );
1194
+ return { messageId: result.messageId };
1195
+ }
1196
+ /**
1197
+ * Create a consumer group for this topic
1198
+ * @param consumerGroupName Name of the consumer group
1199
+ * @param options Optional configuration for the consumer group
1200
+ * @returns A ConsumerGroup instance
1201
+ */
1202
+ consumerGroup(consumerGroupName, options) {
1203
+ const consumerOptions = {
1204
+ ...options,
1205
+ transport: options?.transport || this.transport
1206
+ };
1207
+ return new ConsumerGroup(
1208
+ this.client,
1209
+ this.topicName,
1210
+ consumerGroupName,
1211
+ consumerOptions
1212
+ );
1213
+ }
1214
+ /**
1215
+ * Get the topic name
1216
+ */
1217
+ get name() {
1218
+ return this.topicName;
1219
+ }
1220
+ /**
1221
+ * Get the transport used by this topic
1222
+ */
1223
+ get serializer() {
1224
+ return this.transport;
1225
+ }
1226
+ };
1227
+
1228
+ // src/factory.ts
1229
+ function createTopic(client, topicName, transport) {
1230
+ return new Topic(client, topicName, transport);
1231
+ }
1232
+
1233
+ // src/callback.ts
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 VQS callback headers: ${missingHeaders.join(", ")}`
1246
+ );
1247
+ }
1248
+ return {
1249
+ messageId,
1250
+ queueName,
1251
+ consumerGroup
1252
+ };
1253
+ }
1254
+ export {
1255
+ BadRequestError,
1256
+ BufferTransport,
1257
+ ConsumerGroup,
1258
+ FailedDependencyError,
1259
+ FifoOrderingViolationError,
1260
+ ForbiddenError,
1261
+ InternalServerError,
1262
+ InvalidCallbackError,
1263
+ InvalidLimitError,
1264
+ JsonTransport,
1265
+ MessageCorruptedError,
1266
+ MessageLockedError,
1267
+ MessageNotAvailableError,
1268
+ MessageNotFoundError,
1269
+ QueueEmptyError,
1270
+ StreamTransport,
1271
+ Topic,
1272
+ UnauthorizedError,
1273
+ VQSClient,
1274
+ createTopic,
1275
+ getVercelOidcToken,
1276
+ parseCallbackRequest
1277
+ };
1278
+ //# sourceMappingURL=index.mjs.map