@upstash/qstash 2.7.0-canary-1 → 2.7.0-workflow-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1727 @@
1
+ import { Ok, Err } from 'neverthrow';
2
+
3
+ /**
4
+ * Necessary to verify the signature of a request.
5
+ */
6
+ type ReceiverConfig = {
7
+ /**
8
+ * The current signing key. Get it from `https://console.upstash.com/qstash
9
+ */
10
+ currentSigningKey: string;
11
+ /**
12
+ * The next signing key. Get it from `https://console.upstash.com/qstash
13
+ */
14
+ nextSigningKey: string;
15
+ };
16
+ type VerifyRequest = {
17
+ /**
18
+ * The signature from the `upstash-signature` header.
19
+ */
20
+ signature: string;
21
+ /**
22
+ * The raw request body.
23
+ */
24
+ body: string;
25
+ /**
26
+ * URL of the endpoint where the request was sent to.
27
+ *
28
+ * Omit empty to disable checking the url.
29
+ */
30
+ url?: string;
31
+ /**
32
+ * Number of seconds to tolerate when checking `nbf` and `exp` claims, to deal with small clock differences among different servers
33
+ *
34
+ * @default 0
35
+ */
36
+ clockTolerance?: number;
37
+ };
38
+ declare class SignatureError extends Error {
39
+ constructor(message: string);
40
+ }
41
+ /**
42
+ * Receiver offers a simple way to verify the signature of a request.
43
+ */
44
+ declare class Receiver {
45
+ private readonly currentSigningKey;
46
+ private readonly nextSigningKey;
47
+ constructor(config: ReceiverConfig);
48
+ /**
49
+ * Verify the signature of a request.
50
+ *
51
+ * Tries to verify the signature with the current signing key.
52
+ * If that fails, maybe because you have rotated the keys recently, it will
53
+ * try to verify the signature with the next signing key.
54
+ *
55
+ * If that fails, the signature is invalid and a `SignatureError` is thrown.
56
+ */
57
+ verify(request: VerifyRequest): Promise<boolean>;
58
+ /**
59
+ * Verify signature with a specific signing key
60
+ */
61
+ private verifyWithKey;
62
+ }
63
+
64
+ type State = "CREATED" | "ACTIVE" | "DELIVERED" | "ERROR" | "RETRY" | "FAILED";
65
+ type HTTPMethods = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
66
+ type Event = {
67
+ time: number;
68
+ state: State;
69
+ messageId: string;
70
+ nextDeliveryTime?: number;
71
+ error?: string;
72
+ url: string;
73
+ urlGroup?: string;
74
+ topicName?: string;
75
+ endpointName?: string;
76
+ header?: Record<string, string>;
77
+ body?: string;
78
+ };
79
+ type EventPayload = Omit<Event, "urlGroup"> & {
80
+ topicName: string;
81
+ };
82
+ type GetEventsPayload = {
83
+ cursor?: number;
84
+ events: EventPayload[];
85
+ };
86
+ type WithCursor<T> = T & {
87
+ cursor?: number;
88
+ };
89
+ type BodyInit = Blob | FormData | URLSearchParams | ReadableStream<Uint8Array> | string;
90
+ type HeadersInit = Headers | Record<string, string> | [string, string][] | IterableIterator<[string, string]>;
91
+ type RequestOptions = RequestInit & {
92
+ backend?: string;
93
+ };
94
+ type ChatRateLimit = {
95
+ "limit-requests": string | null;
96
+ "limit-tokens": string | null;
97
+ "remaining-requests": string | null;
98
+ "remaining-tokens": string | null;
99
+ "reset-requests": string | null;
100
+ "reset-tokens": string | null;
101
+ };
102
+ type RateLimit = {
103
+ limit: string | null;
104
+ remaining: string | null;
105
+ reset: string | null;
106
+ };
107
+
108
+ type ProviderReturnType = {
109
+ owner: "upstash" | "openai" | "custom";
110
+ baseUrl: string;
111
+ token: string;
112
+ };
113
+ type AnalyticsConfig = {
114
+ name: "helicone";
115
+ token: string;
116
+ };
117
+ type AnalyticsSetup = {
118
+ baseURL?: string;
119
+ defaultHeaders?: Record<string, string | undefined>;
120
+ };
121
+ declare const setupAnalytics: (analytics: AnalyticsConfig | undefined, providerApiKey: string, providerBaseUrl?: string, provider?: "openai" | "upstash" | "custom") => AnalyticsSetup;
122
+ declare const upstash: () => {
123
+ owner: "upstash";
124
+ baseUrl: "https://qstash.upstash.io/llm";
125
+ token: string;
126
+ };
127
+ declare const openai: ({ token, }: {
128
+ token: string;
129
+ }) => {
130
+ owner: "openai";
131
+ baseUrl: "https://api.openai.com";
132
+ token: string;
133
+ };
134
+ declare const custom: ({ baseUrl, token, }: {
135
+ token: string;
136
+ baseUrl: string;
137
+ }) => {
138
+ owner: "custom";
139
+ baseUrl: string;
140
+ token: string;
141
+ };
142
+
143
+ type ChatCompletionMessage = {
144
+ role: "system" | "assistant" | "user";
145
+ content: string;
146
+ };
147
+ type ChatModel = "meta-llama/Meta-Llama-3-8B-Instruct" | "mistralai/Mistral-7B-Instruct-v0.2";
148
+ type ChatResponseFormat = {
149
+ type: "text" | "json_object";
150
+ };
151
+ type TopLogprob = {
152
+ token: string;
153
+ bytes: number[];
154
+ logprob: number;
155
+ };
156
+ type ChatCompletionTokenLogprob = {
157
+ token: string;
158
+ bytes: number[];
159
+ logprob: number;
160
+ top_logprobs: TopLogprob[];
161
+ };
162
+ type ChoiceLogprobs = {
163
+ content: ChatCompletionTokenLogprob[];
164
+ };
165
+ type Choice = {
166
+ finish_reason: "stop" | "length";
167
+ index: number;
168
+ logprobs: ChoiceLogprobs;
169
+ message: ChatCompletionMessage;
170
+ };
171
+ type CompletionUsage = {
172
+ completion_tokens: number;
173
+ prompt_tokens: number;
174
+ total_tokens: number;
175
+ };
176
+ type ChatCompletion = {
177
+ id: string;
178
+ choices: Choice[];
179
+ created: number;
180
+ model: string;
181
+ object: "chat.completion";
182
+ system_fingerprint: string;
183
+ usage: CompletionUsage;
184
+ };
185
+ type ChunkChoice = {
186
+ delta: ChatCompletionMessage;
187
+ finish_reason: "stop" | "length";
188
+ index: number;
189
+ logprobs: ChoiceLogprobs;
190
+ };
191
+ type ChatCompletionChunk = {
192
+ id: string;
193
+ choices: ChunkChoice[];
194
+ created: number;
195
+ model: string;
196
+ object: "chat.completion.chunk";
197
+ system_fingerprint: string;
198
+ usage: CompletionUsage;
199
+ };
200
+ type StreamEnabled = {
201
+ stream: true;
202
+ };
203
+ type StreamDisabled = {
204
+ stream: false;
205
+ } | object;
206
+ type StreamParameter = StreamEnabled | StreamDisabled;
207
+ type OpenAIChatModel = "gpt-4-turbo" | "gpt-4-turbo-2024-04-09" | "gpt-4-0125-preview" | "gpt-4-turbo-preview" | "gpt-4-1106-preview" | "gpt-4-vision-preview" | "gpt-4" | "gpt-4-0314" | "gpt-4-0613" | "gpt-4-32k" | "gpt-4-32k-0314" | "gpt-4-32k-0613" | "gpt-3.5-turbo" | "gpt-3.5-turbo-16k" | "gpt-3.5-turbo-0301" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-1106" | "gpt-3.5-turbo-0125" | "gpt-3.5-turbo-16k-0613";
208
+ type ChatRequestCommonFields = {
209
+ frequency_penalty?: number;
210
+ logit_bias?: Record<string, number>;
211
+ logprobs?: boolean;
212
+ top_logprobs?: number;
213
+ max_tokens?: number;
214
+ n?: number;
215
+ presence_penalty?: number;
216
+ response_format?: ChatResponseFormat;
217
+ seed?: number;
218
+ stop?: string | string[];
219
+ temperature?: number;
220
+ top_p?: number;
221
+ };
222
+ type PromptChatRequestFields = ChatRequestCommonFields & {
223
+ system: string;
224
+ user: string;
225
+ };
226
+ type ChatRequestFields = ChatRequestCommonFields & {
227
+ messages: ChatCompletionMessage[];
228
+ };
229
+ type ChatRequestProviders = {
230
+ provider: ProviderReturnType;
231
+ model: OpenAIChatModel;
232
+ analytics?: {
233
+ name: "helicone";
234
+ token: string;
235
+ };
236
+ } | {
237
+ provider: ProviderReturnType;
238
+ model: string;
239
+ analytics?: {
240
+ name: "helicone";
241
+ token: string;
242
+ };
243
+ } | {
244
+ provider: ProviderReturnType;
245
+ model: ChatModel;
246
+ analytics?: {
247
+ name: "helicone";
248
+ token: string;
249
+ };
250
+ };
251
+ type PromptChatRequest<TStream extends StreamParameter> = ChatRequestProviders & PromptChatRequestFields & TStream;
252
+ type ChatRequest<TStream extends StreamParameter> = ChatRequestProviders & ChatRequestFields & TStream;
253
+
254
+ type UpstashRequest = {
255
+ /**
256
+ * The path to the resource.
257
+ */
258
+ path: string[];
259
+ /**
260
+ * A BodyInit object or null to set request's body.
261
+ */
262
+ body?: BodyInit | null;
263
+ /**
264
+ * A Headers object, an object literal, or an array of two-item arrays to set
265
+ * request's headers.
266
+ */
267
+ headers?: HeadersInit;
268
+ /**
269
+ * A boolean to set request's keepalive.
270
+ */
271
+ keepalive?: boolean;
272
+ /**
273
+ * A string to set request's method.
274
+ */
275
+ method?: HTTPMethods;
276
+ query?: Record<string, string | number | boolean | undefined>;
277
+ /**
278
+ * if enabled, call `res.json()`
279
+ *
280
+ * @default true
281
+ */
282
+ parseResponseAsJson?: boolean;
283
+ baseUrl?: string;
284
+ };
285
+ type UpstashResponse<TResult> = TResult & {
286
+ error?: string;
287
+ };
288
+ type Requester = {
289
+ request: <TResult = unknown>(request: UpstashRequest) => Promise<UpstashResponse<TResult>>;
290
+ requestStream: (request: UpstashRequest) => AsyncIterable<ChatCompletionChunk>;
291
+ };
292
+ type RetryConfig = false | {
293
+ /**
294
+ * The number of retries to attempt before giving up.
295
+ *
296
+ * @default 5
297
+ */
298
+ retries?: number;
299
+ /**
300
+ * A backoff function receives the current retry cound and returns a number in milliseconds to wait before retrying.
301
+ *
302
+ * @default
303
+ * ```ts
304
+ * Math.exp(retryCount) * 50
305
+ * ```
306
+ */
307
+ backoff?: (retryCount: number) => number;
308
+ };
309
+
310
+ type Message = {
311
+ /**
312
+ * A unique identifier for this message.
313
+ */
314
+ messageId: string;
315
+ /**
316
+ * The url group name if this message was sent to a urlGroup.
317
+ */
318
+ urlGroup?: string;
319
+ /**
320
+ * Deprecated. The topic name if this message was sent to a urlGroup. Use urlGroup instead
321
+ */
322
+ topicName?: string;
323
+ /**
324
+ * The url where this message is sent to.
325
+ */
326
+ url: string;
327
+ /**
328
+ * The endpoint name of the message if the endpoint is given a
329
+ * name within the url group.
330
+ */
331
+ endpointName?: string;
332
+ /**
333
+ * The api name if this message was sent to an api
334
+ */
335
+ api?: string;
336
+ /**
337
+ * The http method used to deliver the message
338
+ */
339
+ method?: HTTPMethods;
340
+ /**
341
+ * The http headers sent along with the message to your API.
342
+ */
343
+ header?: Record<string, string[]>;
344
+ /**
345
+ * The http body sent to your API
346
+ */
347
+ body?: string;
348
+ /**
349
+ * The base64 encoded body if the body contains non-UTF-8 characters,
350
+ * `None` otherwise.
351
+ */
352
+ bodyBase64?: string;
353
+ /**
354
+ * Maxmimum number of retries.
355
+ */
356
+ maxRetries?: number;
357
+ /**
358
+ * A unix timestamp (milliseconds) after which this message may get delivered.
359
+ */
360
+ notBefore?: number;
361
+ /**
362
+ * A unix timestamp (milliseconds) when this messages was created.
363
+ */
364
+ createdAt: number;
365
+ /**
366
+ * The callback url if configured.
367
+ */
368
+ callback?: string;
369
+ /**
370
+ * The failure callback url if configured.
371
+ */
372
+ failureCallback?: string;
373
+ /**
374
+ * The queue name if this message was sent to a queue.
375
+ */
376
+ queueName?: string;
377
+ /**
378
+ * The scheduleId of the message if the message is triggered by a schedule
379
+ */
380
+ scheduleId?: string;
381
+ /**
382
+ * IP address of the publisher of this message
383
+ */
384
+ callerIp?: string;
385
+ };
386
+ type MessagePayload = Omit<Message, "urlGroup"> & {
387
+ topicName: string;
388
+ };
389
+ declare class Messages {
390
+ private readonly http;
391
+ constructor(http: Requester);
392
+ /**
393
+ * Get a message
394
+ */
395
+ get(messageId: string): Promise<Message>;
396
+ /**
397
+ * Cancel a message
398
+ */
399
+ delete(messageId: string): Promise<void>;
400
+ deleteMany(messageIds: string[]): Promise<number>;
401
+ deleteAll(): Promise<number>;
402
+ }
403
+
404
+ type DlqMessage = Message & {
405
+ /**
406
+ * The unique id within the DLQ
407
+ */
408
+ dlqId: string;
409
+ /**
410
+ * The HTTP status code of the last failed delivery attempt
411
+ */
412
+ responseStatus?: number;
413
+ /**
414
+ * The response headers of the last failed delivery attempt
415
+ */
416
+ responseHeader?: Record<string, string[]>;
417
+ /**
418
+ * The response body of the last failed delivery attempt if it is
419
+ * composed of UTF-8 characters only, `None` otherwise.
420
+ */
421
+ responseBody?: string;
422
+ /**
423
+ * The base64 encoded response body of the last failed delivery attempt
424
+ * if the response body contains non-UTF-8 characters, `None` otherwise.
425
+ */
426
+ responseBodyBase64?: string;
427
+ };
428
+ type DLQFilter = {
429
+ /**
430
+ * Filter DLQ entries by message id
431
+ */
432
+ messageId?: string;
433
+ /**
434
+ * Filter DLQ entries by url
435
+ */
436
+ url?: string;
437
+ /**
438
+ * Filter DLQ entries by url group name
439
+ */
440
+ urlGroup?: string;
441
+ /**
442
+ * Filter DLQ entries by api name
443
+ */
444
+ api?: string;
445
+ /**
446
+ * Filter DLQ entries by queue name
447
+ */
448
+ queueName?: string;
449
+ /**
450
+ * Filter DLQ entries by schedule id
451
+ */
452
+ scheduleId?: string;
453
+ /**
454
+ * Filter DLQ entries by starting time, in milliseconds
455
+ */
456
+ fromDate?: number;
457
+ /**
458
+ * Filter DLQ entries by ending time, in milliseconds
459
+ */
460
+ toDate?: number;
461
+ /**
462
+ * Filter DLQ entries by HTTP status of the response
463
+ */
464
+ responseStatus?: number;
465
+ /**
466
+ * Filter DLQ entries by IP address of the publisher of the message
467
+ */
468
+ callerIp?: string;
469
+ };
470
+ declare class DLQ {
471
+ private readonly http;
472
+ constructor(http: Requester);
473
+ /**
474
+ * List messages in the dlq
475
+ */
476
+ listMessages(options?: {
477
+ cursor?: string;
478
+ count?: number;
479
+ filter?: DLQFilter;
480
+ }): Promise<{
481
+ messages: DlqMessage[];
482
+ cursor?: string;
483
+ }>;
484
+ /**
485
+ * Remove a message from the dlq using it's `dlqId`
486
+ */
487
+ delete(dlqMessageId: string): Promise<void>;
488
+ /**
489
+ * Remove multiple messages from the dlq using their `dlqId`s
490
+ */
491
+ deleteMany(request: {
492
+ dlqIds: string[];
493
+ }): Promise<{
494
+ deleted: number;
495
+ }>;
496
+ }
497
+
498
+ declare class Chat {
499
+ private http;
500
+ private token;
501
+ constructor(http: Requester, token: string);
502
+ private static toChatRequest;
503
+ /**
504
+ * Calls the Upstash completions api given a ChatRequest.
505
+ *
506
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
507
+ * if stream is enabled.
508
+ *
509
+ * @param request ChatRequest with messages
510
+ * @returns Chat completion or stream
511
+ */
512
+ create: <TStream extends StreamParameter>(request: ChatRequest<TStream>) => Promise<TStream extends StreamEnabled ? AsyncIterable<ChatCompletionChunk> : ChatCompletion>;
513
+ /**
514
+ * Calls the Upstash completions api given a ChatRequest.
515
+ *
516
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
517
+ * if stream is enabled.
518
+ *
519
+ * @param request ChatRequest with messages
520
+ * @returns Chat completion or stream
521
+ */
522
+ private createThirdParty;
523
+ private getAuthorizationToken;
524
+ /**
525
+ * Calls the Upstash completions api given a PromptRequest.
526
+ *
527
+ * Returns a ChatCompletion or a stream of ChatCompletionChunks
528
+ * if stream is enabled.
529
+ *
530
+ * @param request PromptRequest with system and user messages.
531
+ * Note that system parameter shouldn't be passed in the case of
532
+ * mistralai/Mistral-7B-Instruct-v0.2 model.
533
+ * @returns Chat completion or stream
534
+ */
535
+ prompt: <TStream extends StreamParameter>(request: PromptChatRequest<TStream>) => Promise<TStream extends StreamEnabled ? AsyncIterable<ChatCompletionChunk> : ChatCompletion>;
536
+ }
537
+
538
+ type QueueResponse = {
539
+ createdAt: number;
540
+ updatedAt: number;
541
+ name: string;
542
+ parallelism: number;
543
+ lag: number;
544
+ paused: boolean;
545
+ };
546
+ type UpsertQueueRequest = {
547
+ /**
548
+ * The number of parallel consumers consuming from the queue.
549
+ *
550
+ * @default 1
551
+ */
552
+ parallelism?: number;
553
+ /**
554
+ * Whether to pause the queue or not. A paused queue will not
555
+ * deliver new messages until it is resumed.
556
+ *
557
+ * @default false
558
+ */
559
+ paused?: boolean;
560
+ };
561
+ declare class Queue {
562
+ private readonly http;
563
+ private readonly queueName;
564
+ constructor(http: Requester, queueName?: string);
565
+ /**
566
+ * Create or update the queue
567
+ */
568
+ upsert(request: UpsertQueueRequest): Promise<void>;
569
+ /**
570
+ * Get the queue details
571
+ */
572
+ get(): Promise<QueueResponse>;
573
+ /**
574
+ * List queues
575
+ */
576
+ list(): Promise<QueueResponse[]>;
577
+ /**
578
+ * Delete the queue
579
+ */
580
+ delete(): Promise<void>;
581
+ /**
582
+ * Enqueue a message to a queue.
583
+ */
584
+ enqueue<TRequest extends PublishRequest>(request: TRequest): Promise<PublishResponse<TRequest>>;
585
+ /**
586
+ * Enqueue a message to a queue, serializing the body to JSON.
587
+ */
588
+ enqueueJSON<TBody = unknown, TRequest extends PublishRequest<TBody> = PublishRequest<TBody>>(request: TRequest): Promise<PublishResponse<TRequest>>;
589
+ /**
590
+ * Pauses the queue.
591
+ *
592
+ * A paused queue will not deliver messages until
593
+ * it is resumed.
594
+ */
595
+ pause(): Promise<void>;
596
+ /**
597
+ * Resumes the queue.
598
+ */
599
+ resume(): Promise<void>;
600
+ }
601
+
602
+ type Schedule = {
603
+ scheduleId: string;
604
+ cron: string;
605
+ createdAt: number;
606
+ destination: string;
607
+ method: string;
608
+ header?: Record<string, string[]>;
609
+ body?: string;
610
+ bodyBase64?: string;
611
+ retries: number;
612
+ delay?: number;
613
+ callback?: string;
614
+ failureCallback?: string;
615
+ callerIp?: string;
616
+ isPaused: boolean;
617
+ };
618
+ type CreateScheduleRequest = {
619
+ /**
620
+ * Either a URL or urlGroup name
621
+ */
622
+ destination: string;
623
+ /**
624
+ * The message to send.
625
+ *
626
+ * This can be anything, but please set the `Content-Type` header accordingly.
627
+ *
628
+ * You can leave this empty if you want to send a message with no body.
629
+ */
630
+ body?: BodyInit;
631
+ /**
632
+ * Optionally send along headers with the message.
633
+ * These headers will be sent to your destination.
634
+ *
635
+ * We highly recommend sending a `Content-Type` header along, as this will help your destination
636
+ * server to understand the content of the message.
637
+ */
638
+ headers?: HeadersInit;
639
+ /**
640
+ * Optionally delay the delivery of this message.
641
+ *
642
+ * In seconds.
643
+ *
644
+ * @default undefined
645
+ */
646
+ delay?: number;
647
+ /**
648
+ * In case your destination server is unavailable or returns a status code outside of the 200-299
649
+ * range, we will retry the request after a certain amount of time.
650
+ *
651
+ * Configure how many times you would like the delivery to be retried
652
+ *
653
+ * @default The maximum retry quota associated with your account.
654
+ */
655
+ retries?: number;
656
+ /**
657
+ * Use a callback url to forward the response of your destination server to your callback url.
658
+ *
659
+ * The callback url must be publicly accessible
660
+ *
661
+ * @default undefined
662
+ */
663
+ callback?: string;
664
+ /**
665
+ * Use a failure callback url to handle messages that could not be delivered.
666
+ *
667
+ * The failure callback url must be publicly accessible
668
+ *
669
+ * @default undefined
670
+ */
671
+ failureCallback?: string;
672
+ /**
673
+ * The method to use when sending a request to your API
674
+ *
675
+ * @default `POST`
676
+ */
677
+ method?: HTTPMethods;
678
+ /**
679
+ * Specify a cron expression to repeatedly send this message to the destination.
680
+ */
681
+ cron: string;
682
+ /**
683
+ * The HTTP timeout value to use while calling the destination URL.
684
+ * When a timeout is specified, it will be used instead of the maximum timeout
685
+ * value permitted by the QStash plan. It is useful in scenarios, where a message
686
+ * should be delivered with a shorter timeout.
687
+ *
688
+ * In seconds.
689
+ *
690
+ * @default undefined
691
+ */
692
+ timeout?: number;
693
+ /**
694
+ * Schedule id to use.
695
+ *
696
+ * Can be used to updatine the settings of an existing schedule.
697
+ *
698
+ * @default undefined
699
+ */
700
+ scheduleId?: string;
701
+ };
702
+ declare class Schedules {
703
+ private readonly http;
704
+ constructor(http: Requester);
705
+ /**
706
+ * Create a schedule
707
+ */
708
+ create(request: CreateScheduleRequest): Promise<{
709
+ scheduleId: string;
710
+ }>;
711
+ /**
712
+ * Get a schedule
713
+ */
714
+ get(scheduleId: string): Promise<Schedule>;
715
+ /**
716
+ * List your schedules
717
+ */
718
+ list(): Promise<Schedule[]>;
719
+ /**
720
+ * Delete a schedule
721
+ */
722
+ delete(scheduleId: string): Promise<void>;
723
+ /**
724
+ * Pauses the schedule.
725
+ *
726
+ * A paused schedule will not deliver messages until
727
+ * it is resumed.
728
+ */
729
+ pause({ schedule }: {
730
+ schedule: string;
731
+ }): Promise<void>;
732
+ /**
733
+ * Resumes the schedule.
734
+ */
735
+ resume({ schedule }: {
736
+ schedule: string;
737
+ }): Promise<void>;
738
+ }
739
+
740
+ type Endpoint = {
741
+ /**
742
+ * The name of the endpoint (optional)
743
+ */
744
+ name?: string;
745
+ /**
746
+ * The url of the endpoint
747
+ */
748
+ url: string;
749
+ };
750
+ type AddEndpointsRequest = {
751
+ /**
752
+ * The name of the url group.
753
+ * Must be unique and only contain alphanumeric, hyphen, underscore and periods.
754
+ */
755
+ name: string;
756
+ endpoints: Endpoint[];
757
+ };
758
+ type RemoveEndpointsRequest = {
759
+ /**
760
+ * The name of the url group.
761
+ * Must be unique and only contain alphanumeric, hyphen, underscore and periods.
762
+ */
763
+ name: string;
764
+ endpoints: ({
765
+ name: string;
766
+ url?: string;
767
+ } | {
768
+ name?: string;
769
+ url: string;
770
+ })[];
771
+ };
772
+ type UrlGroup = {
773
+ /**
774
+ * A unix timestamp (milliseconds)
775
+ */
776
+ createdAt: number;
777
+ /**
778
+ * A unix timestamp (milliseconds)
779
+ */
780
+ updatedAt: number;
781
+ /**
782
+ * The name of this url group.
783
+ */
784
+ name: string;
785
+ /**
786
+ * A list of all subscribed endpoints
787
+ */
788
+ endpoints: Endpoint[];
789
+ };
790
+ declare class UrlGroups {
791
+ private readonly http;
792
+ constructor(http: Requester);
793
+ /**
794
+ * Create a new url group with the given name and endpoints
795
+ */
796
+ addEndpoints(request: AddEndpointsRequest): Promise<void>;
797
+ /**
798
+ * Remove endpoints from a url group.
799
+ */
800
+ removeEndpoints(request: RemoveEndpointsRequest): Promise<void>;
801
+ /**
802
+ * Get a list of all url groups.
803
+ */
804
+ list(): Promise<UrlGroup[]>;
805
+ /**
806
+ * Get a single url group
807
+ */
808
+ get(name: string): Promise<UrlGroup>;
809
+ /**
810
+ * Delete a url group
811
+ */
812
+ delete(name: string): Promise<void>;
813
+ }
814
+
815
+ /**
816
+ * Base class outlining steps. Basically, each step kind (run/sleep/sleepUntil)
817
+ * should have two methods: getPlanStep & getResultStep.
818
+ *
819
+ * getPlanStep works the same way for all so it's implemented here.
820
+ * The different step types will implement their own getResultStep method.
821
+ */
822
+ declare abstract class BaseLazyStep<TResult = unknown> {
823
+ readonly stepName: string;
824
+ abstract readonly stepType: StepType;
825
+ constructor(stepName: string);
826
+ /**
827
+ * plan step to submit when step will run parallel with other
828
+ * steps (parallel call state `first`)
829
+ *
830
+ * @param concurrent number of steps running parallel
831
+ * @param targetStep target step id corresponding to this step
832
+ * @returns
833
+ */
834
+ abstract getPlanStep(concurrent: number, targetStep: number): Step<undefined>;
835
+ /**
836
+ * result step to submit after the step executes. Used in single step executions
837
+ * and when a plan step executes in parallel executions (parallel call state `partial`).
838
+ *
839
+ * @param concurrent
840
+ * @param stepId
841
+ */
842
+ abstract getResultStep(concurrent: number, stepId: number): Promise<Step<TResult>>;
843
+ }
844
+
845
+ declare const LOG_LEVELS: readonly ["DEBUG", "INFO", "SUBMIT", "WARN", "ERROR"];
846
+ type LogLevel = (typeof LOG_LEVELS)[number];
847
+ type ChatLogEntry = {
848
+ timestamp: number;
849
+ workflowRunId: string;
850
+ logLevel: LogLevel;
851
+ eventType: "ENDPOINT_START" | "SUBMIT_THIRD_PARTY_RESULT" | "CREATE_CONTEXT" | "SUBMIT_FIRST_INVOCATION" | "RUN_SINGLE" | "RUN_PARALLEL" | "SUBMIT_STEP" | "SUBMIT_CLEANUP" | "RESPONSE_WORKFLOW" | "RESPONSE_DEFAULT" | "ERROR";
852
+ details: unknown;
853
+ };
854
+ type WorkflowLoggerOptions = {
855
+ logLevel: LogLevel;
856
+ logOutput: "console";
857
+ };
858
+ declare class WorkflowLogger {
859
+ private logs;
860
+ private options;
861
+ private workflowRunId?;
862
+ constructor(options: WorkflowLoggerOptions);
863
+ log(level: LogLevel, eventType: ChatLogEntry["eventType"], details?: unknown): Promise<void>;
864
+ setWorkflowRunId(workflowRunId: string): void;
865
+ private writeToConsole;
866
+ private shouldLog;
867
+ static getLogger(verbose?: boolean | WorkflowLogger): WorkflowLogger | undefined;
868
+ }
869
+
870
+ declare class AutoExecutor {
871
+ private context;
872
+ private promises;
873
+ private activeLazyStepList?;
874
+ private debug?;
875
+ private readonly nonPlanStepCount;
876
+ private readonly steps;
877
+ private indexInCurrentList;
878
+ stepCount: number;
879
+ planStepCount: number;
880
+ protected executingStep: string | false;
881
+ constructor(context: WorkflowContext, steps: Step[], debug?: WorkflowLogger);
882
+ /**
883
+ * Adds the step function to the list of step functions to run in
884
+ * parallel. After adding the function, defers the execution, so
885
+ * that if there is another step function to be added, it's also
886
+ * added.
887
+ *
888
+ * After all functions are added, list of functions are executed.
889
+ * If there is a single function, it's executed by itself. If there
890
+ * are multiple, they are run in parallel.
891
+ *
892
+ * If a function is already executing (this.executingStep), this
893
+ * means that there is a nested step which is not allowed. In this
894
+ * case, addStep throws QstashWorkflowError.
895
+ *
896
+ * @param stepInfo step plan to add
897
+ * @returns result of the step function
898
+ */
899
+ addStep<TResult>(stepInfo: BaseLazyStep<TResult>): Promise<TResult>;
900
+ /**
901
+ * Wraps a step function to set this.executingStep to step name
902
+ * before running and set this.executingStep to False after execution
903
+ * ends.
904
+ *
905
+ * this.executingStep allows us to detect nested steps which are not
906
+ * allowed.
907
+ *
908
+ * @param stepName name of the step being wrapped
909
+ * @param stepFunction step function to wrap
910
+ * @returns wrapped step function
911
+ */
912
+ wrapStep<TResult = unknown>(stepName: string, stepFunction: AsyncStepFunction<TResult>): Promise<TResult>;
913
+ /**
914
+ * Executes a step:
915
+ * - If the step result is available in the steps, returns the result
916
+ * - If the result is not avaiable, runs the function
917
+ * - Sends the result to QStash
918
+ *
919
+ * @param lazyStep lazy step to execute
920
+ * @returns step result
921
+ */
922
+ protected runSingle<TResult>(lazyStep: BaseLazyStep<TResult>): Promise<TResult>;
923
+ /**
924
+ * Runs steps in parallel.
925
+ *
926
+ * @param stepName parallel step name
927
+ * @param stepFunctions list of async functions to run in parallel
928
+ * @returns results of the functions run in parallel
929
+ */
930
+ protected runParallel<TResults extends unknown[]>(parallelSteps: {
931
+ [K in keyof TResults]: BaseLazyStep<TResults[K]>;
932
+ }): Promise<TResults>;
933
+ /**
934
+ * Determines the parallel call state
935
+ *
936
+ * First filters the steps to get the steps which are after `initialStepCount` parameter.
937
+ *
938
+ * Depending on the remaining steps, decides the parallel state:
939
+ * - "first": If there are no steps
940
+ * - "last" If there are equal to or more than `2 * parallelStepCount`. We multiply by two
941
+ * because each step in a parallel execution will have 2 steps: a plan step and a result
942
+ * step.
943
+ * - "partial": If the last step is a plan step
944
+ * - "discard": If the last step is not a plan step. This means that the parallel execution
945
+ * is in progress (there are still steps to run) and one step has finished and submitted
946
+ * its result to QStash
947
+ *
948
+ * @param parallelStepCount number of steps to run in parallel
949
+ * @param initialStepCount steps after the parallel invocation
950
+ * @returns parallel call state
951
+ */
952
+ protected getParallelCallState(parallelStepCount: number, initialStepCount: number): ParallelCallState;
953
+ /**
954
+ * sends the steps to QStash as batch
955
+ *
956
+ * @param steps steps to send
957
+ */
958
+ private submitStepsToQstash;
959
+ /**
960
+ * Get the promise by executing the lazt steps list. If there is a single
961
+ * step, we call `runSingle`. Otherwise `runParallel` is called.
962
+ *
963
+ * @param lazyStepList steps list to execute
964
+ * @returns promise corresponding to the execution
965
+ */
966
+ private getExecutionPromise;
967
+ /**
968
+ * @param lazyStepList steps we executed
969
+ * @param result result of the promise from `getExecutionPromise`
970
+ * @param index index of the current step
971
+ * @returns result[index] if lazyStepList > 1, otherwise result
972
+ */
973
+ private static getResult;
974
+ private deferExecution;
975
+ }
976
+
977
+ declare class WorkflowContext<TInitialPayload = unknown> {
978
+ protected readonly executor: AutoExecutor;
979
+ protected readonly steps: Step[];
980
+ /**
981
+ * QStash client of the workflow
982
+ *
983
+ * Can be overwritten by passing `qstashClient` parameter in `serve`:
984
+ *
985
+ * ```ts
986
+ * import { Client } from "@upstash/qstash"
987
+ *
988
+ * export const POST = serve(
989
+ * async (context) => {
990
+ * ...
991
+ * },
992
+ * {
993
+ * qstashClient: new Client({...})
994
+ * }
995
+ * )
996
+ * ```
997
+ */
998
+ readonly qstashClient: Client;
999
+ /**
1000
+ * Run id of the workflow
1001
+ */
1002
+ readonly workflowRunId: string;
1003
+ /**
1004
+ * URL of the workflow
1005
+ *
1006
+ * Can be overwritten by passing a `url` parameter in `serve`:
1007
+ *
1008
+ * ```ts
1009
+ * export const POST = serve(
1010
+ * async (context) => {
1011
+ * ...
1012
+ * },
1013
+ * {
1014
+ * url: "new-url-value"
1015
+ * }
1016
+ * )
1017
+ * ```
1018
+ */
1019
+ readonly url: string;
1020
+ /**
1021
+ * URL to call in case of workflow failure with QStash failure callback
1022
+ *
1023
+ * https://upstash.com/docs/qstash/features/callbacks#what-is-a-failure-callback
1024
+ *
1025
+ * Can be overwritten by passing a `failureUrl` parameter in `serve`:
1026
+ *
1027
+ * ```ts
1028
+ * export const POST = serve(
1029
+ * async (context) => {
1030
+ * ...
1031
+ * },
1032
+ * {
1033
+ * failureUrl: "new-url-value"
1034
+ * }
1035
+ * )
1036
+ * ```
1037
+ */
1038
+ readonly failureUrl?: string;
1039
+ /**
1040
+ * Payload of the request which started the workflow.
1041
+ *
1042
+ * To specify its type, you can define `serve` as follows:
1043
+ *
1044
+ * ```ts
1045
+ * // set requestPayload type to MyPayload:
1046
+ * export const POST = serve<MyPayload>(
1047
+ * async (context) => {
1048
+ * ...
1049
+ * }
1050
+ * )
1051
+ * ```
1052
+ *
1053
+ * By default, `serve` tries to apply `JSON.parse` to the request payload.
1054
+ * If your payload is encoded in a format other than JSON, you can utilize
1055
+ * the `initialPayloadParser` parameter:
1056
+ *
1057
+ * ```ts
1058
+ * export const POST = serve<MyPayload>(
1059
+ * async (context) => {
1060
+ * ...
1061
+ * },
1062
+ * {
1063
+ * initialPayloadParser: (initialPayload) => {return doSomething(initialPayload)}
1064
+ * }
1065
+ * )
1066
+ * ```
1067
+ */
1068
+ readonly requestPayload: TInitialPayload;
1069
+ /**
1070
+ * headers of the initial request
1071
+ */
1072
+ readonly headers: Headers;
1073
+ /**
1074
+ * initial payload as a raw string
1075
+ */
1076
+ readonly rawInitialPayload: string;
1077
+ constructor({ qstashClient, workflowRunId, headers, steps, url, failureUrl, debug, initialPayload, rawInitialPayload, }: {
1078
+ qstashClient: Client;
1079
+ workflowRunId: string;
1080
+ headers: Headers;
1081
+ steps: Step[];
1082
+ url: string;
1083
+ failureUrl?: string;
1084
+ debug?: WorkflowLogger;
1085
+ initialPayload: TInitialPayload;
1086
+ rawInitialPayload?: string;
1087
+ });
1088
+ /**
1089
+ * Executes a workflow step
1090
+ *
1091
+ * ```typescript
1092
+ * const result = await context.run("step 1", async () => {
1093
+ * return await Promise.resolve("result")
1094
+ * })
1095
+ * ```
1096
+ *
1097
+ * Can also be called in parallel and the steps will be executed
1098
+ * simulatenously:
1099
+ *
1100
+ * ```typescript
1101
+ * const [result1, result2] = await Promise.all([
1102
+ * context.run("step 1", async () => {
1103
+ * return await Promise.resolve("result1")
1104
+ * })
1105
+ * context.run("step 2", async () => {
1106
+ * return await Promise.resolve("result2")
1107
+ * })
1108
+ * ])
1109
+ * ```
1110
+ *
1111
+ * @param stepName name of the step
1112
+ * @param stepFunction step function to be executed
1113
+ * @returns result of the step function
1114
+ */
1115
+ run<TResult>(stepName: string, stepFunction: AsyncStepFunction<TResult>): Promise<TResult>;
1116
+ /**
1117
+ * Stops the execution for the duration provided.
1118
+ *
1119
+ * @param stepName
1120
+ * @param duration sleep duration in seconds
1121
+ * @returns undefined
1122
+ */
1123
+ sleep(stepName: string, duration: number): Promise<void>;
1124
+ /**
1125
+ * Stops the execution until the date time provided.
1126
+ *
1127
+ * @param stepName
1128
+ * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
1129
+ * as a Date object or a string (passed to `new Date(datetimeString)`)
1130
+ * @returns undefined
1131
+ */
1132
+ sleepUntil(stepName: string, datetime: Date | string | number): Promise<void>;
1133
+ /**
1134
+ * Makes a third party call through QStash in order to make a
1135
+ * network call without consuming any runtime.
1136
+ *
1137
+ * ```ts
1138
+ * const postResult = await context.call<string>(
1139
+ * "post call step",
1140
+ * `https://www.some-endpoint.com/api`,
1141
+ * "POST",
1142
+ * "my-payload"
1143
+ * );
1144
+ * ```
1145
+ *
1146
+ * @param stepName
1147
+ * @param url url to call
1148
+ * @param method call method
1149
+ * @param body call body
1150
+ * @param headers call headers
1151
+ * @returns call result
1152
+ */
1153
+ call<TResult = unknown, TBody = unknown>(stepName: string, url: string, method: HTTPMethods, body?: TBody, headers?: Record<string, string>): Promise<TResult>;
1154
+ /**
1155
+ * Adds steps to the executor. Needed so that it can be overwritten in
1156
+ * DisabledWorkflowContext.
1157
+ */
1158
+ protected addStep<TResult = unknown>(step: BaseLazyStep<TResult>): Promise<TResult>;
1159
+ }
1160
+ /**
1161
+ * Workflow context which throws QstashWorkflowAbort before running the steps.
1162
+ *
1163
+ * Used for making a dry run before running any steps to check authentication.
1164
+ *
1165
+ * Consider an endpoint like this:
1166
+ * ```ts
1167
+ * export const POST = serve({
1168
+ * routeFunction: context => {
1169
+ * if (context.headers.get("authentication") !== "Bearer secretPassword") {
1170
+ * console.error("Authentication failed.");
1171
+ * return;
1172
+ * }
1173
+ *
1174
+ * // ...
1175
+ * }
1176
+ * })
1177
+ * ```
1178
+ *
1179
+ * the serve method will first call the routeFunction with an DisabledWorkflowContext.
1180
+ * Here is the action we take in different cases
1181
+ * - "step-found": we will run the workflow related sections of `serve`.
1182
+ * - "run-ended": simply return success and end the workflow
1183
+ * - error: returns 500.
1184
+ */
1185
+ declare class DisabledWorkflowContext<TInitialPayload = unknown> extends WorkflowContext<TInitialPayload> {
1186
+ private static readonly disabledMessage;
1187
+ /**
1188
+ * overwrite the WorkflowContext.addStep method to always raise QstashWorkflowAbort
1189
+ * error in order to stop the execution whenever we encounter a step.
1190
+ *
1191
+ * @param _step
1192
+ */
1193
+ protected addStep<TResult = unknown>(_step: BaseLazyStep<TResult>): Promise<TResult>;
1194
+ /**
1195
+ * copies the passed context to create a DisabledWorkflowContext. Then, runs the
1196
+ * route function with the new context.
1197
+ *
1198
+ * - returns "run-ended" if there are no steps found or
1199
+ * if the auth failed and user called `return`
1200
+ * - returns "step-found" if DisabledWorkflowContext.addStep is called.
1201
+ * - if there is another error, returns the error.
1202
+ *
1203
+ * @param routeFunction
1204
+ */
1205
+ static tryAuthentication<TInitialPayload = unknown>(routeFunction: RouteFunction<TInitialPayload>, context: WorkflowContext<TInitialPayload>): Promise<Ok<"step-found" | "run-ended", never> | Err<never, Error>>;
1206
+ }
1207
+
1208
+ declare const StepTypes: readonly ["Initial", "Run", "SleepFor", "SleepUntil", "Call"];
1209
+ type StepType = (typeof StepTypes)[number];
1210
+ type ThirdPartyCallFields<TBody = unknown> = {
1211
+ /**
1212
+ * Third party call URL. Set when context.call is used.
1213
+ */
1214
+ callUrl: string;
1215
+ /**
1216
+ * Third party call method. Set when context.call is used.
1217
+ */
1218
+ callMethod: HTTPMethods;
1219
+ /**
1220
+ * Third party call body. Set when context.call is used.
1221
+ */
1222
+ callBody: TBody;
1223
+ /**
1224
+ * Third party call headers. Set when context.call is used.
1225
+ */
1226
+ callHeaders: Record<string, string>;
1227
+ };
1228
+ type Step<TResult = unknown, TBody = unknown> = {
1229
+ /**
1230
+ * index of the step
1231
+ */
1232
+ stepId: number;
1233
+ /**
1234
+ * name of the step
1235
+ */
1236
+ stepName: string;
1237
+ /**
1238
+ * type of the step (Initial/Run/SleepFor/SleepUntil/Call)
1239
+ */
1240
+ stepType: StepType;
1241
+ /**
1242
+ * step result. Set if context.run or context.call are used.
1243
+ */
1244
+ out?: TResult;
1245
+ /**
1246
+ * sleep duration in seconds. Set when context.sleep is used.
1247
+ */
1248
+ sleepFor?: number;
1249
+ /**
1250
+ * unix timestamp (in seconds) to wait until. Set when context.sleepUntil is used.
1251
+ */
1252
+ sleepUntil?: number;
1253
+ /**
1254
+ * number of steps running concurrently if the step is in a parallel run.
1255
+ * Set to 1 if step is not parallel.
1256
+ */
1257
+ concurrent: number;
1258
+ /**
1259
+ * target step of a plan step. In other words, the step to assign the
1260
+ * result of a plan step.
1261
+ *
1262
+ * undefined if the step is not a plan step (of a parallel run). Otherwise,
1263
+ * set to the target step.
1264
+ */
1265
+ targetStep?: number;
1266
+ } & (ThirdPartyCallFields<TBody> | {
1267
+ [P in keyof ThirdPartyCallFields]?: never;
1268
+ });
1269
+ type RawStep = {
1270
+ messageId: string;
1271
+ body: string;
1272
+ callType: "step" | "toCallback" | "fromCallback";
1273
+ };
1274
+ type SyncStepFunction<TResult> = () => TResult;
1275
+ type AsyncStepFunction<TResult> = () => Promise<TResult>;
1276
+ type StepFunction<TResult> = AsyncStepFunction<TResult> | SyncStepFunction<TResult>;
1277
+ type ParallelCallState = "first" | "partial" | "discard" | "last";
1278
+ type RouteFunction<TInitialPayload> = (context: WorkflowContext<TInitialPayload>) => Promise<void>;
1279
+ type FinishCondition = "success" | "duplicate-step" | "fromCallback" | "auth-fail" | "failure-callback";
1280
+ type WorkflowServeOptions<TResponse extends Response = Response, TInitialPayload = unknown> = {
1281
+ /**
1282
+ * QStash client
1283
+ */
1284
+ qstashClient?: Client;
1285
+ /**
1286
+ * Function called to return a response after each step execution
1287
+ *
1288
+ * @param workflowRunId
1289
+ * @returns response
1290
+ */
1291
+ onStepFinish?: (workflowRunId: string, finishCondition: FinishCondition) => TResponse;
1292
+ /**
1293
+ * Function to parse the initial payload passed by the user
1294
+ */
1295
+ initialPayloadParser?: (initialPayload: string) => TInitialPayload;
1296
+ /**
1297
+ * Url of the endpoint where the workflow is set up.
1298
+ *
1299
+ * If not set, url will be inferred from the request.
1300
+ */
1301
+ url?: string;
1302
+ /**
1303
+ * Verbose mode
1304
+ *
1305
+ * Disabled if not set. If set to true, a logger is created automatically.
1306
+ *
1307
+ * Alternatively, a WorkflowLogger can be passed.
1308
+ */
1309
+ verbose?: WorkflowLogger | true;
1310
+ /**
1311
+ * Receiver to verify *all* requests by checking if they come from QStash
1312
+ *
1313
+ * By default, a receiver is created from the env variables
1314
+ * QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY if they are set.
1315
+ */
1316
+ receiver?: Receiver;
1317
+ /**
1318
+ * Url to call if QStash retries are exhausted while executing the workflow
1319
+ */
1320
+ failureUrl?: string;
1321
+ /**
1322
+ * Failure function called when QStash retries are exhausted while executing
1323
+ * the workflow. Will overwrite `failureUrl` parameter with the workflow
1324
+ * endpoint if passed.
1325
+ *
1326
+ * @param context workflow context at the moment of error
1327
+ * @param failStatus error status
1328
+ * @param failResponse error message
1329
+ * @returns void
1330
+ */
1331
+ failureFunction?: (context: Omit<WorkflowContext, "run" | "sleepUntil" | "sleep" | "call">, failStatus: number, failResponse: string, failHeader: Record<string, string[]>) => Promise<void>;
1332
+ /**
1333
+ * Base Url of the workflow endpoint
1334
+ *
1335
+ * Can be used to set if there is a local tunnel or a proxy between
1336
+ * QStash and the workflow endpoint.
1337
+ *
1338
+ * Will be set to the env variable UPSTASH_WORKFLOW_URL if not passed.
1339
+ * If the env variable is not set, the url will be infered as usual from
1340
+ * the `request.url` or the `url` parameter in `serve` options.
1341
+ *
1342
+ * @default undefined
1343
+ */
1344
+ baseUrl?: string;
1345
+ };
1346
+ /**
1347
+ * Payload passed as body in failureFunction
1348
+ */
1349
+ type FailureFunctionPayload = {
1350
+ /**
1351
+ * error name
1352
+ */
1353
+ error: string;
1354
+ /**
1355
+ * error message
1356
+ */
1357
+ message: string;
1358
+ };
1359
+ /**
1360
+ * Makes all fields except the ones selected required
1361
+ */
1362
+ type RequiredExceptFields<T, K extends keyof T> = Omit<Required<T>, K> & Partial<Pick<T, K>>;
1363
+
1364
+ /**
1365
+ * Fills the options with default values if they are not provided.
1366
+ *
1367
+ * Default values for:
1368
+ * - qstashClient: QStash client created with QSTASH_URL and QSTASH_TOKEN env vars
1369
+ * - onStepFinish: returns a Response with workflowRunId & finish condition in the body (status: 200)
1370
+ * - initialPayloadParser: calls JSON.parse if initial request body exists.
1371
+ * - receiver: a Receiver if the required env vars are set
1372
+ * - baseUrl: env variable UPSTASH_WORKFLOW_URL
1373
+ *
1374
+ * @param options options including the client, onFinish and initialPayloadParser
1375
+ * @returns
1376
+ */
1377
+ declare const processOptions: <TResponse extends Response = Response, TInitialPayload = unknown>(options?: WorkflowServeOptions<TResponse, TInitialPayload>) => RequiredExceptFields<WorkflowServeOptions<TResponse, TInitialPayload>, "verbose" | "receiver" | "url" | "failureFunction" | "failureUrl" | "baseUrl">;
1378
+ /**
1379
+ * Creates an async method that handles incoming requests and runs the provided
1380
+ * route function as a workflow.
1381
+ *
1382
+ * @param routeFunction - A function that uses WorkflowContext as a parameter and runs a workflow.
1383
+ * @param options - Options including the client, onFinish callback, and initialPayloadParser.
1384
+ * @returns An async method that consumes incoming requests and runs the workflow.
1385
+ */
1386
+ declare const serve: <TInitialPayload = unknown, TRequest extends Request = Request, TResponse extends Response = Response>(routeFunction: RouteFunction<TInitialPayload>, options?: WorkflowServeOptions<TResponse, TInitialPayload>) => ((request: TRequest) => Promise<TResponse>);
1387
+
1388
+ declare class Workflow {
1389
+ private readonly http;
1390
+ constructor(http: Requester);
1391
+ /**
1392
+ * Cancel an ongoing workflow
1393
+ *
1394
+ * @param workflowRunId run id of the workflow to delete
1395
+ * @returns true if workflow is succesfully deleted. Otherwise throws QStashError
1396
+ */
1397
+ cancel(workflowRunId: string): Promise<true | {
1398
+ error: string;
1399
+ }>;
1400
+ }
1401
+
1402
+ type ClientConfig = {
1403
+ /**
1404
+ * Url of the qstash api server.
1405
+ *
1406
+ * This is only used for testing.
1407
+ *
1408
+ * @default "https://qstash.upstash.io"
1409
+ */
1410
+ baseUrl?: string;
1411
+ /**
1412
+ * The authorization token from the upstash console.
1413
+ */
1414
+ token: string;
1415
+ /**
1416
+ * Configure how the client should retry requests.
1417
+ */
1418
+ retry?: RetryConfig;
1419
+ };
1420
+ type PublishBatchRequest<TBody = BodyInit> = PublishRequest<TBody> & {
1421
+ queueName?: string;
1422
+ };
1423
+ type PublishRequest<TBody = BodyInit> = {
1424
+ /**
1425
+ * The message to send.
1426
+ *
1427
+ * This can be anything, but please set the `Content-Type` header accordingly.
1428
+ *
1429
+ * You can leave this empty if you want to send a message with no body.
1430
+ */
1431
+ body?: TBody;
1432
+ /**
1433
+ * Optionally send along headers with the message.
1434
+ * These headers will be sent to your destination.
1435
+ *
1436
+ * We highly recommend sending a `Content-Type` header along, as this will help your destination
1437
+ * server to understand the content of the message.
1438
+ */
1439
+ headers?: HeadersInit;
1440
+ /**
1441
+ * Optionally delay the delivery of this message.
1442
+ *
1443
+ * In seconds.
1444
+ *
1445
+ * @default undefined
1446
+ */
1447
+ delay?: number;
1448
+ /**
1449
+ * Optionally set the absolute delay of this message.
1450
+ * This will override the delay option.
1451
+ * The message will not delivered until the specified time.
1452
+ *
1453
+ * Unix timestamp in seconds.
1454
+ *
1455
+ * @default undefined
1456
+ */
1457
+ notBefore?: number;
1458
+ /**
1459
+ * Provide a unique id for deduplication. This id will be used to detect duplicate messages.
1460
+ * If a duplicate message is detected, the request will be accepted but not enqueued.
1461
+ *
1462
+ * We store deduplication ids for 90 days. Afterwards it is possible that the message with the
1463
+ * same deduplication id is delivered again.
1464
+ *
1465
+ * When scheduling a message, the deduplication happens before the schedule is created.
1466
+ *
1467
+ * @default undefined
1468
+ */
1469
+ deduplicationId?: string;
1470
+ /**
1471
+ * If true, the message content will get hashed and used as deduplication id.
1472
+ * If a duplicate message is detected, the request will be accepted but not enqueued.
1473
+ *
1474
+ * The content based hash includes the following values:
1475
+ * - All headers, except Upstash-Authorization, this includes all headers you are sending.
1476
+ * - The entire raw request body The destination from the url path
1477
+ *
1478
+ * We store deduplication ids for 90 days. Afterwards it is possible that the message with the
1479
+ * same deduplication id is delivered again.
1480
+ *
1481
+ * When scheduling a message, the deduplication happens before the schedule is created.
1482
+ *
1483
+ * @default false
1484
+ */
1485
+ contentBasedDeduplication?: boolean;
1486
+ /**
1487
+ * In case your destination server is unavaialble or returns a status code outside of the 200-299
1488
+ * range, we will retry the request after a certain amount of time.
1489
+ *
1490
+ * Configure how many times you would like the delivery to be retried up to the maxRetries limit
1491
+ * defined in your plan.
1492
+ *
1493
+ * @default 3
1494
+ */
1495
+ retries?: number;
1496
+ /**
1497
+ * Use a failure callback url to handle messages that could not be delivered.
1498
+ *
1499
+ * The failure callback url must be publicly accessible
1500
+ *
1501
+ * @default undefined
1502
+ */
1503
+ failureCallback?: string;
1504
+ /**
1505
+ * The method to use when sending a request to your API
1506
+ *
1507
+ * @default `POST`
1508
+ */
1509
+ method?: HTTPMethods;
1510
+ /**
1511
+ * The HTTP timeout value to use while calling the destination URL.
1512
+ * When a timeout is specified, it will be used instead of the maximum timeout
1513
+ * value permitted by the QStash plan. It is useful in scenarios, where a message
1514
+ * should be delivered with a shorter timeout.
1515
+ *
1516
+ * In seconds.
1517
+ *
1518
+ * @default undefined
1519
+ */
1520
+ timeout?: number;
1521
+ } & ({
1522
+ /**
1523
+ * The url where the message should be sent to.
1524
+ */
1525
+ url: string;
1526
+ urlGroup?: never;
1527
+ api?: never;
1528
+ topic?: never;
1529
+ /**
1530
+ * Use a callback url to forward the response of your destination server to your callback url.
1531
+ *
1532
+ * The callback url must be publicly accessible
1533
+ *
1534
+ * @default undefined
1535
+ */
1536
+ callback?: string;
1537
+ } | {
1538
+ url?: never;
1539
+ /**
1540
+ * The url group the message should be sent to.
1541
+ */
1542
+ urlGroup: string;
1543
+ api?: never;
1544
+ topic?: never;
1545
+ /**
1546
+ * Use a callback url to forward the response of your destination server to your callback url.
1547
+ *
1548
+ * The callback url must be publicly accessible
1549
+ *
1550
+ * @default undefined
1551
+ */
1552
+ callback?: string;
1553
+ } | {
1554
+ url?: string;
1555
+ urlGroup?: never;
1556
+ /**
1557
+ * The api endpoint the request should be sent to.
1558
+ */
1559
+ api: {
1560
+ name: "llm";
1561
+ provider?: ProviderReturnType;
1562
+ analytics?: {
1563
+ name: "helicone";
1564
+ token: string;
1565
+ };
1566
+ };
1567
+ /**
1568
+ * Use a callback url to forward the response of your destination server to your callback url.
1569
+ *
1570
+ * The callback url must be publicly accessible
1571
+ *
1572
+ * @default undefined
1573
+ */
1574
+ callback: string;
1575
+ topic?: never;
1576
+ } | {
1577
+ url?: never;
1578
+ urlGroup?: never;
1579
+ api: never;
1580
+ /**
1581
+ * Deprecated. The topic the message should be sent to. Same as urlGroup
1582
+ */
1583
+ topic?: string;
1584
+ /**
1585
+ * Use a callback url to forward the response of your destination server to your callback url.
1586
+ *
1587
+ * The callback url must be publicly accessible
1588
+ *
1589
+ * @default undefined
1590
+ */
1591
+ callback?: string;
1592
+ });
1593
+ type PublishJsonRequest = Omit<PublishRequest, "body"> & {
1594
+ /**
1595
+ * The message to send.
1596
+ * This can be anything as long as it can be serialized to JSON.
1597
+ */
1598
+ body: unknown;
1599
+ };
1600
+ type EventsRequest = {
1601
+ cursor?: number;
1602
+ filter?: EventsRequestFilter;
1603
+ };
1604
+ type EventsRequestFilter = {
1605
+ messageId?: string;
1606
+ state?: State;
1607
+ url?: string;
1608
+ urlGroup?: string;
1609
+ topicName?: string;
1610
+ api?: string;
1611
+ scheduleId?: string;
1612
+ queueName?: string;
1613
+ fromDate?: number;
1614
+ toDate?: number;
1615
+ count?: number;
1616
+ };
1617
+ type GetEventsResponse = {
1618
+ cursor?: number;
1619
+ events: Event[];
1620
+ };
1621
+ type QueueRequest = {
1622
+ queueName?: string;
1623
+ };
1624
+ declare class Client {
1625
+ http: Requester;
1626
+ private token;
1627
+ constructor(config: ClientConfig);
1628
+ /**
1629
+ * Access the urlGroup API.
1630
+ *
1631
+ * Create, read, update or delete urlGroups.
1632
+ */
1633
+ get urlGroups(): UrlGroups;
1634
+ /**
1635
+ * Deprecated. Use urlGroups instead.
1636
+ *
1637
+ * Access the topic API.
1638
+ *
1639
+ * Create, read, update or delete topics.
1640
+ */
1641
+ get topics(): UrlGroups;
1642
+ /**
1643
+ * Access the dlq API.
1644
+ *
1645
+ * List or remove messages from the DLQ.
1646
+ */
1647
+ get dlq(): DLQ;
1648
+ /**
1649
+ * Access the message API.
1650
+ *
1651
+ * Read or cancel messages.
1652
+ */
1653
+ get messages(): Messages;
1654
+ /**
1655
+ * Access the schedule API.
1656
+ *
1657
+ * Create, read or delete schedules.
1658
+ */
1659
+ get schedules(): Schedules;
1660
+ /**
1661
+ * Access the workflow API.
1662
+ *
1663
+ * cancel workflows.
1664
+ */
1665
+ get workflow(): Workflow;
1666
+ /**
1667
+ * Access the queue API.
1668
+ *
1669
+ * Create, read, update or delete queues.
1670
+ */
1671
+ queue(request?: QueueRequest): Queue;
1672
+ /**
1673
+ * Access the Chat API
1674
+ *
1675
+ * Call the create or prompt methods
1676
+ */
1677
+ chat(): Chat;
1678
+ publish<TRequest extends PublishRequest>(request: TRequest): Promise<PublishResponse<TRequest>>;
1679
+ /**
1680
+ * publishJSON is a utility wrapper around `publish` that automatically serializes the body
1681
+ * and sets the `Content-Type` header to `application/json`.
1682
+ */
1683
+ publishJSON<TBody = unknown, TRequest extends PublishRequest<TBody> = PublishRequest<TBody>>(request: TRequest): Promise<PublishResponse<TRequest>>;
1684
+ /**
1685
+ * Batch publish messages to QStash.
1686
+ */
1687
+ batch(request: PublishBatchRequest[]): Promise<PublishResponse<PublishRequest>[]>;
1688
+ /**
1689
+ * Batch publish messages to QStash, serializing each body to JSON.
1690
+ */
1691
+ batchJSON<TBody = unknown, TRequest extends PublishBatchRequest<TBody> = PublishBatchRequest<TBody>>(request: TRequest[]): Promise<PublishResponse<TRequest>[]>;
1692
+ /**
1693
+ * Retrieve your logs.
1694
+ *
1695
+ * The logs endpoint is paginated and returns only 100 logs at a time.
1696
+ * If you want to receive more logs, you can use the cursor to paginate.
1697
+ *
1698
+ * The cursor is a unix timestamp with millisecond precision
1699
+ *
1700
+ * @example
1701
+ * ```ts
1702
+ * let cursor = Date.now()
1703
+ * const logs: Log[] = []
1704
+ * while (cursor > 0) {
1705
+ * const res = await qstash.logs({ cursor })
1706
+ * logs.push(...res.logs)
1707
+ * cursor = res.cursor ?? 0
1708
+ * }
1709
+ * ```
1710
+ */
1711
+ events(request?: EventsRequest): Promise<GetEventsResponse>;
1712
+ }
1713
+ type PublishToApiResponse = {
1714
+ messageId: string;
1715
+ };
1716
+ type PublishToUrlResponse = PublishToApiResponse & {
1717
+ url: string;
1718
+ deduplicated?: boolean;
1719
+ };
1720
+ type PublishToUrlGroupsResponse = PublishToUrlResponse[];
1721
+ type PublishResponse<TRequest> = TRequest extends {
1722
+ url: string;
1723
+ } ? PublishToUrlResponse : TRequest extends {
1724
+ urlGroup: string;
1725
+ } ? PublishToUrlGroupsResponse : PublishToApiResponse;
1726
+
1727
+ export { type AnalyticsConfig as $, type AddEndpointsRequest as A, type BodyInit as B, type ChatRateLimit as C, type ChatCompletion as D, type EventsRequest as E, type FailureFunctionPayload as F, type GetEventsResponse as G, type HTTPMethods as H, type ChatCompletionChunk as I, type StreamEnabled as J, type StreamDisabled as K, type StreamParameter as L, type Message as M, type PromptChatRequest as N, type OpenAIChatModel as O, type PublishBatchRequest as P, type QueueRequest as Q, type RateLimit as R, type Step as S, type ChatRequest as T, type UrlGroup as U, type VerifyRequest as V, type WithCursor as W, custom as X, openai as Y, upstash as Z, type ProviderReturnType as _, type ReceiverConfig as a, type AnalyticsSetup as a0, setupAnalytics as a1, type RouteFunction as a2, type WorkflowServeOptions as a3, Workflow as a4, processOptions as a5, serve as a6, WorkflowContext as a7, DisabledWorkflowContext as a8, StepTypes as a9, type StepType as aa, type RawStep as ab, type SyncStepFunction as ac, type AsyncStepFunction as ad, type StepFunction as ae, type ParallelCallState as af, type FinishCondition as ag, type RequiredExceptFields as ah, type LogLevel as ai, type WorkflowLoggerOptions as aj, WorkflowLogger as ak, SignatureError as b, Receiver as c, type PublishRequest as d, type PublishJsonRequest as e, Client as f, type PublishToApiResponse as g, type PublishToUrlResponse as h, type PublishToUrlGroupsResponse as i, type PublishResponse as j, type MessagePayload as k, Messages as l, type Schedule as m, type CreateScheduleRequest as n, Schedules as o, type Endpoint as p, type RemoveEndpointsRequest as q, UrlGroups as r, type State as s, type Event as t, type EventPayload as u, type GetEventsPayload as v, type HeadersInit as w, type RequestOptions as x, Chat as y, type ChatCompletionMessage as z };