@upstash/qstash 2.6.4-workflow-alpha.4 → 2.6.5

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