@upstash/qstash 2.7.1 → 2.7.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.
@@ -434,6 +434,9 @@ declare class DLQ {
434
434
  }>;
435
435
  }
436
436
 
437
+ type Unit = "s" | "m" | "h" | "d";
438
+ type Duration = `${bigint}${Unit}`;
439
+
437
440
  declare class Chat {
438
441
  private http;
439
442
  private token;
@@ -582,7 +585,7 @@ type CreateScheduleRequest = {
582
585
  *
583
586
  * @default undefined
584
587
  */
585
- delay?: number;
588
+ delay?: Duration | number;
586
589
  /**
587
590
  * In case your destination server is unavailable or returns a status code outside of the 200-299
588
591
  * range, we will retry the request after a certain amount of time.
@@ -628,7 +631,7 @@ type CreateScheduleRequest = {
628
631
  *
629
632
  * @default undefined
630
633
  */
631
- timeout?: number;
634
+ timeout?: Duration | number;
632
635
  /**
633
636
  * Schedule id to use.
634
637
  *
@@ -796,7 +799,7 @@ type PublishRequest<TBody = BodyInit> = {
796
799
  *
797
800
  * @default undefined
798
801
  */
799
- delay?: number;
802
+ delay?: Duration | number;
800
803
  /**
801
804
  * Optionally set the absolute delay of this message.
802
805
  * This will override the delay option.
@@ -869,7 +872,7 @@ type PublishRequest<TBody = BodyInit> = {
869
872
  *
870
873
  * @default undefined
871
874
  */
872
- timeout?: number;
875
+ timeout?: Duration | number;
873
876
  } & ({
874
877
  /**
875
878
  * The url where the message should be sent to.
@@ -1,5 +1,5 @@
1
1
  import*as Pe from"jose";import ke from"crypto-js";var q=class extends Error{constructor(e){super(e),this.name="SignatureError"}},J=class{currentSigningKey;nextSigningKey;constructor(e){this.currentSigningKey=e.currentSigningKey,this.nextSigningKey=e.nextSigningKey}async verify(e){return await this.verifyWithKey(this.currentSigningKey,e)?!0:this.verifyWithKey(this.nextSigningKey,e)}async verifyWithKey(e,t){let n=(await Pe.jwtVerify(t.signature,new TextEncoder().encode(e),{issuer:"Upstash",clockTolerance:t.clockTolerance}).catch(a=>{throw new q(a.message)})).payload;if(t.url!==void 0&&n.sub!==t.url)throw new q(`invalid subject: ${n.sub}, want: ${t.url}`);let o=ke.SHA256(t.body).toString(ke.enc.Base64url),i=new RegExp(/=+$/);if(n.body.replace(i,"")!==o.replace(i,""))throw new q(`body hash does not match, want: ${n.body}, got: ${o}`);return!0}};var Q=class{http;constructor(e){this.http=e}async listMessages(e){let t={...e?.filter,topicName:e?.filter?.urlGroup},s=await this.http.request({method:"GET",path:["v2","dlq"],query:{cursor:e?.cursor,count:e?.count,...t}});return{messages:s.messages.map(n=>({...n,urlGroup:n.topicName})),cursor:s.cursor}}async delete(e){return await this.http.request({method:"DELETE",path:["v2","dlq",e],parseResponseAsJson:!1})}async deleteMany(e){return await this.http.request({method:"DELETE",path:["v2","dlq"],headers:{"Content-Type":"application/json"},body:JSON.stringify({dlqIds:e.dlqIds})})}};var P=class extends Error{constructor(e){super(e),this.name="QstashError"}},K=class extends P{limit;remaining;reset;constructor(e){super(`Exceeded burst rate limit. ${JSON.stringify(e)} `),this.name="QstashRatelimitError",this.limit=e.limit,this.remaining=e.remaining,this.reset=e.reset}},j=class extends P{limitRequests;limitTokens;remainingRequests;remainingTokens;resetRequests;resetTokens;constructor(e){super(`Exceeded chat rate limit. ${JSON.stringify(e)} `),this.limitRequests=e["limit-requests"],this.limitTokens=e["limit-tokens"],this.remainingRequests=e["remaining-requests"],this.remainingTokens=e["remaining-tokens"],this.resetRequests=e["reset-requests"],this.resetTokens=e["reset-tokens"]}},z=class extends P{limit;remaining;reset;constructor(e){super(`Exceeded daily rate limit. ${JSON.stringify(e)} `),this.limit=e.limit,this.remaining=e.remaining,this.reset=e.reset,this.name="QstashChatRatelimitError"}},d=class extends P{constructor(e){super(e),this.name="QStashWorkflowError"}},R=class extends Error{stepInfo;stepName;constructor(e,t){super(`This is an QStash Workflow error thrown after a step executes. It is expected to be raised. Make sure that you await for each step. Also, if you are using try/catch blocks, you should not wrap context.run/sleep/sleepUntil/call methods with try/catch. Aborting workflow after executing step '${e}'.`),this.name="QStashWorkflowAbort",this.stepName=e,this.stepInfo=t}},ve=r=>r instanceof Error?{error:r.name,message:r.message}:{error:"Error",message:"An error occured while executing workflow."};var V=class{baseUrl;authorization;options;retry;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.authorization=e.authorization,this.retry=typeof e.retry=="boolean"&&!e.retry?{attempts:1,backoff:()=>0}:{attempts:e.retry?.retries?e.retry.retries+1:5,backoff:e.retry?.backoff??(t=>Math.exp(t)*50)}}async request(e){let{response:t}=await this.requestWithBackoff(e);if(e.parseResponseAsJson!==!1)return await t.json()}async*requestStream(e){let{response:t}=await this.requestWithBackoff(e);if(!t.body)throw new Error("No response body");let n=t.body.getReader(),o=new TextDecoder;try{for(;;){let{done:i,value:a}=await n.read();if(i)break;let p=o.decode(a,{stream:!0}).split(`
2
- `).filter(Boolean);for(let c of p)if(c.startsWith("data: ")){let m=c.slice(6);if(m==="[DONE]")break;yield JSON.parse(m)}}}finally{await n.cancel()}}requestWithBackoff=async e=>{let[t,s]=this.processRequest(e),n,o;for(let i=0;i<this.retry.attempts;i++)try{n=await fetch(t.toString(),s);break}catch(a){o=a,await new Promise(l=>setTimeout(l,this.retry.backoff(i)))}if(!n)throw o??new Error("Exhausted all retries");return await this.checkResponse(n),{response:n,error:o}};processRequest=e=>{let t=new Headers(e.headers);t.has("Authorization")||t.set("Authorization",this.authorization);let s={method:e.method,headers:t,body:e.body,keepalive:e.keepalive},n=new URL([e.baseUrl??this.baseUrl,...e.path].join("/"));if(e.query)for(let[o,i]of Object.entries(e.query))i!==void 0&&n.searchParams.set(o,i.toString());return[n.toString(),s]};async checkResponse(e){if(e.status===429)throw e.headers.get("x-ratelimit-limit-requests")?new j({"limit-requests":e.headers.get("x-ratelimit-limit-requests"),"limit-tokens":e.headers.get("x-ratelimit-limit-tokens"),"remaining-requests":e.headers.get("x-ratelimit-remaining-requests"),"remaining-tokens":e.headers.get("x-ratelimit-remaining-tokens"),"reset-requests":e.headers.get("x-ratelimit-reset-requests"),"reset-tokens":e.headers.get("x-ratelimit-reset-tokens")}):e.headers.get("RateLimit-Limit")?new z({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new K({limit:e.headers.get("Burst-RateLimit-Limit"),remaining:e.headers.get("Burst-RateLimit-Remaining"),reset:e.headers.get("Burst-RateLimit-Reset")});if(e.status<200||e.status>=300){let t=await e.text();throw new P(t.length>0?t:`Error: status=${e.status}`)}}};var I=(r,e,t,s)=>{if(!r)return{};switch(r.name){case"helicone":switch(s){case"upstash":return{baseURL:"https://qstash.helicone.ai/llm/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,Authorization:`Bearer ${e}`}};default:return{baseURL:"https://gateway.helicone.ai/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,"Helicone-Target-Url":t,Authorization:`Bearer ${e}`}}}default:throw new Error("Unknown analytics provider")}};var Y=class r{http;token;constructor(e,t){this.http=e,this.token=t}static toChatRequest(e){let t=[];return t.push({role:"system",content:e.system},{role:"user",content:e.user}),{...e,messages:t}}create=async e=>{if(e.provider.owner!="upstash")return this.createThirdParty(e);let t=JSON.stringify(e),s,n={"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,..."stream"in e&&e.stream?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{}};if(e.analytics){let{baseURL:i,defaultHeaders:a}=I({name:"helicone",token:e.analytics.token},this.getAuthorizationToken(),e.provider.baseUrl,"upstash");n={...n,...a},s=i}let o=e.analytics?[]:["llm","v1","chat","completions"];return"stream"in e&&e.stream?this.http.requestStream({path:o,method:"POST",headers:n,baseUrl:s,body:t}):this.http.request({path:o,method:"POST",headers:n,baseUrl:s,body:t})};createThirdParty=async e=>{let{baseUrl:t,token:s,owner:n}=e.provider;if(n==="upstash")throw new Error("Upstash is not 3rd party provider!");delete e.provider,delete e.system;let o=e.analytics;delete e.analytics;let i=JSON.stringify(e),a=o?.name&&o.token,l=o?.name&&o.token?I({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},p="stream"in e&&e.stream,c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...p?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...l.defaultHeaders};return await this.http[p?"requestStream":"request"]({path:a?[]:["v1","chat","completions"],method:"POST",headers:c,body:i,baseUrl:l.baseURL})};getAuthorizationToken(){let t=String(this.http.authorization).match(/Bearer (.+)/);if(!t)throw new Error("Invalid authorization header format");return t[1]}prompt=async e=>{let t=r.toChatRequest(e);return this.create(t)}};function W(r,e,t){if(!r.api)return;let s=r.api.provider,n=r.api.analytics;if(s?.owner==="upstash"){ze(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ve(s),a=n?I({name:n.name,token:n.token},i,o,"custom"):void 0;a?(Ee(e,a),r.url=a.baseURL):(r.url=`${o}/v1/chat/completions`,e.set("Authorization",`Bearer ${i}`))}function ze(r,e,t,s){if(s){let n=I({name:s.name,token:s.token},String(t.authorization).split("Bearer ")[1],r.api?.provider?.baseUrl,"upstash");Ee(e,n),r.url=n.baseURL}else r.api={name:"llm"}}function Ve(r){if(!r?.baseUrl)throw new Error("baseUrl cannot be empty or undefined!");if(!r.token)throw new Error("token cannot be empty or undefined!");return{baseUrl:r.baseUrl,token:r.token}}function Ee(r,e){r.set("Helicone-Auth",e.defaultHeaders?.["Helicone-Auth"]??""),r.set("Authorization",e.defaultHeaders?.Authorization??""),e.defaultHeaders?.["Helicone-Target-Url"]&&r.set("Helicone-Target-Url",e.defaultHeaders["Helicone-Target-Url"])}function A(r){if(r.api?.name==="llm"&&!r.callback)throw new TypeError("Callback cannot be undefined when using LLM")}var X=class{http;constructor(e){this.http=e}async get(e){let t=await this.http.request({method:"GET",path:["v2","messages",e]});return{...t,urlGroup:t.topicName}}async delete(e){return await this.http.request({method:"DELETE",path:["v2","messages",e],parseResponseAsJson:!1})}async deleteMany(e){return(await this.http.request({method:"DELETE",path:["v2","messages"],headers:{"Content-Type":"application/json"},body:JSON.stringify({messageIds:e})})).cancelled}async deleteAll(){return(await this.http.request({method:"DELETE",path:["v2","messages"]})).cancelled}};var Ye=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function v(r){let e=[...r.keys()].filter(t=>!Ye(t));for(let t of e){let s=r.get(t);s!==null&&r.set(`Upstash-Forward-${t}`,s),r.delete(t)}return r}function _(r){let e=v(new Headers(r.headers));return e.set("Upstash-Method",r.method??"POST"),r.delay!==void 0&&e.set("Upstash-Delay",`${r.delay.toFixed(0)}s`),r.notBefore!==void 0&&e.set("Upstash-Not-Before",r.notBefore.toFixed(0)),r.deduplicationId!==void 0&&e.set("Upstash-Deduplication-Id",r.deduplicationId),r.contentBasedDeduplication!==void 0&&e.set("Upstash-Content-Based-Deduplication","true"),r.retries!==void 0&&e.set("Upstash-Retries",r.retries.toFixed(0)),r.callback!==void 0&&e.set("Upstash-Callback",r.callback),r.failureCallback!==void 0&&e.set("Upstash-Failure-Callback",r.failureCallback),r.timeout!==void 0&&e.set("Upstash-Timeout",`${r.timeout}s`),e}function F(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var Ce="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",Xe=21;function Ie(){return[...crypto.getRandomValues(new Uint8Array(Xe))].map(r=>Ce[r%Ce.length]).join("")}var Z=class{http;queueName;constructor(e,t){this.http=e,this.queueName=t}async upsert(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t={queueName:this.queueName,parallelism:e.parallelism??1,paused:e.paused??!1};await this.http.request({method:"POST",path:["v2","queues"],headers:{"Content-Type":"application/json"},body:JSON.stringify(t),parseResponseAsJson:!1})}async get(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");return await this.http.request({method:"GET",path:["v2","queues",this.queueName]})}async list(){return await this.http.request({method:"GET",path:["v2","queues"]})}async delete(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"DELETE",path:["v2","queues",this.queueName],parseResponseAsJson:!1})}async enqueue(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t=_(e),s=F(e);return await this.http.request({path:["v2","enqueue",this.queueName,s],body:e.body,headers:t,method:"POST"})}async enqueueJSON(e){let t=v(new Headers(e.headers));return t.set("Content-Type","application/json"),A(e),W(e,t,this.http),await this.enqueue({...e,body:JSON.stringify(e.body),headers:t})}async pause(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"pause"],parseResponseAsJson:!1})}async resume(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"resume"],parseResponseAsJson:!1})}};var ee=class{http;constructor(e){this.http=e}async create(e){let t=v(new Headers(e.headers));return t.has("Content-Type")||t.set("Content-Type","application/json"),t.set("Upstash-Cron",e.cron),e.method!==void 0&&t.set("Upstash-Method",e.method),e.delay!==void 0&&t.set("Upstash-Delay",`${e.delay.toFixed(0)}s`),e.retries!==void 0&&t.set("Upstash-Retries",e.retries.toFixed(0)),e.callback!==void 0&&t.set("Upstash-Callback",e.callback),e.failureCallback!==void 0&&t.set("Upstash-Failure-Callback",e.failureCallback),e.timeout!==void 0&&t.set("Upstash-Timeout",`${e.timeout}s`),e.scheduleId!==void 0&&t.set("Upstash-Schedule-Id",e.scheduleId),await this.http.request({method:"POST",headers:t,path:["v2","schedules",e.destination],body:e.body})}async get(e){return await this.http.request({method:"GET",path:["v2","schedules",e]})}async list(){return await this.http.request({method:"GET",path:["v2","schedules"]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","schedules",e],parseResponseAsJson:!1})}async pause({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"pause"],parseResponseAsJson:!1})}async resume({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"resume"],parseResponseAsJson:!1})}};var te=class{http;constructor(e){this.http=e}async addEndpoints(e){await this.http.request({method:"POST",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async removeEndpoints(e){await this.http.request({method:"DELETE",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async list(){return await this.http.request({method:"GET",path:["v2","topics"]})}async get(e){return await this.http.request({method:"GET",path:["v2","topics",e]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","topics",e],parseResponseAsJson:!1})}};var x=class{http;token;constructor(e){this.http=new V({retry:e.retry,baseUrl:e.baseUrl?e.baseUrl.replace(/\/$/,""):"https://qstash.upstash.io",authorization:`Bearer ${e.token}`}),this.token=e.token}get urlGroups(){return new te(this.http)}get topics(){return this.urlGroups}get dlq(){return new Q(this.http)}get messages(){return new X(this.http)}get schedules(){return new ee(this.http)}get workflow(){return new re(this.http)}queue(e){return new Z(this.http,e?.queueName)}chat(){return new Y(this.http,this.token)}async publish(e){let t=_(e);return await this.http.request({path:["v2","publish",F(e)],body:e.body,headers:t,method:"POST"})}async publishJSON(e){let t=v(new Headers(e.headers));return t.set("Content-Type","application/json"),A(e),W(e,t,this.http),await this.publish({...e,headers:t,body:JSON.stringify(e.body)})}async batch(e){let t=[];for(let o of e){let i=_(o),a=Object.fromEntries(i.entries());t.push({destination:F(o),headers:a,body:o.body,...o.queueName&&{queue:o.queueName}})}let s=await this.http.request({path:["v2","batch"],body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST"});return Array.isArray(s)?s:[s]}async batchJSON(e){for(let s of e)"body"in s&&(s.body=JSON.stringify(s.body)),s.headers=new Headers(s.headers),A(s),W(s,s.headers,this.http),s.headers.set("Content-Type","application/json");return await this.batch(e)}async events(e){let t={};e?.cursor&&e.cursor>0&&(t.cursor=e.cursor.toString());for(let[n,o]of Object.entries(e?.filter??{}))typeof o=="number"&&o<0||(n==="urlGroup"?t.topicName=o.toString():typeof o<"u"&&(t[n]=o.toString()));let s=await this.http.request({path:["v2","events"],method:"GET",query:t});return{cursor:s.cursor,events:s.events.map(n=>({...n,urlGroup:n.topicName}))}}};var Ze={withStackTrace:!1},Ue=(r,e,t=Ze)=>{let s=e.isOk()?{type:"Ok",value:e.value}:{type:"Err",value:e.error},n=t.withStackTrace?new Error().stack:void 0;return{data:s,message:r,stack:n}};function U(r,e,t,s){function n(o){return o instanceof t?o:new t(function(i){i(o)})}return new(t||(t=Promise))(function(o,i){function a(c){try{p(s.next(c))}catch(m){i(m)}}function l(c){try{p(s.throw(c))}catch(m){i(m)}}function p(c){c.done?o(c.value):n(c.value).then(a,l)}p((s=s.apply(r,[])).next())})}function xe(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],s=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&s>=r.length&&(r=void 0),{value:r&&r[s++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function E(r){return this instanceof E?(this.v=r,this):new E(r)}function et(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(r,e||[]),n,o=[];return n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n;function i(u){s[u]&&(n[u]=function(w){return new Promise(function(f,g){o.push([u,w,f,g])>1||a(u,w)})})}function a(u,w){try{l(s[u](w))}catch(f){m(o[0][3],f)}}function l(u){u.value instanceof E?Promise.resolve(u.value.v).then(p,c):m(o[0][2],u)}function p(u){a("next",u)}function c(u){a("throw",u)}function m(u,w){u(w),o.shift(),o.length&&a(o[0][0],o[0][1])}}function tt(r){var e,t;return e={},s("next"),s("throw",function(n){throw n}),s("return"),e[Symbol.iterator]=function(){return this},e;function s(n,o){e[n]=r[n]?function(i){return(t=!t)?{value:E(r[n](i)),done:n==="return"}:o?o(i):i}:o}}function rt(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof xe=="function"?xe(r):r[Symbol.iterator](),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(o){t[o]=r[o]&&function(i){return new Promise(function(a,l){i=r[o](i),n(a,l,i.done,i.value)})}}function n(o,i,a,l){Promise.resolve(l).then(function(p){o({value:p,done:a})},i)}}var k=class r{constructor(e){this._promise=e}static fromSafePromise(e){let t=e.then(s=>new T(s));return new r(t)}static fromPromise(e,t){let s=e.then(n=>new T(n)).catch(n=>new b(t(n)));return new r(s)}static fromThrowable(e,t){return(...s)=>new r(U(this,void 0,void 0,function*(){try{return new T(yield e(...s))}catch(n){return new b(t?t(n):n)}}))}static combine(e){return st(e)}static combineWithAllErrors(e){return nt(e)}map(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isErr()?new b(t.error):new T(yield e(t.value))})))}andThrough(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){if(t.isErr())return new b(t.error);let s=yield e(t.value);return s.isErr()?new b(s.error):new T(t.value)})))}andTee(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){if(t.isErr())return new b(t.error);try{yield e(t.value)}catch{}return new T(t.value)})))}mapErr(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isOk()?new T(t.value):new b(yield e(t.error))})))}andThen(e){return new r(this._promise.then(t=>{if(t.isErr())return new b(t.error);let s=e(t.value);return s instanceof r?s._promise:s}))}orElse(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isErr()?e(t.error):new T(t.value)})))}match(e,t){return this._promise.then(s=>s.match(e,t))}unwrapOr(e){return this._promise.then(t=>t.unwrapOr(e))}safeUnwrap(){return et(this,arguments,function*(){return yield E(yield E(yield*tt(rt(yield E(this._promise.then(t=>t.safeUnwrap()))))))})}then(e,t){return this._promise.then(e,t)}};var ge=r=>new k(Promise.resolve(new b(r))),Mt=k.fromPromise,Gt=k.fromSafePromise,$t=k.fromThrowable,Oe=r=>{let e=h([]);for(let t of r)if(t.isErr()){e=y(t.error);break}else e.map(s=>s.push(t.value));return e},st=r=>k.fromSafePromise(Promise.all(r)).andThen(Oe),Ne=r=>{let e=h([]);for(let t of r)t.isErr()&&e.isErr()?e.error.push(t.error):t.isErr()&&e.isOk()?e=y([t.error]):t.isOk()&&e.isOk()&&e.value.push(t.value);return e},nt=r=>k.fromSafePromise(Promise.all(r)).andThen(Ne),we;(function(r){function e(n,o){return(...i)=>{try{let a=n(...i);return h(a)}catch(a){return y(o?o(a):a)}}}r.fromThrowable=e;function t(n){return Oe(n)}r.combine=t;function s(n){return Ne(n)}r.combineWithAllErrors=s})(we||(we={}));var h=r=>new T(r);function y(r){return new b(r)}var T=class{constructor(e){this.value=e}isOk(){return!0}isErr(){return!this.isOk()}map(e){return h(e(this.value))}mapErr(e){return h(this.value)}andThen(e){return e(this.value)}andThrough(e){return e(this.value).map(t=>this.value)}andTee(e){try{e(this.value)}catch{}return h(this.value)}orElse(e){return h(this.value)}asyncAndThen(e){return e(this.value)}asyncAndThrough(e){return e(this.value).map(()=>this.value)}asyncMap(e){return k.fromSafePromise(e(this.value))}unwrapOr(e){return this.value}match(e,t){return e(this.value)}safeUnwrap(){let e=this.value;return function*(){return e}()}_unsafeUnwrap(e){return this.value}_unsafeUnwrapErr(e){throw Ue("Called `_unsafeUnwrapErr` on an Ok",this,e)}},b=class{constructor(e){this.error=e}isOk(){return!1}isErr(){return!this.isOk()}map(e){return y(this.error)}mapErr(e){return y(e(this.error))}andThrough(e){return y(this.error)}andTee(e){return y(this.error)}andThen(e){return y(this.error)}orElse(e){return e(this.error)}asyncAndThen(e){return ge(this.error)}asyncAndThrough(e){return ge(this.error)}asyncMap(e){return ge(this.error)}unwrapOr(e){return e}match(e,t){return t(this.error)}safeUnwrap(){let e=this.error;return function*(){throw yield y(e),new Error("Do not use this generator out of `safeTry`")}()}_unsafeUnwrap(e){throw Ue("Called `_unsafeUnwrap` on an Err",this,e)}_unsafeUnwrapErr(e){return this.error}},Jt=we.fromThrowable;var H="Upstash-Workflow-RunId",Le="Upstash-Workflow-Init",qe="Upstash-Workflow-Url",se="Upstash-Workflow-Is-Failure",B="1",ne="Upstash-Workflow-Sdk-Version",We="application/json";var Ae=["Initial","Run","SleepFor","SleepUntil","Call"];var _e=async(r,e)=>{let t=oe("true",r.workflowRunId,r.url,r.headers,void 0,r.failureUrl);await e?.log("SUBMIT","SUBMIT_FIRST_INVOCATION",{headers:t,requestPayload:r.requestPayload,url:r.url});try{return await r.qstashClient.publishJSON({headers:t,method:"POST",body:r.requestPayload,url:r.url}),h("success")}catch(s){return y(s)}},Fe=async({onCleanup:r,onStep:e})=>{try{return await e(),await r(),h("workflow-finished")}catch(t){let s=t;return s instanceof R?h("step-finished"):y(s)}},He=async(r,e,t=!1)=>{await e?.log("SUBMIT","SUBMIT_CLEANUP",{deletedWorkflowRunId:r.workflowRunId});let s=await r.qstashClient.http.request({path:["v2","workflows","runs",`${r.workflowRunId}?cancel=${t}`],method:"DELETE",parseResponseAsJson:!1});await e?.log("SUBMIT","SUBMIT_CLEANUP",s)},D=r=>{let e=new Headers,t=r.entries();for(let[s,n]of t){let o=s.toLowerCase();!o.startsWith("upstash-workflow-")&&!o.startsWith("x-vercel-")&&!o.startsWith("x-forwarded-")&&e.append(s,n)}return e},Be=async(r,e,t,s,n,o)=>{try{if(r.headers.get("Upstash-Workflow-Callback")){let i=JSON.parse(e);if(!(i.status>=200&&i.status<300))return await o?.log("WARN","SUBMIT_THIRD_PARTY_RESULT",i),h("call-will-retry");let a=r.headers.get(H),l=r.headers.get("Upstash-Workflow-StepId"),p=r.headers.get("Upstash-Workflow-StepName"),c=r.headers.get("Upstash-Workflow-StepType"),m=r.headers.get("Upstash-Workflow-Concurrent"),u=r.headers.get("Upstash-Workflow-ContentType");if(!(a&&l&&p&&Ae.includes(c)&&m&&u))throw new Error(`Missing info in callback message source header: ${JSON.stringify({workflowRunId:a,stepIdString:l,stepName:p,stepType:c,concurrentString:m,contentType:u})}`);let w=D(r.headers),f=oe("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:p,stepType:c,out:Buffer.from(i.body,"base64").toString(),concurrent:Number(m)};await o?.log("SUBMIT","SUBMIT_THIRD_PARTY_RESULT",{step:g,headers:f,url:s});let S=await t.publishJSON({headers:f,method:"POST",body:g,url:s});return await o?.log("SUBMIT","SUBMIT_THIRD_PARTY_RESULT",{messageId:S.messageId}),h("is-call-return")}else return h("continue-workflow")}catch(i){let a=r.headers.get("Upstash-Workflow-Callback");return y(new d(`Error when handling call return (isCallReturn=${a}): ${i}`))}},oe=(r,e,t,s,n,o)=>{let i={[Le]:r,[H]:e,[qe]:t,[`Upstash-Forward-${ne}`]:B,...o?{[`Upstash-Failure-Callback-Forward-${se}`]:"true","Upstash-Failure-Callback":o}:{}};if(s)for(let a of s.keys())n?.callHeaders?i[`Upstash-Callback-Forward-${a}`]=s.get(a):i[`Upstash-Forward-${a}`]=s.get(a);if(n?.callHeaders){let a=Object.fromEntries(Object.entries(n.callHeaders).map(([p,c])=>[`Upstash-Forward-${p}`,c])),l=n.callHeaders["Content-Type"];return{...i,...a,"Upstash-Callback":t,"Upstash-Callback-Workflow-RunId":e,"Upstash-Callback-Workflow-CallType":"fromCallback","Upstash-Callback-Workflow-Init":"false","Upstash-Callback-Workflow-Url":t,"Upstash-Callback-Forward-Upstash-Workflow-Callback":"true","Upstash-Callback-Forward-Upstash-Workflow-StepId":n.stepId.toString(),"Upstash-Callback-Forward-Upstash-Workflow-StepName":n.stepName,"Upstash-Callback-Forward-Upstash-Workflow-StepType":n.stepType,"Upstash-Callback-Forward-Upstash-Workflow-Concurrent":n.concurrent.toString(),"Upstash-Callback-Forward-Upstash-Workflow-ContentType":l??We,"Upstash-Workflow-CallType":"toCallback"}}return i},De=async(r,e,t)=>{if(t)try{if(!e)throw new Error("`Upstash-Signature` header is not passed.");if(!await t.verify({body:r,signature:e}))throw new Error("Signature in `Upstash-Signature` header is not valid")}catch(s){throw new d(`Failed to verify that the Workflow request comes from QStash: ${s}
2
+ `).filter(Boolean);for(let c of p)if(c.startsWith("data: ")){let m=c.slice(6);if(m==="[DONE]")break;yield JSON.parse(m)}}}finally{await n.cancel()}}requestWithBackoff=async e=>{let[t,s]=this.processRequest(e),n,o;for(let i=0;i<this.retry.attempts;i++)try{n=await fetch(t.toString(),s);break}catch(a){o=a,await new Promise(l=>setTimeout(l,this.retry.backoff(i)))}if(!n)throw o??new Error("Exhausted all retries");return await this.checkResponse(n),{response:n,error:o}};processRequest=e=>{let t=new Headers(e.headers);t.has("Authorization")||t.set("Authorization",this.authorization);let s={method:e.method,headers:t,body:e.body,keepalive:e.keepalive},n=new URL([e.baseUrl??this.baseUrl,...e.path].join("/"));if(e.query)for(let[o,i]of Object.entries(e.query))i!==void 0&&n.searchParams.set(o,i.toString());return[n.toString(),s]};async checkResponse(e){if(e.status===429)throw e.headers.get("x-ratelimit-limit-requests")?new j({"limit-requests":e.headers.get("x-ratelimit-limit-requests"),"limit-tokens":e.headers.get("x-ratelimit-limit-tokens"),"remaining-requests":e.headers.get("x-ratelimit-remaining-requests"),"remaining-tokens":e.headers.get("x-ratelimit-remaining-tokens"),"reset-requests":e.headers.get("x-ratelimit-reset-requests"),"reset-tokens":e.headers.get("x-ratelimit-reset-tokens")}):e.headers.get("RateLimit-Limit")?new z({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new K({limit:e.headers.get("Burst-RateLimit-Limit"),remaining:e.headers.get("Burst-RateLimit-Remaining"),reset:e.headers.get("Burst-RateLimit-Reset")});if(e.status<200||e.status>=300){let t=await e.text();throw new P(t.length>0?t:`Error: status=${e.status}`)}}};var I=(r,e,t,s)=>{if(!r)return{};switch(r.name){case"helicone":switch(s){case"upstash":return{baseURL:"https://qstash.helicone.ai/llm/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,Authorization:`Bearer ${e}`}};default:return{baseURL:"https://gateway.helicone.ai/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,"Helicone-Target-Url":t,Authorization:`Bearer ${e}`}}}default:throw new Error("Unknown analytics provider")}};var Y=class r{http;token;constructor(e,t){this.http=e,this.token=t}static toChatRequest(e){let t=[];return t.push({role:"system",content:e.system},{role:"user",content:e.user}),{...e,messages:t}}create=async e=>{if(e.provider.owner!="upstash")return this.createThirdParty(e);let t=JSON.stringify(e),s,n={"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,..."stream"in e&&e.stream?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{}};if(e.analytics){let{baseURL:i,defaultHeaders:a}=I({name:"helicone",token:e.analytics.token},this.getAuthorizationToken(),e.provider.baseUrl,"upstash");n={...n,...a},s=i}let o=e.analytics?[]:["llm","v1","chat","completions"];return"stream"in e&&e.stream?this.http.requestStream({path:o,method:"POST",headers:n,baseUrl:s,body:t}):this.http.request({path:o,method:"POST",headers:n,baseUrl:s,body:t})};createThirdParty=async e=>{let{baseUrl:t,token:s,owner:n}=e.provider;if(n==="upstash")throw new Error("Upstash is not 3rd party provider!");delete e.provider,delete e.system;let o=e.analytics;delete e.analytics;let i=JSON.stringify(e),a=o?.name&&o.token,l=o?.name&&o.token?I({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},p="stream"in e&&e.stream,c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...p?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...l.defaultHeaders};return await this.http[p?"requestStream":"request"]({path:a?[]:["v1","chat","completions"],method:"POST",headers:c,body:i,baseUrl:l.baseURL})};getAuthorizationToken(){let t=String(this.http.authorization).match(/Bearer (.+)/);if(!t)throw new Error("Invalid authorization header format");return t[1]}prompt=async e=>{let t=r.toChatRequest(e);return this.create(t)}};function W(r,e,t){if(!r.api)return;let s=r.api.provider,n=r.api.analytics;if(s?.owner==="upstash"){ze(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ve(s),a=n?I({name:n.name,token:n.token},i,o,"custom"):void 0;a?(Ee(e,a),r.url=a.baseURL):(r.url=`${o}/v1/chat/completions`,e.set("Authorization",`Bearer ${i}`))}function ze(r,e,t,s){if(s){let n=I({name:s.name,token:s.token},String(t.authorization).split("Bearer ")[1],r.api?.provider?.baseUrl,"upstash");Ee(e,n),r.url=n.baseURL}else r.api={name:"llm"}}function Ve(r){if(!r?.baseUrl)throw new Error("baseUrl cannot be empty or undefined!");if(!r.token)throw new Error("token cannot be empty or undefined!");return{baseUrl:r.baseUrl,token:r.token}}function Ee(r,e){r.set("Helicone-Auth",e.defaultHeaders?.["Helicone-Auth"]??""),r.set("Authorization",e.defaultHeaders?.Authorization??""),e.defaultHeaders?.["Helicone-Target-Url"]&&r.set("Helicone-Target-Url",e.defaultHeaders["Helicone-Target-Url"])}function A(r){if(r.api?.name==="llm"&&!r.callback)throw new TypeError("Callback cannot be undefined when using LLM")}var X=class{http;constructor(e){this.http=e}async get(e){let t=await this.http.request({method:"GET",path:["v2","messages",e]});return{...t,urlGroup:t.topicName}}async delete(e){return await this.http.request({method:"DELETE",path:["v2","messages",e],parseResponseAsJson:!1})}async deleteMany(e){return(await this.http.request({method:"DELETE",path:["v2","messages"],headers:{"Content-Type":"application/json"},body:JSON.stringify({messageIds:e})})).cancelled}async deleteAll(){return(await this.http.request({method:"DELETE",path:["v2","messages"]})).cancelled}};var Ye=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function v(r){let e=[...r.keys()].filter(t=>!Ye(t));for(let t of e){let s=r.get(t);s!==null&&r.set(`Upstash-Forward-${t}`,s),r.delete(t)}return r}function _(r){let e=v(new Headers(r.headers));return e.set("Upstash-Method",r.method??"POST"),r.delay!==void 0&&(typeof r.delay=="string"?e.set("Upstash-Delay",r.delay):e.set("Upstash-Delay",`${r.delay.toFixed(0)}s`)),r.notBefore!==void 0&&e.set("Upstash-Not-Before",r.notBefore.toFixed(0)),r.deduplicationId!==void 0&&e.set("Upstash-Deduplication-Id",r.deduplicationId),r.contentBasedDeduplication!==void 0&&e.set("Upstash-Content-Based-Deduplication","true"),r.retries!==void 0&&e.set("Upstash-Retries",r.retries.toFixed(0)),r.callback!==void 0&&e.set("Upstash-Callback",r.callback),r.failureCallback!==void 0&&e.set("Upstash-Failure-Callback",r.failureCallback),r.timeout!==void 0&&(typeof r.timeout=="string"?e.set("Upstash-Timeout",r.timeout):e.set("Upstash-Timeout",`${r.timeout}s`)),e}function F(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var Ce="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",Xe=21;function Ie(){return[...crypto.getRandomValues(new Uint8Array(Xe))].map(r=>Ce[r%Ce.length]).join("")}var Z=class{http;queueName;constructor(e,t){this.http=e,this.queueName=t}async upsert(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t={queueName:this.queueName,parallelism:e.parallelism??1,paused:e.paused??!1};await this.http.request({method:"POST",path:["v2","queues"],headers:{"Content-Type":"application/json"},body:JSON.stringify(t),parseResponseAsJson:!1})}async get(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");return await this.http.request({method:"GET",path:["v2","queues",this.queueName]})}async list(){return await this.http.request({method:"GET",path:["v2","queues"]})}async delete(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"DELETE",path:["v2","queues",this.queueName],parseResponseAsJson:!1})}async enqueue(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t=_(e),s=F(e);return await this.http.request({path:["v2","enqueue",this.queueName,s],body:e.body,headers:t,method:"POST"})}async enqueueJSON(e){let t=v(new Headers(e.headers));return t.set("Content-Type","application/json"),A(e),W(e,t,this.http),await this.enqueue({...e,body:JSON.stringify(e.body),headers:t})}async pause(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"pause"],parseResponseAsJson:!1})}async resume(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"resume"],parseResponseAsJson:!1})}};var ee=class{http;constructor(e){this.http=e}async create(e){let t=v(new Headers(e.headers));return t.has("Content-Type")||t.set("Content-Type","application/json"),t.set("Upstash-Cron",e.cron),e.method!==void 0&&t.set("Upstash-Method",e.method),e.delay!==void 0&&(typeof e.delay=="string"?t.set("Upstash-Delay",e.delay):t.set("Upstash-Delay",`${e.delay.toFixed(0)}s`)),e.retries!==void 0&&t.set("Upstash-Retries",e.retries.toFixed(0)),e.callback!==void 0&&t.set("Upstash-Callback",e.callback),e.failureCallback!==void 0&&t.set("Upstash-Failure-Callback",e.failureCallback),e.timeout!==void 0&&(typeof e.timeout=="string"?t.set("Upstash-Timeout",e.timeout):t.set("Upstash-Timeout",`${e.timeout}s`)),e.scheduleId!==void 0&&t.set("Upstash-Schedule-Id",e.scheduleId),await this.http.request({method:"POST",headers:t,path:["v2","schedules",e.destination],body:e.body})}async get(e){return await this.http.request({method:"GET",path:["v2","schedules",e]})}async list(){return await this.http.request({method:"GET",path:["v2","schedules"]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","schedules",e],parseResponseAsJson:!1})}async pause({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"pause"],parseResponseAsJson:!1})}async resume({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"resume"],parseResponseAsJson:!1})}};var te=class{http;constructor(e){this.http=e}async addEndpoints(e){await this.http.request({method:"POST",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async removeEndpoints(e){await this.http.request({method:"DELETE",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async list(){return await this.http.request({method:"GET",path:["v2","topics"]})}async get(e){return await this.http.request({method:"GET",path:["v2","topics",e]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","topics",e],parseResponseAsJson:!1})}};var x=class{http;token;constructor(e){this.http=new V({retry:e.retry,baseUrl:e.baseUrl?e.baseUrl.replace(/\/$/,""):"https://qstash.upstash.io",authorization:`Bearer ${e.token}`}),this.token=e.token}get urlGroups(){return new te(this.http)}get topics(){return this.urlGroups}get dlq(){return new Q(this.http)}get messages(){return new X(this.http)}get schedules(){return new ee(this.http)}get workflow(){return new re(this.http)}queue(e){return new Z(this.http,e?.queueName)}chat(){return new Y(this.http,this.token)}async publish(e){let t=_(e);return await this.http.request({path:["v2","publish",F(e)],body:e.body,headers:t,method:"POST"})}async publishJSON(e){let t=v(new Headers(e.headers));return t.set("Content-Type","application/json"),A(e),W(e,t,this.http),await this.publish({...e,headers:t,body:JSON.stringify(e.body)})}async batch(e){let t=[];for(let o of e){let i=_(o),a=Object.fromEntries(i.entries());t.push({destination:F(o),headers:a,body:o.body,...o.queueName&&{queue:o.queueName}})}let s=await this.http.request({path:["v2","batch"],body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST"});return Array.isArray(s)?s:[s]}async batchJSON(e){for(let s of e)"body"in s&&(s.body=JSON.stringify(s.body)),s.headers=new Headers(s.headers),A(s),W(s,s.headers,this.http),s.headers.set("Content-Type","application/json");return await this.batch(e)}async events(e){let t={};e?.cursor&&e.cursor>0&&(t.cursor=e.cursor.toString());for(let[n,o]of Object.entries(e?.filter??{}))typeof o=="number"&&o<0||(n==="urlGroup"?t.topicName=o.toString():typeof o<"u"&&(t[n]=o.toString()));let s=await this.http.request({path:["v2","events"],method:"GET",query:t});return{cursor:s.cursor,events:s.events.map(n=>({...n,urlGroup:n.topicName}))}}};var Ze={withStackTrace:!1},Ue=(r,e,t=Ze)=>{let s=e.isOk()?{type:"Ok",value:e.value}:{type:"Err",value:e.error},n=t.withStackTrace?new Error().stack:void 0;return{data:s,message:r,stack:n}};function U(r,e,t,s){function n(o){return o instanceof t?o:new t(function(i){i(o)})}return new(t||(t=Promise))(function(o,i){function a(c){try{p(s.next(c))}catch(m){i(m)}}function l(c){try{p(s.throw(c))}catch(m){i(m)}}function p(c){c.done?o(c.value):n(c.value).then(a,l)}p((s=s.apply(r,[])).next())})}function xe(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],s=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&s>=r.length&&(r=void 0),{value:r&&r[s++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function E(r){return this instanceof E?(this.v=r,this):new E(r)}function et(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(r,e||[]),n,o=[];return n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n;function i(u){s[u]&&(n[u]=function(w){return new Promise(function(f,g){o.push([u,w,f,g])>1||a(u,w)})})}function a(u,w){try{l(s[u](w))}catch(f){m(o[0][3],f)}}function l(u){u.value instanceof E?Promise.resolve(u.value.v).then(p,c):m(o[0][2],u)}function p(u){a("next",u)}function c(u){a("throw",u)}function m(u,w){u(w),o.shift(),o.length&&a(o[0][0],o[0][1])}}function tt(r){var e,t;return e={},s("next"),s("throw",function(n){throw n}),s("return"),e[Symbol.iterator]=function(){return this},e;function s(n,o){e[n]=r[n]?function(i){return(t=!t)?{value:E(r[n](i)),done:n==="return"}:o?o(i):i}:o}}function rt(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof xe=="function"?xe(r):r[Symbol.iterator](),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(o){t[o]=r[o]&&function(i){return new Promise(function(a,l){i=r[o](i),n(a,l,i.done,i.value)})}}function n(o,i,a,l){Promise.resolve(l).then(function(p){o({value:p,done:a})},i)}}var k=class r{constructor(e){this._promise=e}static fromSafePromise(e){let t=e.then(s=>new T(s));return new r(t)}static fromPromise(e,t){let s=e.then(n=>new T(n)).catch(n=>new b(t(n)));return new r(s)}static fromThrowable(e,t){return(...s)=>new r(U(this,void 0,void 0,function*(){try{return new T(yield e(...s))}catch(n){return new b(t?t(n):n)}}))}static combine(e){return st(e)}static combineWithAllErrors(e){return nt(e)}map(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isErr()?new b(t.error):new T(yield e(t.value))})))}andThrough(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){if(t.isErr())return new b(t.error);let s=yield e(t.value);return s.isErr()?new b(s.error):new T(t.value)})))}andTee(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){if(t.isErr())return new b(t.error);try{yield e(t.value)}catch{}return new T(t.value)})))}mapErr(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isOk()?new T(t.value):new b(yield e(t.error))})))}andThen(e){return new r(this._promise.then(t=>{if(t.isErr())return new b(t.error);let s=e(t.value);return s instanceof r?s._promise:s}))}orElse(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isErr()?e(t.error):new T(t.value)})))}match(e,t){return this._promise.then(s=>s.match(e,t))}unwrapOr(e){return this._promise.then(t=>t.unwrapOr(e))}safeUnwrap(){return et(this,arguments,function*(){return yield E(yield E(yield*tt(rt(yield E(this._promise.then(t=>t.safeUnwrap()))))))})}then(e,t){return this._promise.then(e,t)}};var ge=r=>new k(Promise.resolve(new b(r))),Mt=k.fromPromise,Gt=k.fromSafePromise,$t=k.fromThrowable,Oe=r=>{let e=h([]);for(let t of r)if(t.isErr()){e=y(t.error);break}else e.map(s=>s.push(t.value));return e},st=r=>k.fromSafePromise(Promise.all(r)).andThen(Oe),Ne=r=>{let e=h([]);for(let t of r)t.isErr()&&e.isErr()?e.error.push(t.error):t.isErr()&&e.isOk()?e=y([t.error]):t.isOk()&&e.isOk()&&e.value.push(t.value);return e},nt=r=>k.fromSafePromise(Promise.all(r)).andThen(Ne),we;(function(r){function e(n,o){return(...i)=>{try{let a=n(...i);return h(a)}catch(a){return y(o?o(a):a)}}}r.fromThrowable=e;function t(n){return Oe(n)}r.combine=t;function s(n){return Ne(n)}r.combineWithAllErrors=s})(we||(we={}));var h=r=>new T(r);function y(r){return new b(r)}var T=class{constructor(e){this.value=e}isOk(){return!0}isErr(){return!this.isOk()}map(e){return h(e(this.value))}mapErr(e){return h(this.value)}andThen(e){return e(this.value)}andThrough(e){return e(this.value).map(t=>this.value)}andTee(e){try{e(this.value)}catch{}return h(this.value)}orElse(e){return h(this.value)}asyncAndThen(e){return e(this.value)}asyncAndThrough(e){return e(this.value).map(()=>this.value)}asyncMap(e){return k.fromSafePromise(e(this.value))}unwrapOr(e){return this.value}match(e,t){return e(this.value)}safeUnwrap(){let e=this.value;return function*(){return e}()}_unsafeUnwrap(e){return this.value}_unsafeUnwrapErr(e){throw Ue("Called `_unsafeUnwrapErr` on an Ok",this,e)}},b=class{constructor(e){this.error=e}isOk(){return!1}isErr(){return!this.isOk()}map(e){return y(this.error)}mapErr(e){return y(e(this.error))}andThrough(e){return y(this.error)}andTee(e){return y(this.error)}andThen(e){return y(this.error)}orElse(e){return e(this.error)}asyncAndThen(e){return ge(this.error)}asyncAndThrough(e){return ge(this.error)}asyncMap(e){return ge(this.error)}unwrapOr(e){return e}match(e,t){return t(this.error)}safeUnwrap(){let e=this.error;return function*(){throw yield y(e),new Error("Do not use this generator out of `safeTry`")}()}_unsafeUnwrap(e){throw Ue("Called `_unsafeUnwrap` on an Err",this,e)}_unsafeUnwrapErr(e){return this.error}},Jt=we.fromThrowable;var H="Upstash-Workflow-RunId",Le="Upstash-Workflow-Init",qe="Upstash-Workflow-Url",se="Upstash-Workflow-Is-Failure",B="1",ne="Upstash-Workflow-Sdk-Version",We="application/json";var Ae=["Initial","Run","SleepFor","SleepUntil","Call"];var _e=async(r,e)=>{let t=oe("true",r.workflowRunId,r.url,r.headers,void 0,r.failureUrl);await e?.log("SUBMIT","SUBMIT_FIRST_INVOCATION",{headers:t,requestPayload:r.requestPayload,url:r.url});try{return await r.qstashClient.publishJSON({headers:t,method:"POST",body:r.requestPayload,url:r.url}),h("success")}catch(s){return y(s)}},Fe=async({onCleanup:r,onStep:e})=>{try{return await e(),await r(),h("workflow-finished")}catch(t){let s=t;return s instanceof R?h("step-finished"):y(s)}},He=async(r,e,t=!1)=>{await e?.log("SUBMIT","SUBMIT_CLEANUP",{deletedWorkflowRunId:r.workflowRunId});let s=await r.qstashClient.http.request({path:["v2","workflows","runs",`${r.workflowRunId}?cancel=${t}`],method:"DELETE",parseResponseAsJson:!1});await e?.log("SUBMIT","SUBMIT_CLEANUP",s)},D=r=>{let e=new Headers,t=r.entries();for(let[s,n]of t){let o=s.toLowerCase();!o.startsWith("upstash-workflow-")&&!o.startsWith("x-vercel-")&&!o.startsWith("x-forwarded-")&&e.append(s,n)}return e},Be=async(r,e,t,s,n,o)=>{try{if(r.headers.get("Upstash-Workflow-Callback")){let i=JSON.parse(e);if(!(i.status>=200&&i.status<300))return await o?.log("WARN","SUBMIT_THIRD_PARTY_RESULT",i),h("call-will-retry");let a=r.headers.get(H),l=r.headers.get("Upstash-Workflow-StepId"),p=r.headers.get("Upstash-Workflow-StepName"),c=r.headers.get("Upstash-Workflow-StepType"),m=r.headers.get("Upstash-Workflow-Concurrent"),u=r.headers.get("Upstash-Workflow-ContentType");if(!(a&&l&&p&&Ae.includes(c)&&m&&u))throw new Error(`Missing info in callback message source header: ${JSON.stringify({workflowRunId:a,stepIdString:l,stepName:p,stepType:c,concurrentString:m,contentType:u})}`);let w=D(r.headers),f=oe("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:p,stepType:c,out:Buffer.from(i.body,"base64").toString(),concurrent:Number(m)};await o?.log("SUBMIT","SUBMIT_THIRD_PARTY_RESULT",{step:g,headers:f,url:s});let S=await t.publishJSON({headers:f,method:"POST",body:g,url:s});return await o?.log("SUBMIT","SUBMIT_THIRD_PARTY_RESULT",{messageId:S.messageId}),h("is-call-return")}else return h("continue-workflow")}catch(i){let a=r.headers.get("Upstash-Workflow-Callback");return y(new d(`Error when handling call return (isCallReturn=${a}): ${i}`))}},oe=(r,e,t,s,n,o)=>{let i={[Le]:r,[H]:e,[qe]:t,[`Upstash-Forward-${ne}`]:B,...o?{[`Upstash-Failure-Callback-Forward-${se}`]:"true","Upstash-Failure-Callback":o}:{}};if(s)for(let a of s.keys())n?.callHeaders?i[`Upstash-Callback-Forward-${a}`]=s.get(a):i[`Upstash-Forward-${a}`]=s.get(a);if(n?.callHeaders){let a=Object.fromEntries(Object.entries(n.callHeaders).map(([p,c])=>[`Upstash-Forward-${p}`,c])),l=n.callHeaders["Content-Type"];return{...i,...a,"Upstash-Callback":t,"Upstash-Callback-Workflow-RunId":e,"Upstash-Callback-Workflow-CallType":"fromCallback","Upstash-Callback-Workflow-Init":"false","Upstash-Callback-Workflow-Url":t,"Upstash-Callback-Forward-Upstash-Workflow-Callback":"true","Upstash-Callback-Forward-Upstash-Workflow-StepId":n.stepId.toString(),"Upstash-Callback-Forward-Upstash-Workflow-StepName":n.stepName,"Upstash-Callback-Forward-Upstash-Workflow-StepType":n.stepType,"Upstash-Callback-Forward-Upstash-Workflow-Concurrent":n.concurrent.toString(),"Upstash-Callback-Forward-Upstash-Workflow-ContentType":l??We,"Upstash-Workflow-CallType":"toCallback"}}return i},De=async(r,e,t)=>{if(t)try{if(!e)throw new Error("`Upstash-Signature` header is not passed.");if(!await t.verify({body:r,signature:e}))throw new Error("Signature in `Upstash-Signature` header is not valid")}catch(s){throw new d(`Failed to verify that the Workflow request comes from QStash: ${s}
3
3
 
4
4
  If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
5
5
 
package/package.json CHANGED
@@ -1 +1 @@
1
- { "version": "v2.7.1", "name": "@upstash/qstash", "description": "Official Typescript client for QStash", "author": "Andreas Thomas <dev@chronark.com>", "license": "MIT", "homepage": "https://github.com/upstash/sdk-qstash-ts#readme", "repository": { "type": "git", "url": "git+https://github.com/upstash/sdk-qstash-ts.git" }, "bugs": { "url": "https://github.com/upstash/sdk-qstash-ts/issues" }, "files": [ "dist" ], "main": "./dist/base/index.mjs", "module": "./dist/base/index.mjs", "types": "./dist/base/index.d.mts", "exports": { ".": { "types": "./dist/base/index.d.mts", "import": "./dist/base/index.mjs", "require": "./dist/base/index.js" }, "./nextjs": { "import": "./dist/nextjs/index.mjs" }, "./dist/nextjs": { "import": "./dist/nextjs/index.mjs" }, "./h3": { "types": "./dist/h3/index.d.mts", "import": "./dist/h3/index.mjs" }, "./nuxt": { "types": "./dist/h3/index.d.mts", "import": "./dist/h3/index.mjs" }, "./svelte": { "types": "./dist/svelte/index.d.mts", "import": "./dist/svelte/index.mjs" }, "./solidjs": { "types": "./dist/solidjs/index.d.mts", "import": "./dist/solidjs/index.mjs" }, "./workflow": { "types": "./dist/workflow/index.d.mts", "import": "./dist/workflow/index.mjs" }, "./hono": { "types": "./dist/hono/index.d.mts", "import": "./dist/hono/index.mjs" }, "./cloudflare": { "types": "./dist/cloudflare/index.d.mts", "import": "./dist/cloudflare/index.mjs" } }, "keywords": [ "qstash", "queue", "events", "serverless", "upstash" ], "scripts": { "build": "tsup", "test": "bun test src", "fmt": "prettier --write .", "lint": "tsc && eslint \"src/**/*.{js,ts,tsx}\" --quiet --fix", "prepare": "husky" }, "devDependencies": { "@commitlint/cli": "^19.2.2", "@commitlint/config-conventional": "^19.2.2", "@types/bun": "^1.1.1", "@types/crypto-js": "^4.2.0", "@typescript-eslint/eslint-plugin": "^7.0.1", "@typescript-eslint/parser": "^7.0.1", "ai": "^3.1.28", "bun-types": "^1.1.7", "eslint": "^8", "eslint-plugin-unicorn": "^51.0.1", "husky": "^9.0.10", "neverthrow": "^7.0.1", "next": "^14.0.2", "prettier": "^3.2.5", "tsup": "latest", "typescript": "^5.4.5", "undici-types": "^6.16.0", "@solidjs/start": "^1.0.6", "@sveltejs/kit": "^2.5.18", "hono": "^4.5.8", "h3": "^1.12.0", "vitest": "latest" }, "dependencies": { "crypto-js": ">=4.2.0", "jose": "^ 5.2.3" } }
1
+ { "version": "v2.7.2", "name": "@upstash/qstash", "description": "Official Typescript client for QStash", "author": "Andreas Thomas <dev@chronark.com>", "license": "MIT", "homepage": "https://github.com/upstash/sdk-qstash-ts#readme", "repository": { "type": "git", "url": "git+https://github.com/upstash/sdk-qstash-ts.git" }, "bugs": { "url": "https://github.com/upstash/sdk-qstash-ts/issues" }, "files": [ "dist" ], "main": "./dist/base/index.mjs", "module": "./dist/base/index.mjs", "types": "./dist/base/index.d.mts", "exports": { ".": { "types": "./dist/base/index.d.mts", "import": "./dist/base/index.mjs", "require": "./dist/base/index.js" }, "./nextjs": { "import": "./dist/nextjs/index.mjs" }, "./dist/nextjs": { "import": "./dist/nextjs/index.mjs" }, "./h3": { "types": "./dist/h3/index.d.mts", "import": "./dist/h3/index.mjs" }, "./nuxt": { "types": "./dist/h3/index.d.mts", "import": "./dist/h3/index.mjs" }, "./svelte": { "types": "./dist/svelte/index.d.mts", "import": "./dist/svelte/index.mjs" }, "./solidjs": { "types": "./dist/solidjs/index.d.mts", "import": "./dist/solidjs/index.mjs" }, "./workflow": { "types": "./dist/workflow/index.d.mts", "import": "./dist/workflow/index.mjs" }, "./hono": { "types": "./dist/hono/index.d.mts", "import": "./dist/hono/index.mjs" }, "./cloudflare": { "types": "./dist/cloudflare/index.d.mts", "import": "./dist/cloudflare/index.mjs" } }, "keywords": [ "qstash", "queue", "events", "serverless", "upstash" ], "scripts": { "build": "tsup", "test": "bun test src", "fmt": "prettier --write .", "lint": "tsc && eslint \"src/**/*.{js,ts,tsx}\" --quiet --fix", "prepare": "husky" }, "devDependencies": { "@commitlint/cli": "^19.2.2", "@commitlint/config-conventional": "^19.2.2", "@types/bun": "^1.1.1", "@types/crypto-js": "^4.2.0", "@typescript-eslint/eslint-plugin": "^7.0.1", "@typescript-eslint/parser": "^7.0.1", "ai": "^3.1.28", "bun-types": "^1.1.7", "eslint": "^8", "eslint-plugin-unicorn": "^51.0.1", "husky": "^9.0.10", "neverthrow": "^7.0.1", "next": "^14.0.2", "prettier": "^3.2.5", "tsup": "latest", "typescript": "^5.4.5", "undici-types": "^6.16.0", "@solidjs/start": "^1.0.6", "@sveltejs/kit": "^2.5.18", "hono": "^4.5.8", "h3": "^1.12.0", "vitest": "latest" }, "dependencies": { "crypto-js": ">=4.2.0", "jose": "^ 5.2.3" } }