@upstash/qstash 2.6.2 → 2.6.4-workflow-alpha.0

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.
@@ -1,7 +1,482 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2;// src/receiver.ts
2
+ var _jose = require('jose'); var jose = _interopRequireWildcard(_jose);
3
+ var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);
4
+ var SignatureError = class extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "SignatureError";
8
+ }
9
+ };
10
+ var Receiver = class {
11
+
12
+
13
+ constructor(config) {
14
+ this.currentSigningKey = config.currentSigningKey;
15
+ this.nextSigningKey = config.nextSigningKey;
16
+ }
17
+ /**
18
+ * Verify the signature of a request.
19
+ *
20
+ * Tries to verify the signature with the current signing key.
21
+ * If that fails, maybe because you have rotated the keys recently, it will
22
+ * try to verify the signature with the next signing key.
23
+ *
24
+ * If that fails, the signature is invalid and a `SignatureError` is thrown.
25
+ */
26
+ async verify(request) {
27
+ const isValid = await this.verifyWithKey(this.currentSigningKey, request);
28
+ if (isValid) {
29
+ return true;
30
+ }
31
+ return this.verifyWithKey(this.nextSigningKey, request);
32
+ }
33
+ /**
34
+ * Verify signature with a specific signing key
35
+ */
36
+ async verifyWithKey(key, request) {
37
+ const jwt = await jose.jwtVerify(request.signature, new TextEncoder().encode(key), {
38
+ issuer: "Upstash",
39
+ clockTolerance: request.clockTolerance
40
+ }).catch((error) => {
41
+ throw new SignatureError(error.message);
42
+ });
43
+ const p = jwt.payload;
44
+ if (request.url !== void 0 && p.sub !== request.url) {
45
+ throw new SignatureError(`invalid subject: ${p.sub}, want: ${request.url}`);
46
+ }
47
+ const bodyHash = _cryptojs2.default.SHA256(request.body).toString(_cryptojs2.default.enc.Base64url);
48
+ const padding = new RegExp(/=+$/);
49
+ if (p.body.replace(padding, "") !== bodyHash.replace(padding, "")) {
50
+ throw new SignatureError(`body hash does not match, want: ${p.body}, got: ${bodyHash}`);
51
+ }
52
+ return true;
53
+ }
54
+ };
55
+
56
+ // src/client/error.ts
57
+ var QstashError = class extends Error {
58
+ constructor(message) {
59
+ super(message);
60
+ this.name = "QstashError";
61
+ }
62
+ };
63
+ var QstashRatelimitError = class extends QstashError {
64
+
65
+
66
+
67
+ constructor(args) {
68
+ super(`Exceeded burst rate limit. ${JSON.stringify(args)} `);
69
+ this.name = "QstashRatelimitError";
70
+ this.limit = args.limit;
71
+ this.remaining = args.remaining;
72
+ this.reset = args.reset;
73
+ }
74
+ };
75
+ var QstashChatRatelimitError = class extends QstashError {
76
+
77
+
78
+
79
+
80
+
81
+
82
+ constructor(args) {
83
+ super(`Exceeded chat rate limit. ${JSON.stringify(args)} `);
84
+ this.limitRequests = args["limit-requests"];
85
+ this.limitTokens = args["limit-tokens"];
86
+ this.remainingRequests = args["remaining-requests"];
87
+ this.remainingTokens = args["remaining-tokens"];
88
+ this.resetRequests = args["reset-requests"];
89
+ this.resetTokens = args["reset-tokens"];
90
+ }
91
+ };
92
+ var QstashDailyRatelimitError = class extends QstashError {
93
+
94
+
95
+
96
+ constructor(args) {
97
+ super(`Exceeded daily rate limit. ${JSON.stringify(args)} `);
98
+ this.limit = args.limit;
99
+ this.remaining = args.remaining;
100
+ this.reset = args.reset;
101
+ this.name = "QstashChatRatelimitError";
102
+ }
103
+ };
104
+ var QstashWorkflowError = class extends QstashError {
105
+ constructor(message) {
106
+ super(message);
107
+ this.name = "QstashWorkflowError";
108
+ }
109
+ };
110
+ var QstashWorkflowAbort = class extends Error {
111
+
112
+
113
+ constructor(stepName, stepInfo) {
114
+ super(`Aborting workflow after executing step '${stepName}'.`);
115
+ this.name = "QstashWorkflowAbort";
116
+ this.stepName = stepName;
117
+ this.stepInfo = stepInfo;
118
+ }
119
+ };
120
+
121
+ // src/client/llm/chat.ts
122
+ var Chat = (_class = class _Chat {
123
+
124
+
125
+ constructor(http, token) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);
126
+ this.http = http;
127
+ this.token = token;
128
+ }
129
+ static toChatRequest(request) {
130
+ const messages = [];
131
+ messages.push(
132
+ { role: "system", content: request.system },
133
+ { role: "user", content: request.user }
134
+ );
135
+ const chatRequest = { ...request, messages };
136
+ return chatRequest;
137
+ }
138
+ /**
139
+ * Calls the Upstash completions api given a ChatRequest.
140
+ *
141
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
142
+ * if stream is enabled.
143
+ *
144
+ * @param request ChatRequest with messages
145
+ * @returns Chat completion or stream
146
+ */
147
+ __init() {this.create = async (request) => {
148
+ if (request.provider.owner != "upstash")
149
+ return this.createThirdParty(request);
150
+ const body = JSON.stringify(request);
151
+ if ("stream" in request && request.stream) {
152
+ return this.http.requestStream({
153
+ path: ["llm", "v1", "chat", "completions"],
154
+ method: "POST",
155
+ headers: {
156
+ "Content-Type": "application/json",
157
+ Connection: "keep-alive",
158
+ Accept: "text/event-stream",
159
+ "Cache-Control": "no-cache",
160
+ Authorization: `Bearer ${this.token}`
161
+ },
162
+ body
163
+ });
164
+ }
165
+ return this.http.request({
166
+ path: ["llm", "v1", "chat", "completions"],
167
+ method: "POST",
168
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.token}` },
169
+ body
170
+ });
171
+ }}
172
+ /**
173
+ * Calls the Upstash completions api given a ChatRequest.
174
+ *
175
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
176
+ * if stream is enabled.
177
+ *
178
+ * @param request ChatRequest with messages
179
+ * @returns Chat completion or stream
180
+ */
181
+ __init2() {this.createThirdParty = async (request) => {
182
+ const { baseUrl, token, owner } = request.provider;
183
+ if (owner === "upstash")
184
+ throw new Error("Upstash is not 3rd party provider!");
185
+ delete request.provider;
186
+ delete request.system;
187
+ const body = JSON.stringify(request);
188
+ if ("stream" in request && request.stream) {
189
+ return this.http.requestStream({
190
+ path: ["v1", "chat", "completions"],
191
+ method: "POST",
192
+ headers: {
193
+ "Content-Type": "application/json",
194
+ Connection: "keep-alive",
195
+ Accept: "text/event-stream",
196
+ "Cache-Control": "no-cache",
197
+ Authorization: `Bearer ${token}`
198
+ },
199
+ body,
200
+ baseUrl
201
+ });
202
+ }
203
+ return this.http.request({
204
+ path: ["v1", "chat", "completions"],
205
+ method: "POST",
206
+ headers: {
207
+ "Content-Type": "application/json",
208
+ Authorization: `Bearer ${token}`
209
+ },
210
+ body,
211
+ baseUrl
212
+ });
213
+ }}
214
+ /**
215
+ * Calls the Upstash completions api given a PromptRequest.
216
+ *
217
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
218
+ * if stream is enabled.
219
+ *
220
+ * @param request PromptRequest with system and user messages.
221
+ * Note that system parameter shouldn't be passed in the case of
222
+ * mistralai/Mistral-7B-Instruct-v0.2 model.
223
+ * @returns Chat completion or stream
224
+ */
225
+ __init3() {this.prompt = async (request) => {
226
+ const chatRequest = _Chat.toChatRequest(request);
227
+ return this.create(chatRequest);
228
+ }}
229
+ }, _class);
230
+
231
+ // src/client/messages.ts
232
+ var Messages = class {
233
+
234
+ constructor(http) {
235
+ this.http = http;
236
+ }
237
+ /**
238
+ * Get a message
239
+ */
240
+ async get(messageId) {
241
+ const messagePayload = await this.http.request({
242
+ method: "GET",
243
+ path: ["v2", "messages", messageId]
244
+ });
245
+ const message = {
246
+ ...messagePayload,
247
+ urlGroup: messagePayload.topicName
248
+ };
249
+ return message;
250
+ }
251
+ /**
252
+ * Cancel a message
253
+ */
254
+ async delete(messageId) {
255
+ return await this.http.request({
256
+ method: "DELETE",
257
+ path: ["v2", "messages", messageId],
258
+ parseResponseAsJson: false
259
+ });
260
+ }
261
+ async deleteMany(messageIds) {
262
+ const result = await this.http.request({
263
+ method: "DELETE",
264
+ path: ["v2", "messages"],
265
+ headers: { "Content-Type": "application/json" },
266
+ body: JSON.stringify({ messageIds })
267
+ });
268
+ return result.cancelled;
269
+ }
270
+ async deleteAll() {
271
+ const result = await this.http.request({
272
+ method: "DELETE",
273
+ path: ["v2", "messages"]
274
+ });
275
+ return result.cancelled;
276
+ }
277
+ };
278
+
279
+ // src/client/utils.ts
280
+ var isIgnoredHeader = (header) => {
281
+ const lowerCaseHeader = header.toLowerCase();
282
+ return lowerCaseHeader.startsWith("content-type") || lowerCaseHeader.startsWith("upstash-");
283
+ };
284
+ function prefixHeaders(headers) {
285
+ const keysToBePrefixed = [...headers.keys()].filter((key) => !isIgnoredHeader(key));
286
+ for (const key of keysToBePrefixed) {
287
+ const value = headers.get(key);
288
+ if (value !== null) {
289
+ headers.set(`Upstash-Forward-${key}`, value);
290
+ }
291
+ headers.delete(key);
292
+ }
293
+ return headers;
294
+ }
295
+ function processHeaders(request) {
296
+ const headers = prefixHeaders(new Headers(request.headers));
297
+ headers.set("Upstash-Method", _nullishCoalesce(request.method, () => ( "POST")));
298
+ if (request.delay !== void 0) {
299
+ headers.set("Upstash-Delay", `${request.delay.toFixed(0)}s`);
300
+ }
301
+ if (request.notBefore !== void 0) {
302
+ headers.set("Upstash-Not-Before", request.notBefore.toFixed(0));
303
+ }
304
+ if (request.deduplicationId !== void 0) {
305
+ headers.set("Upstash-Deduplication-Id", request.deduplicationId);
306
+ }
307
+ if (request.contentBasedDeduplication !== void 0) {
308
+ headers.set("Upstash-Content-Based-Deduplication", "true");
309
+ }
310
+ if (request.retries !== void 0) {
311
+ headers.set("Upstash-Retries", request.retries.toFixed(0));
312
+ }
313
+ if (request.callback !== void 0) {
314
+ headers.set("Upstash-Callback", request.callback);
315
+ }
316
+ if (request.failureCallback !== void 0) {
317
+ headers.set("Upstash-Failure-Callback", request.failureCallback);
318
+ }
319
+ if (request.timeout !== void 0) {
320
+ headers.set("Upstash-Timeout", `${request.timeout}s`);
321
+ }
322
+ return headers;
323
+ }
324
+ function getRequestPath(request) {
325
+ return _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(request.url, () => ( request.urlGroup)), () => ( request.topic)), () => ( `api/${_optionalChain([request, 'access', _ => _.api, 'optionalAccess', _2 => _2.name])}`));
326
+ }
2
327
 
328
+ // src/client/schedules.ts
329
+ var Schedules = class {
330
+
331
+ constructor(http) {
332
+ this.http = http;
333
+ }
334
+ /**
335
+ * Create a schedule
336
+ */
337
+ async create(request) {
338
+ const headers = prefixHeaders(new Headers(request.headers));
339
+ if (!headers.has("Content-Type")) {
340
+ headers.set("Content-Type", "application/json");
341
+ }
342
+ headers.set("Upstash-Cron", request.cron);
343
+ if (request.method !== void 0) {
344
+ headers.set("Upstash-Method", request.method);
345
+ }
346
+ if (request.delay !== void 0) {
347
+ headers.set("Upstash-Delay", `${request.delay.toFixed(0)}s`);
348
+ }
349
+ if (request.retries !== void 0) {
350
+ headers.set("Upstash-Retries", request.retries.toFixed(0));
351
+ }
352
+ if (request.callback !== void 0) {
353
+ headers.set("Upstash-Callback", request.callback);
354
+ }
355
+ if (request.failureCallback !== void 0) {
356
+ headers.set("Upstash-Failure-Callback", request.failureCallback);
357
+ }
358
+ if (request.timeout !== void 0) {
359
+ headers.set("Upstash-Timeout", `${request.timeout}s`);
360
+ }
361
+ return await this.http.request({
362
+ method: "POST",
363
+ headers,
364
+ path: ["v2", "schedules", request.destination],
365
+ body: request.body
366
+ });
367
+ }
368
+ /**
369
+ * Get a schedule
370
+ */
371
+ async get(scheduleId) {
372
+ return await this.http.request({
373
+ method: "GET",
374
+ path: ["v2", "schedules", scheduleId]
375
+ });
376
+ }
377
+ /**
378
+ * List your schedules
379
+ */
380
+ async list() {
381
+ return await this.http.request({
382
+ method: "GET",
383
+ path: ["v2", "schedules"]
384
+ });
385
+ }
386
+ /**
387
+ * Delete a schedule
388
+ */
389
+ async delete(scheduleId) {
390
+ return await this.http.request({
391
+ method: "DELETE",
392
+ path: ["v2", "schedules", scheduleId],
393
+ parseResponseAsJson: false
394
+ });
395
+ }
396
+ /**
397
+ * Pauses the schedule.
398
+ *
399
+ * A paused schedule will not deliver messages until
400
+ * it is resumed.
401
+ */
402
+ async pause({ schedule }) {
403
+ await this.http.request({
404
+ method: "PATCH",
405
+ path: ["v2", "schedules", schedule, "pause"],
406
+ parseResponseAsJson: false
407
+ });
408
+ }
409
+ /**
410
+ * Resumes the schedule.
411
+ */
412
+ async resume({ schedule }) {
413
+ await this.http.request({
414
+ method: "PATCH",
415
+ path: ["v2", "schedules", schedule, "resume"],
416
+ parseResponseAsJson: false
417
+ });
418
+ }
419
+ };
3
420
 
4
- var _chunkUUR7N6E6js = require('./chunk-UUR7N6E6.js');
421
+ // src/client/url-groups.ts
422
+ var UrlGroups = class {
423
+
424
+ constructor(http) {
425
+ this.http = http;
426
+ }
427
+ /**
428
+ * Create a new url group with the given name and endpoints
429
+ */
430
+ async addEndpoints(request) {
431
+ await this.http.request({
432
+ method: "POST",
433
+ path: ["v2", "topics", request.name, "endpoints"],
434
+ headers: { "Content-Type": "application/json" },
435
+ body: JSON.stringify({ endpoints: request.endpoints }),
436
+ parseResponseAsJson: false
437
+ });
438
+ }
439
+ /**
440
+ * Remove endpoints from a url group.
441
+ */
442
+ async removeEndpoints(request) {
443
+ await this.http.request({
444
+ method: "DELETE",
445
+ path: ["v2", "topics", request.name, "endpoints"],
446
+ headers: { "Content-Type": "application/json" },
447
+ body: JSON.stringify({ endpoints: request.endpoints }),
448
+ parseResponseAsJson: false
449
+ });
450
+ }
451
+ /**
452
+ * Get a list of all url groups.
453
+ */
454
+ async list() {
455
+ return await this.http.request({
456
+ method: "GET",
457
+ path: ["v2", "topics"]
458
+ });
459
+ }
460
+ /**
461
+ * Get a single url group
462
+ */
463
+ async get(name) {
464
+ return await this.http.request({
465
+ method: "GET",
466
+ path: ["v2", "topics", name]
467
+ });
468
+ }
469
+ /**
470
+ * Delete a url group
471
+ */
472
+ async delete(name) {
473
+ return await this.http.request({
474
+ method: "DELETE",
475
+ path: ["v2", "topics", name],
476
+ parseResponseAsJson: false
477
+ });
478
+ }
479
+ };
5
480
 
6
481
  // src/client/dlq.ts
7
482
  var DLQ = class {
@@ -14,15 +489,15 @@ var DLQ = class {
14
489
  */
15
490
  async listMessages(options) {
16
491
  const filterPayload = {
17
- ..._optionalChain([options, 'optionalAccess', _ => _.filter]),
18
- topicName: _optionalChain([options, 'optionalAccess', _2 => _2.filter, 'optionalAccess', _3 => _3.urlGroup])
492
+ ..._optionalChain([options, 'optionalAccess', _3 => _3.filter]),
493
+ topicName: _optionalChain([options, 'optionalAccess', _4 => _4.filter, 'optionalAccess', _5 => _5.urlGroup])
19
494
  };
20
495
  const messagesPayload = await this.http.request({
21
496
  method: "GET",
22
497
  path: ["v2", "dlq"],
23
498
  query: {
24
- cursor: _optionalChain([options, 'optionalAccess', _4 => _4.cursor]),
25
- count: _optionalChain([options, 'optionalAccess', _5 => _5.count]),
499
+ cursor: _optionalChain([options, 'optionalAccess', _6 => _6.cursor]),
500
+ count: _optionalChain([options, 'optionalAccess', _7 => _7.count]),
26
501
  ...filterPayload
27
502
  }
28
503
  });
@@ -60,60 +535,13 @@ var DLQ = class {
60
535
  }
61
536
  };
62
537
 
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
-
72
-
73
-
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
-
83
-
84
-
85
-
86
-
87
-
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
-
100
-
101
-
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
538
  // src/client/http.ts
111
- var HttpClient = (_class = class {
539
+ var HttpClient = (_class2 = class {
112
540
 
113
541
 
114
542
 
115
543
 
116
- constructor(config) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);
544
+ constructor(config) {;_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);
117
545
  this.baseUrl = config.baseUrl.replace(/\/$/, "");
118
546
  this.authorization = config.authorization;
119
547
  this.retry = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
@@ -121,8 +549,8 @@ var HttpClient = (_class = class {
121
549
  attempts: 1,
122
550
  backoff: () => 0
123
551
  } : {
124
- attempts: _optionalChain([config, 'access', _6 => _6.retry, 'optionalAccess', _7 => _7.retries]) ? config.retry.retries + 1 : 5,
125
- backoff: _nullishCoalesce(_optionalChain([config, 'access', _8 => _8.retry, 'optionalAccess', _9 => _9.backoff]), () => ( ((retryCount) => Math.exp(retryCount) * 50)))
552
+ attempts: _optionalChain([config, 'access', _8 => _8.retry, 'optionalAccess', _9 => _9.retries]) ? config.retry.retries + 1 : 5,
553
+ backoff: _nullishCoalesce(_optionalChain([config, 'access', _10 => _10.retry, 'optionalAccess', _11 => _11.backoff]), () => ( ((retryCount) => Math.exp(retryCount) * 50)))
126
554
  };
127
555
  }
128
556
  async request(request) {
@@ -162,7 +590,7 @@ var HttpClient = (_class = class {
162
590
  await reader.cancel();
163
591
  }
164
592
  }
165
- __init() {this.requestWithBackoff = async (request) => {
593
+ __init4() {this.requestWithBackoff = async (request) => {
166
594
  const [url, requestOptions] = this.processRequest(request);
167
595
  let response = void 0;
168
596
  let error = void 0;
@@ -184,7 +612,7 @@ var HttpClient = (_class = class {
184
612
  error
185
613
  };
186
614
  }}
187
- __init2() {this.processRequest = (request) => {
615
+ __init5() {this.processRequest = (request) => {
188
616
  const headers = new Headers(request.headers);
189
617
  if (!headers.has("Authorization")) {
190
618
  headers.set("Authorization", this.authorization);
@@ -230,131 +658,21 @@ var HttpClient = (_class = class {
230
658
  });
231
659
  }
232
660
  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
- }, _class);
238
-
239
- // src/client/llm/chat.ts
240
- var Chat = (_class2 = class _Chat {
241
-
242
-
243
- constructor(http, token) {;_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);
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
- __init3() {this.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
- __init4() {this.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
- __init5() {this.prompt = async (request) => {
344
- const chatRequest = _Chat.toChatRequest(request);
345
- return this.create(chatRequest);
346
- }}
661
+ const body = await response.text();
662
+ throw new QstashError(body.length > 0 ? body : `Error: status=${response.status}`);
663
+ }
664
+ }
347
665
  }, _class2);
348
666
 
349
667
  // src/client/llm/utils.ts
350
668
  function appendLLMOptionsIfNeeded(request, headers) {
351
- if (_optionalChain([request, 'access', _10 => _10.api, 'optionalAccess', _11 => _11.provider, 'optionalAccess', _12 => _12.owner]) === "upstash") {
669
+ if (_optionalChain([request, 'access', _12 => _12.api, 'optionalAccess', _13 => _13.provider, 'optionalAccess', _14 => _14.owner]) === "upstash") {
352
670
  request.api = { name: "llm" };
353
671
  return;
354
672
  }
355
673
  if (request.api && "provider" in request.api) {
356
674
  const provider = request.api.provider;
357
- if (!_optionalChain([provider, 'optionalAccess', _13 => _13.baseUrl]))
675
+ if (!_optionalChain([provider, 'optionalAccess', _15 => _15.baseUrl]))
358
676
  throw new Error("baseUrl cannot be empty or undefined!");
359
677
  if (!provider.token)
360
678
  throw new Error("token cannot be empty or undefined!");
@@ -362,102 +680,10 @@ function appendLLMOptionsIfNeeded(request, headers) {
362
680
  headers.set("Authorization", `Bearer ${provider.token}`);
363
681
  }
364
682
  }
365
-
366
- // src/client/messages.ts
367
- var Messages = class {
368
-
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", _nullishCoalesce(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);
683
+ function ensureCallbackPresent(request) {
684
+ if (_optionalChain([request, 'access', _16 => _16.api, 'optionalAccess', _17 => _17.name]) === "llm" && !request.callback) {
685
+ throw new TypeError("Callback cannot be undefined when using LLM");
441
686
  }
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 _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(request.url, () => ( request.urlGroup)), () => ( request.topic)), () => ( `api/${_optionalChain([request, 'access', _14 => _14.api, 'optionalAccess', _15 => _15.name])}`));
461
687
  }
462
688
 
463
689
  // src/client/queue.ts
@@ -547,6 +773,7 @@ var Queue = class {
547
773
  async enqueueJSON(request) {
548
774
  const headers = prefixHeaders(new Headers(request.headers));
549
775
  headers.set("Content-Type", "application/json");
776
+ ensureCallbackPresent(request);
550
777
  appendLLMOptionsIfNeeded(request, headers);
551
778
  const response = await this.enqueue({
552
779
  ...request,
@@ -586,159 +813,6 @@ var Queue = class {
586
813
  }
587
814
  };
588
815
 
589
- // src/client/schedules.ts
590
- var Schedules = class {
591
-
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
-
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
816
  // src/client/client.ts
743
817
  var Client = class {
744
818
 
@@ -799,7 +873,7 @@ var Client = class {
799
873
  * Create, read, update or delete queues.
800
874
  */
801
875
  queue(request) {
802
- return new Queue(this.http, _optionalChain([request, 'optionalAccess', _16 => _16.queueName]));
876
+ return new Queue(this.http, _optionalChain([request, 'optionalAccess', _18 => _18.queueName]));
803
877
  }
804
878
  /**
805
879
  * Access the Chat API
@@ -826,6 +900,7 @@ var Client = class {
826
900
  async publishJSON(request) {
827
901
  const headers = prefixHeaders(new Headers(request.headers));
828
902
  headers.set("Content-Type", "application/json");
903
+ ensureCallbackPresent(request);
829
904
  appendLLMOptionsIfNeeded(request, headers);
830
905
  const response = await this.publish({
831
906
  ...request,
@@ -857,7 +932,8 @@ var Client = class {
857
932
  },
858
933
  method: "POST"
859
934
  });
860
- return response;
935
+ const arrayResposne = Array.isArray(response) ? response : [response];
936
+ return arrayResposne;
861
937
  }
862
938
  /**
863
939
  * Batch publish messages to QStash, serializing each body to JSON.
@@ -868,6 +944,7 @@ var Client = class {
868
944
  message.body = JSON.stringify(message.body);
869
945
  }
870
946
  message.headers = new Headers(message.headers);
947
+ ensureCallbackPresent(message);
871
948
  appendLLMOptionsIfNeeded(message, message.headers);
872
949
  message.headers.set("Content-Type", "application/json");
873
950
  }
@@ -895,10 +972,10 @@ var Client = class {
895
972
  */
896
973
  async events(request) {
897
974
  const query = {};
898
- if (_optionalChain([request, 'optionalAccess', _17 => _17.cursor]) && request.cursor > 0) {
975
+ if (_optionalChain([request, 'optionalAccess', _19 => _19.cursor]) && request.cursor > 0) {
899
976
  query.cursor = request.cursor.toString();
900
977
  }
901
- for (const [key, value] of Object.entries(_nullishCoalesce(_optionalChain([request, 'optionalAccess', _18 => _18.filter]), () => ( {})))) {
978
+ for (const [key, value] of Object.entries(_nullishCoalesce(_optionalChain([request, 'optionalAccess', _20 => _20.filter]), () => ( {})))) {
902
979
  if (typeof value === "number" && value < 0) {
903
980
  continue;
904
981
  }
@@ -925,31 +1002,6 @@ var Client = class {
925
1002
  }
926
1003
  };
927
1004
 
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
-
953
1005
 
954
1006
 
955
1007
 
@@ -964,4 +1016,4 @@ var custom = ({
964
1016
 
965
1017
 
966
1018
 
967
- exports.Chat = Chat; exports.Client = Client; exports.Messages = Messages; exports.QstashChatRatelimitError = QstashChatRatelimitError; exports.QstashDailyRatelimitError = QstashDailyRatelimitError; exports.QstashError = QstashError; exports.QstashRatelimitError = QstashRatelimitError; exports.Receiver = _chunkUUR7N6E6js.Receiver; exports.Schedules = Schedules; exports.SignatureError = _chunkUUR7N6E6js.SignatureError; exports.UrlGroups = UrlGroups; exports.custom = custom; exports.openai = openai; exports.upstash = upstash;
1019
+ exports.SignatureError = SignatureError; exports.Receiver = Receiver; exports.QstashError = QstashError; exports.QstashRatelimitError = QstashRatelimitError; exports.QstashChatRatelimitError = QstashChatRatelimitError; exports.QstashDailyRatelimitError = QstashDailyRatelimitError; exports.QstashWorkflowError = QstashWorkflowError; exports.QstashWorkflowAbort = QstashWorkflowAbort; exports.Chat = Chat; exports.Messages = Messages; exports.Schedules = Schedules; exports.UrlGroups = UrlGroups; exports.Client = Client;