@upstash/qstash 2.6.2 → 2.6.3

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/index.mjs CHANGED
@@ -1,954 +1,22 @@
1
+ import {
2
+ Chat,
3
+ Client,
4
+ Messages,
5
+ QstashChatRatelimitError,
6
+ QstashDailyRatelimitError,
7
+ QstashError,
8
+ QstashRatelimitError,
9
+ Schedules,
10
+ UrlGroups,
11
+ analyticsBaseUrlMap,
12
+ custom,
13
+ openai,
14
+ upstash
15
+ } from "./chunk-PTZPACVC.mjs";
1
16
  import {
2
17
  Receiver,
3
18
  SignatureError
4
19
  } from "./chunk-CP4IU45K.mjs";
5
-
6
- // src/client/dlq.ts
7
- var DLQ = class {
8
- http;
9
- constructor(http) {
10
- this.http = http;
11
- }
12
- /**
13
- * List messages in the dlq
14
- */
15
- async listMessages(options) {
16
- const filterPayload = {
17
- ...options?.filter,
18
- topicName: options?.filter?.urlGroup
19
- };
20
- const messagesPayload = await this.http.request({
21
- method: "GET",
22
- path: ["v2", "dlq"],
23
- query: {
24
- cursor: options?.cursor,
25
- count: options?.count,
26
- ...filterPayload
27
- }
28
- });
29
- return {
30
- messages: messagesPayload.messages.map((message) => {
31
- return {
32
- ...message,
33
- urlGroup: message.topicName
34
- };
35
- }),
36
- cursor: messagesPayload.cursor
37
- };
38
- }
39
- /**
40
- * Remove a message from the dlq using it's `dlqId`
41
- */
42
- async delete(dlqMessageId) {
43
- return await this.http.request({
44
- method: "DELETE",
45
- path: ["v2", "dlq", dlqMessageId],
46
- parseResponseAsJson: false
47
- // there is no response
48
- });
49
- }
50
- /**
51
- * Remove multiple messages from the dlq using their `dlqId`s
52
- */
53
- async deleteMany(request) {
54
- return await this.http.request({
55
- method: "DELETE",
56
- path: ["v2", "dlq"],
57
- headers: { "Content-Type": "application/json" },
58
- body: JSON.stringify({ dlqIds: request.dlqIds })
59
- });
60
- }
61
- };
62
-
63
- // src/client/error.ts
64
- var QstashError = class extends Error {
65
- constructor(message) {
66
- super(message);
67
- this.name = "QstashError";
68
- }
69
- };
70
- var QstashRatelimitError = class extends QstashError {
71
- limit;
72
- remaining;
73
- reset;
74
- constructor(args) {
75
- super(`Exceeded burst rate limit. ${JSON.stringify(args)} `);
76
- this.limit = args.limit;
77
- this.remaining = args.remaining;
78
- this.reset = args.reset;
79
- }
80
- };
81
- var QstashChatRatelimitError = class extends QstashError {
82
- limitRequests;
83
- limitTokens;
84
- remainingRequests;
85
- remainingTokens;
86
- resetRequests;
87
- resetTokens;
88
- constructor(args) {
89
- super(`Exceeded chat rate limit. ${JSON.stringify(args)} `);
90
- this.limitRequests = args["limit-requests"];
91
- this.limitTokens = args["limit-tokens"];
92
- this.remainingRequests = args["remaining-requests"];
93
- this.remainingTokens = args["remaining-tokens"];
94
- this.resetRequests = args["reset-requests"];
95
- this.resetTokens = args["reset-tokens"];
96
- }
97
- };
98
- var QstashDailyRatelimitError = class extends QstashError {
99
- limit;
100
- remaining;
101
- reset;
102
- constructor(args) {
103
- super(`Exceeded daily rate limit. ${JSON.stringify(args)} `);
104
- this.limit = args.limit;
105
- this.remaining = args.remaining;
106
- this.reset = args.reset;
107
- }
108
- };
109
-
110
- // src/client/http.ts
111
- var HttpClient = class {
112
- baseUrl;
113
- authorization;
114
- options;
115
- retry;
116
- constructor(config) {
117
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
118
- this.authorization = config.authorization;
119
- this.retry = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
120
- typeof config.retry === "boolean" && !config.retry ? {
121
- attempts: 1,
122
- backoff: () => 0
123
- } : {
124
- attempts: config.retry?.retries ? config.retry.retries + 1 : 5,
125
- backoff: config.retry?.backoff ?? ((retryCount) => Math.exp(retryCount) * 50)
126
- };
127
- }
128
- async request(request) {
129
- const { response } = await this.requestWithBackoff(request);
130
- if (request.parseResponseAsJson === false) {
131
- return void 0;
132
- }
133
- return await response.json();
134
- }
135
- async *requestStream(request) {
136
- const { response } = await this.requestWithBackoff(request);
137
- if (!response.body) {
138
- throw new Error("No response body");
139
- }
140
- const body = response.body;
141
- const reader = body.getReader();
142
- const decoder = new TextDecoder();
143
- try {
144
- while (true) {
145
- const { done, value } = await reader.read();
146
- if (done) {
147
- break;
148
- }
149
- const chunkText = decoder.decode(value, { stream: true });
150
- const chunks = chunkText.split("\n").filter(Boolean);
151
- for (const chunk of chunks) {
152
- if (chunk.startsWith("data: ")) {
153
- const data = chunk.slice(6);
154
- if (data === "[DONE]") {
155
- break;
156
- }
157
- yield JSON.parse(data);
158
- }
159
- }
160
- }
161
- } finally {
162
- await reader.cancel();
163
- }
164
- }
165
- requestWithBackoff = async (request) => {
166
- const [url, requestOptions] = this.processRequest(request);
167
- let response = void 0;
168
- let error = void 0;
169
- for (let index = 0; index < this.retry.attempts; index++) {
170
- try {
171
- response = await fetch(url.toString(), requestOptions);
172
- break;
173
- } catch (error_) {
174
- error = error_;
175
- await new Promise((r) => setTimeout(r, this.retry.backoff(index)));
176
- }
177
- }
178
- if (!response) {
179
- throw error ?? new Error("Exhausted all retries");
180
- }
181
- await this.checkResponse(response);
182
- return {
183
- response,
184
- error
185
- };
186
- };
187
- processRequest = (request) => {
188
- const headers = new Headers(request.headers);
189
- if (!headers.has("Authorization")) {
190
- headers.set("Authorization", this.authorization);
191
- }
192
- const requestOptions = {
193
- method: request.method,
194
- headers,
195
- body: request.body,
196
- keepalive: request.keepalive
197
- };
198
- const url = new URL([request.baseUrl ?? this.baseUrl, ...request.path].join("/"));
199
- if (request.query) {
200
- for (const [key, value] of Object.entries(request.query)) {
201
- if (value !== void 0) {
202
- url.searchParams.set(key, value.toString());
203
- }
204
- }
205
- }
206
- return [url.toString(), requestOptions];
207
- };
208
- async checkResponse(response) {
209
- if (response.status === 429) {
210
- if (response.headers.get("x-ratelimit-limit-requests")) {
211
- throw new QstashChatRatelimitError({
212
- "limit-requests": response.headers.get("x-ratelimit-limit-requests"),
213
- "limit-tokens": response.headers.get("x-ratelimit-limit-tokens"),
214
- "remaining-requests": response.headers.get("x-ratelimit-remaining-requests"),
215
- "remaining-tokens": response.headers.get("x-ratelimit-remaining-tokens"),
216
- "reset-requests": response.headers.get("x-ratelimit-reset-requests"),
217
- "reset-tokens": response.headers.get("x-ratelimit-reset-tokens")
218
- });
219
- } else if (response.headers.get("RateLimit-Limit")) {
220
- throw new QstashDailyRatelimitError({
221
- limit: response.headers.get("RateLimit-Limit"),
222
- remaining: response.headers.get("RateLimit-Remaining"),
223
- reset: response.headers.get("RateLimit-Reset")
224
- });
225
- }
226
- throw new QstashRatelimitError({
227
- limit: response.headers.get("Burst-RateLimit-Limit"),
228
- remaining: response.headers.get("Burst-RateLimit-Remaining"),
229
- reset: response.headers.get("Burst-RateLimit-Reset")
230
- });
231
- }
232
- if (response.status < 200 || response.status >= 300) {
233
- const body = await response.text();
234
- throw new QstashError(body.length > 0 ? body : `Error: status=${response.status}`);
235
- }
236
- }
237
- };
238
-
239
- // src/client/llm/chat.ts
240
- var Chat = class _Chat {
241
- http;
242
- token;
243
- constructor(http, token) {
244
- this.http = http;
245
- this.token = token;
246
- }
247
- static toChatRequest(request) {
248
- const messages = [];
249
- messages.push(
250
- { role: "system", content: request.system },
251
- { role: "user", content: request.user }
252
- );
253
- const chatRequest = { ...request, messages };
254
- return chatRequest;
255
- }
256
- /**
257
- * Calls the Upstash completions api given a ChatRequest.
258
- *
259
- * Returns a ChatCompletion or a stream of ChatCompletionChunks
260
- * if stream is enabled.
261
- *
262
- * @param request ChatRequest with messages
263
- * @returns Chat completion or stream
264
- */
265
- create = async (request) => {
266
- if (request.provider.owner != "upstash")
267
- return this.createThirdParty(request);
268
- const body = JSON.stringify(request);
269
- if ("stream" in request && request.stream) {
270
- return this.http.requestStream({
271
- path: ["llm", "v1", "chat", "completions"],
272
- method: "POST",
273
- headers: {
274
- "Content-Type": "application/json",
275
- Connection: "keep-alive",
276
- Accept: "text/event-stream",
277
- "Cache-Control": "no-cache",
278
- Authorization: `Bearer ${this.token}`
279
- },
280
- body
281
- });
282
- }
283
- return this.http.request({
284
- path: ["llm", "v1", "chat", "completions"],
285
- method: "POST",
286
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.token}` },
287
- body
288
- });
289
- };
290
- /**
291
- * Calls the Upstash completions api given a ChatRequest.
292
- *
293
- * Returns a ChatCompletion or a stream of ChatCompletionChunks
294
- * if stream is enabled.
295
- *
296
- * @param request ChatRequest with messages
297
- * @returns Chat completion or stream
298
- */
299
- createThirdParty = async (request) => {
300
- const { baseUrl, token, owner } = request.provider;
301
- if (owner === "upstash")
302
- throw new Error("Upstash is not 3rd party provider!");
303
- delete request.provider;
304
- delete request.system;
305
- const body = JSON.stringify(request);
306
- if ("stream" in request && request.stream) {
307
- return this.http.requestStream({
308
- path: ["v1", "chat", "completions"],
309
- method: "POST",
310
- headers: {
311
- "Content-Type": "application/json",
312
- Connection: "keep-alive",
313
- Accept: "text/event-stream",
314
- "Cache-Control": "no-cache",
315
- Authorization: `Bearer ${token}`
316
- },
317
- body,
318
- baseUrl
319
- });
320
- }
321
- return this.http.request({
322
- path: ["v1", "chat", "completions"],
323
- method: "POST",
324
- headers: {
325
- "Content-Type": "application/json",
326
- Authorization: `Bearer ${token}`
327
- },
328
- body,
329
- baseUrl
330
- });
331
- };
332
- /**
333
- * Calls the Upstash completions api given a PromptRequest.
334
- *
335
- * Returns a ChatCompletion or a stream of ChatCompletionChunks
336
- * if stream is enabled.
337
- *
338
- * @param request PromptRequest with system and user messages.
339
- * Note that system parameter shouldn't be passed in the case of
340
- * mistralai/Mistral-7B-Instruct-v0.2 model.
341
- * @returns Chat completion or stream
342
- */
343
- prompt = async (request) => {
344
- const chatRequest = _Chat.toChatRequest(request);
345
- return this.create(chatRequest);
346
- };
347
- };
348
-
349
- // src/client/llm/utils.ts
350
- function appendLLMOptionsIfNeeded(request, headers) {
351
- if (request.api?.provider?.owner === "upstash") {
352
- request.api = { name: "llm" };
353
- return;
354
- }
355
- if (request.api && "provider" in request.api) {
356
- const provider = request.api.provider;
357
- if (!provider?.baseUrl)
358
- throw new Error("baseUrl cannot be empty or undefined!");
359
- if (!provider.token)
360
- throw new Error("token cannot be empty or undefined!");
361
- request.url = `${provider.baseUrl}/v1/chat/completions`;
362
- headers.set("Authorization", `Bearer ${provider.token}`);
363
- }
364
- }
365
-
366
- // src/client/messages.ts
367
- var Messages = class {
368
- http;
369
- constructor(http) {
370
- this.http = http;
371
- }
372
- /**
373
- * Get a message
374
- */
375
- async get(messageId) {
376
- const messagePayload = await this.http.request({
377
- method: "GET",
378
- path: ["v2", "messages", messageId]
379
- });
380
- const message = {
381
- ...messagePayload,
382
- urlGroup: messagePayload.topicName
383
- };
384
- return message;
385
- }
386
- /**
387
- * Cancel a message
388
- */
389
- async delete(messageId) {
390
- return await this.http.request({
391
- method: "DELETE",
392
- path: ["v2", "messages", messageId],
393
- parseResponseAsJson: false
394
- });
395
- }
396
- async deleteMany(messageIds) {
397
- const result = await this.http.request({
398
- method: "DELETE",
399
- path: ["v2", "messages"],
400
- headers: { "Content-Type": "application/json" },
401
- body: JSON.stringify({ messageIds })
402
- });
403
- return result.cancelled;
404
- }
405
- async deleteAll() {
406
- const result = await this.http.request({
407
- method: "DELETE",
408
- path: ["v2", "messages"]
409
- });
410
- return result.cancelled;
411
- }
412
- };
413
-
414
- // src/client/utils.ts
415
- var isIgnoredHeader = (header) => {
416
- const lowerCaseHeader = header.toLowerCase();
417
- return lowerCaseHeader.startsWith("content-type") || lowerCaseHeader.startsWith("upstash-");
418
- };
419
- function prefixHeaders(headers) {
420
- const keysToBePrefixed = [...headers.keys()].filter((key) => !isIgnoredHeader(key));
421
- for (const key of keysToBePrefixed) {
422
- const value = headers.get(key);
423
- if (value !== null) {
424
- headers.set(`Upstash-Forward-${key}`, value);
425
- }
426
- headers.delete(key);
427
- }
428
- return headers;
429
- }
430
- function processHeaders(request) {
431
- const headers = prefixHeaders(new Headers(request.headers));
432
- headers.set("Upstash-Method", request.method ?? "POST");
433
- if (request.delay !== void 0) {
434
- headers.set("Upstash-Delay", `${request.delay.toFixed(0)}s`);
435
- }
436
- if (request.notBefore !== void 0) {
437
- headers.set("Upstash-Not-Before", request.notBefore.toFixed(0));
438
- }
439
- if (request.deduplicationId !== void 0) {
440
- headers.set("Upstash-Deduplication-Id", request.deduplicationId);
441
- }
442
- if (request.contentBasedDeduplication !== void 0) {
443
- headers.set("Upstash-Content-Based-Deduplication", "true");
444
- }
445
- if (request.retries !== void 0) {
446
- headers.set("Upstash-Retries", request.retries.toFixed(0));
447
- }
448
- if (request.callback !== void 0) {
449
- headers.set("Upstash-Callback", request.callback);
450
- }
451
- if (request.failureCallback !== void 0) {
452
- headers.set("Upstash-Failure-Callback", request.failureCallback);
453
- }
454
- if (request.timeout !== void 0) {
455
- headers.set("Upstash-Timeout", `${request.timeout}s`);
456
- }
457
- return headers;
458
- }
459
- function getRequestPath(request) {
460
- return request.url ?? request.urlGroup ?? request.topic ?? `api/${request.api?.name}`;
461
- }
462
-
463
- // src/client/queue.ts
464
- var Queue = class {
465
- http;
466
- queueName;
467
- constructor(http, queueName) {
468
- this.http = http;
469
- this.queueName = queueName;
470
- }
471
- /**
472
- * Create or update the queue
473
- */
474
- async upsert(request) {
475
- if (!this.queueName) {
476
- throw new Error("Please provide a queue name to the Queue constructor");
477
- }
478
- const body = {
479
- queueName: this.queueName,
480
- parallelism: request.parallelism ?? 1,
481
- paused: request.paused ?? false
482
- };
483
- await this.http.request({
484
- method: "POST",
485
- path: ["v2", "queues"],
486
- headers: {
487
- "Content-Type": "application/json"
488
- },
489
- body: JSON.stringify(body),
490
- parseResponseAsJson: false
491
- });
492
- }
493
- /**
494
- * Get the queue details
495
- */
496
- async get() {
497
- if (!this.queueName) {
498
- throw new Error("Please provide a queue name to the Queue constructor");
499
- }
500
- return await this.http.request({
501
- method: "GET",
502
- path: ["v2", "queues", this.queueName]
503
- });
504
- }
505
- /**
506
- * List queues
507
- */
508
- async list() {
509
- return await this.http.request({
510
- method: "GET",
511
- path: ["v2", "queues"]
512
- });
513
- }
514
- /**
515
- * Delete the queue
516
- */
517
- async delete() {
518
- if (!this.queueName) {
519
- throw new Error("Please provide a queue name to the Queue constructor");
520
- }
521
- await this.http.request({
522
- method: "DELETE",
523
- path: ["v2", "queues", this.queueName],
524
- parseResponseAsJson: false
525
- });
526
- }
527
- /**
528
- * Enqueue a message to a queue.
529
- */
530
- async enqueue(request) {
531
- if (!this.queueName) {
532
- throw new Error("Please provide a queue name to the Queue constructor");
533
- }
534
- const headers = processHeaders(request);
535
- const destination = getRequestPath(request);
536
- const response = await this.http.request({
537
- path: ["v2", "enqueue", this.queueName, destination],
538
- body: request.body,
539
- headers,
540
- method: "POST"
541
- });
542
- return response;
543
- }
544
- /**
545
- * Enqueue a message to a queue, serializing the body to JSON.
546
- */
547
- async enqueueJSON(request) {
548
- const headers = prefixHeaders(new Headers(request.headers));
549
- headers.set("Content-Type", "application/json");
550
- appendLLMOptionsIfNeeded(request, headers);
551
- const response = await this.enqueue({
552
- ...request,
553
- body: JSON.stringify(request.body),
554
- headers
555
- });
556
- return response;
557
- }
558
- /**
559
- * Pauses the queue.
560
- *
561
- * A paused queue will not deliver messages until
562
- * it is resumed.
563
- */
564
- async pause() {
565
- if (!this.queueName) {
566
- throw new Error("Please provide a queue name to the Queue constructor");
567
- }
568
- await this.http.request({
569
- method: "POST",
570
- path: ["v2", "queues", this.queueName, "pause"],
571
- parseResponseAsJson: false
572
- });
573
- }
574
- /**
575
- * Resumes the queue.
576
- */
577
- async resume() {
578
- if (!this.queueName) {
579
- throw new Error("Please provide a queue name to the Queue constructor");
580
- }
581
- await this.http.request({
582
- method: "POST",
583
- path: ["v2", "queues", this.queueName, "resume"],
584
- parseResponseAsJson: false
585
- });
586
- }
587
- };
588
-
589
- // src/client/schedules.ts
590
- var Schedules = class {
591
- http;
592
- constructor(http) {
593
- this.http = http;
594
- }
595
- /**
596
- * Create a schedule
597
- */
598
- async create(request) {
599
- const headers = prefixHeaders(new Headers(request.headers));
600
- if (!headers.has("Content-Type")) {
601
- headers.set("Content-Type", "application/json");
602
- }
603
- headers.set("Upstash-Cron", request.cron);
604
- if (request.method !== void 0) {
605
- headers.set("Upstash-Method", request.method);
606
- }
607
- if (request.delay !== void 0) {
608
- headers.set("Upstash-Delay", `${request.delay.toFixed(0)}s`);
609
- }
610
- if (request.retries !== void 0) {
611
- headers.set("Upstash-Retries", request.retries.toFixed(0));
612
- }
613
- if (request.callback !== void 0) {
614
- headers.set("Upstash-Callback", request.callback);
615
- }
616
- if (request.failureCallback !== void 0) {
617
- headers.set("Upstash-Failure-Callback", request.failureCallback);
618
- }
619
- if (request.timeout !== void 0) {
620
- headers.set("Upstash-Timeout", `${request.timeout}s`);
621
- }
622
- return await this.http.request({
623
- method: "POST",
624
- headers,
625
- path: ["v2", "schedules", request.destination],
626
- body: request.body
627
- });
628
- }
629
- /**
630
- * Get a schedule
631
- */
632
- async get(scheduleId) {
633
- return await this.http.request({
634
- method: "GET",
635
- path: ["v2", "schedules", scheduleId]
636
- });
637
- }
638
- /**
639
- * List your schedules
640
- */
641
- async list() {
642
- return await this.http.request({
643
- method: "GET",
644
- path: ["v2", "schedules"]
645
- });
646
- }
647
- /**
648
- * Delete a schedule
649
- */
650
- async delete(scheduleId) {
651
- return await this.http.request({
652
- method: "DELETE",
653
- path: ["v2", "schedules", scheduleId],
654
- parseResponseAsJson: false
655
- });
656
- }
657
- /**
658
- * Pauses the schedule.
659
- *
660
- * A paused schedule will not deliver messages until
661
- * it is resumed.
662
- */
663
- async pause({ schedule }) {
664
- await this.http.request({
665
- method: "PATCH",
666
- path: ["v2", "schedules", schedule, "pause"],
667
- parseResponseAsJson: false
668
- });
669
- }
670
- /**
671
- * Resumes the schedule.
672
- */
673
- async resume({ schedule }) {
674
- await this.http.request({
675
- method: "PATCH",
676
- path: ["v2", "schedules", schedule, "resume"],
677
- parseResponseAsJson: false
678
- });
679
- }
680
- };
681
-
682
- // src/client/url-groups.ts
683
- var UrlGroups = class {
684
- http;
685
- constructor(http) {
686
- this.http = http;
687
- }
688
- /**
689
- * Create a new url group with the given name and endpoints
690
- */
691
- async addEndpoints(request) {
692
- await this.http.request({
693
- method: "POST",
694
- path: ["v2", "topics", request.name, "endpoints"],
695
- headers: { "Content-Type": "application/json" },
696
- body: JSON.stringify({ endpoints: request.endpoints }),
697
- parseResponseAsJson: false
698
- });
699
- }
700
- /**
701
- * Remove endpoints from a url group.
702
- */
703
- async removeEndpoints(request) {
704
- await this.http.request({
705
- method: "DELETE",
706
- path: ["v2", "topics", request.name, "endpoints"],
707
- headers: { "Content-Type": "application/json" },
708
- body: JSON.stringify({ endpoints: request.endpoints }),
709
- parseResponseAsJson: false
710
- });
711
- }
712
- /**
713
- * Get a list of all url groups.
714
- */
715
- async list() {
716
- return await this.http.request({
717
- method: "GET",
718
- path: ["v2", "topics"]
719
- });
720
- }
721
- /**
722
- * Get a single url group
723
- */
724
- async get(name) {
725
- return await this.http.request({
726
- method: "GET",
727
- path: ["v2", "topics", name]
728
- });
729
- }
730
- /**
731
- * Delete a url group
732
- */
733
- async delete(name) {
734
- return await this.http.request({
735
- method: "DELETE",
736
- path: ["v2", "topics", name],
737
- parseResponseAsJson: false
738
- });
739
- }
740
- };
741
-
742
- // src/client/client.ts
743
- var Client = class {
744
- http;
745
- token;
746
- constructor(config) {
747
- this.http = new HttpClient({
748
- retry: config.retry,
749
- baseUrl: config.baseUrl ? config.baseUrl.replace(/\/$/, "") : "https://qstash.upstash.io",
750
- authorization: `Bearer ${config.token}`
751
- });
752
- this.token = config.token;
753
- }
754
- /**
755
- * Access the urlGroup API.
756
- *
757
- * Create, read, update or delete urlGroups.
758
- */
759
- get urlGroups() {
760
- return new UrlGroups(this.http);
761
- }
762
- /**
763
- * Deprecated. Use urlGroups instead.
764
- *
765
- * Access the topic API.
766
- *
767
- * Create, read, update or delete topics.
768
- */
769
- get topics() {
770
- return this.urlGroups;
771
- }
772
- /**
773
- * Access the dlq API.
774
- *
775
- * List or remove messages from the DLQ.
776
- */
777
- get dlq() {
778
- return new DLQ(this.http);
779
- }
780
- /**
781
- * Access the message API.
782
- *
783
- * Read or cancel messages.
784
- */
785
- get messages() {
786
- return new Messages(this.http);
787
- }
788
- /**
789
- * Access the schedule API.
790
- *
791
- * Create, read or delete schedules.
792
- */
793
- get schedules() {
794
- return new Schedules(this.http);
795
- }
796
- /**
797
- * Access the queue API.
798
- *
799
- * Create, read, update or delete queues.
800
- */
801
- queue(request) {
802
- return new Queue(this.http, request?.queueName);
803
- }
804
- /**
805
- * Access the Chat API
806
- *
807
- * Call the create or prompt methods
808
- */
809
- chat() {
810
- return new Chat(this.http, this.token);
811
- }
812
- async publish(request) {
813
- const headers = processHeaders(request);
814
- const response = await this.http.request({
815
- path: ["v2", "publish", getRequestPath(request)],
816
- body: request.body,
817
- headers,
818
- method: "POST"
819
- });
820
- return response;
821
- }
822
- /**
823
- * publishJSON is a utility wrapper around `publish` that automatically serializes the body
824
- * and sets the `Content-Type` header to `application/json`.
825
- */
826
- async publishJSON(request) {
827
- const headers = prefixHeaders(new Headers(request.headers));
828
- headers.set("Content-Type", "application/json");
829
- appendLLMOptionsIfNeeded(request, headers);
830
- const response = await this.publish({
831
- ...request,
832
- headers,
833
- body: JSON.stringify(request.body)
834
- });
835
- return response;
836
- }
837
- /**
838
- * Batch publish messages to QStash.
839
- */
840
- async batch(request) {
841
- const messages = [];
842
- for (const message of request) {
843
- const headers = processHeaders(message);
844
- const headerEntries = Object.fromEntries(headers.entries());
845
- messages.push({
846
- destination: getRequestPath(message),
847
- headers: headerEntries,
848
- body: message.body,
849
- ...message.queueName && { queue: message.queueName }
850
- });
851
- }
852
- const response = await this.http.request({
853
- path: ["v2", "batch"],
854
- body: JSON.stringify(messages),
855
- headers: {
856
- "Content-Type": "application/json"
857
- },
858
- method: "POST"
859
- });
860
- return response;
861
- }
862
- /**
863
- * Batch publish messages to QStash, serializing each body to JSON.
864
- */
865
- async batchJSON(request) {
866
- for (const message of request) {
867
- if ("body" in message) {
868
- message.body = JSON.stringify(message.body);
869
- }
870
- message.headers = new Headers(message.headers);
871
- appendLLMOptionsIfNeeded(message, message.headers);
872
- message.headers.set("Content-Type", "application/json");
873
- }
874
- const response = await this.batch(request);
875
- return response;
876
- }
877
- /**
878
- * Retrieve your logs.
879
- *
880
- * The logs endpoint is paginated and returns only 100 logs at a time.
881
- * If you want to receive more logs, you can use the cursor to paginate.
882
- *
883
- * The cursor is a unix timestamp with millisecond precision
884
- *
885
- * @example
886
- * ```ts
887
- * let cursor = Date.now()
888
- * const logs: Log[] = []
889
- * while (cursor > 0) {
890
- * const res = await qstash.logs({ cursor })
891
- * logs.push(...res.logs)
892
- * cursor = res.cursor ?? 0
893
- * }
894
- * ```
895
- */
896
- async events(request) {
897
- const query = {};
898
- if (request?.cursor && request.cursor > 0) {
899
- query.cursor = request.cursor.toString();
900
- }
901
- for (const [key, value] of Object.entries(request?.filter ?? {})) {
902
- if (typeof value === "number" && value < 0) {
903
- continue;
904
- }
905
- if (key === "urlGroup") {
906
- query.topicName = value.toString();
907
- } else if (typeof value !== "undefined") {
908
- query[key] = value.toString();
909
- }
910
- }
911
- const responsePayload = await this.http.request({
912
- path: ["v2", "events"],
913
- method: "GET",
914
- query
915
- });
916
- return {
917
- cursor: responsePayload.cursor,
918
- events: responsePayload.events.map((event) => {
919
- return {
920
- ...event,
921
- urlGroup: event.topicName
922
- };
923
- })
924
- };
925
- }
926
- };
927
-
928
- // src/client/llm/providers.ts
929
- var upstash = () => {
930
- return {
931
- owner: "upstash",
932
- baseUrl: "https://qstash.upstash.io/llm",
933
- token: ""
934
- };
935
- };
936
- var openai = ({
937
- token
938
- }) => {
939
- return { token, owner: "openai", baseUrl: "https://api.openai.com" };
940
- };
941
- var custom = ({
942
- baseUrl,
943
- token
944
- }) => {
945
- const trimmedBaseUrl = baseUrl.replace(/\/(v1\/)?chat\/completions$/, "");
946
- return {
947
- token,
948
- owner: "custom",
949
- baseUrl: trimmedBaseUrl
950
- };
951
- };
952
20
  export {
953
21
  Chat,
954
22
  Client,
@@ -961,6 +29,7 @@ export {
961
29
  Schedules,
962
30
  SignatureError,
963
31
  UrlGroups,
32
+ analyticsBaseUrlMap,
964
33
  custom,
965
34
  openai,
966
35
  upstash