@novu/framework 2.14.0-rc.5ea799b171 → 2.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -153,13 +153,13 @@ $$`:`${e}$$`},$T=e=>FT(e)%2===0?e:HT(e),qT=e=>UT(e)%2===1?`${e}$`:e,jT=(e,t,n)=>
153
153
  `);n&&r.length>0&&r.at(-1)===""&&r.pop();let i=[],a=!1,o=!1;for(let l=0;l<r.length;l++){let p=r[l].trim();if(!a&&(p.startsWith("```")||p.startsWith("~~~"))){o=!o,i.push(r[l]);continue}if(o){i.push(r[l]);continue}let d=p!==""&&(ac.test(p)||oc.test(p));if(d&&!a){let h=!1;for(let y=l;y<r.length;y++){let g=r[y].trim();if(oc.test(g)){h=!0;break}if(g===""||!ac.test(g))break}h&&(i.push("```"),a=!0)}else!d&&a&&(i.push("```"),a=!1);i.push(r[l])}a&&t&&i.push("```");let s=i.join(`
154
154
  `);return n&&(s+=`
155
155
  `),s}function gx(e){return"adapterName"in e&&!("adapter"in e)}var Kf="thread-state:";function Xf(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}var yx=new AbortController().signal;async function*bx(e,t){let n=e[Symbol.asyncIterator](),r;try{for(;!t.aborted;){let i=new Promise(s=>{r=()=>s({done:!0,value:void 0}),t.addEventListener("abort",r,{once:!0})}),a=n.next(),o=await Promise.race([a,i]);if(r&&t.removeEventListener("abort",r),o.done||t.aborted)return;yield o.value}}finally{r&&t.removeEventListener("abort",r),n.return&&n.return().catch(()=>{})}}var wx=class sc{constructor(t){Se(this,"id");Se(this,"channelId");Se(this,"isDM");Se(this,"channelVisibility");Se(this,"signal");Se(this,"_adapter");Se(this,"_adapterName");Se(this,"_stateAdapterInstance");Se(this,"_recentMessages",[]);Se(this,"_isSubscribedContext");Se(this,"_currentMessage");Se(this,"_streamingUpdateIntervalMs");Se(this,"_fallbackStreamingPlaceholderText");Se(this,"_channel");Se(this,"_threadHistory");Se(this,"_logger");Se(this,"_typingStarted",!1);var n,r,i,a,o;this.id=t.id,this.channelId=t.channelId,this.isDM=(n=t.isDM)!=null?n:!1,this.channelVisibility=(r=t.channelVisibility)!=null?r:"unknown",this.signal=(i=t.signal)!=null?i:yx,this._isSubscribedContext=(a=t.isSubscribedContext)!=null?a:!1,this._currentMessage=t.currentMessage,this._logger=t.logger,this._streamingUpdateIntervalMs=(o=t.streamingUpdateIntervalMs)!=null?o:500,this._fallbackStreamingPlaceholderText=t.fallbackStreamingPlaceholderText,gx(t)?this._adapterName=t.adapterName:(this._adapter=t.adapter,this._stateAdapterInstance=t.stateAdapter,this._threadHistory=t.threadHistory),t.initialMessage&&(this._recentMessages=[t.initialMessage])}get adapter(){if(this._adapter)return this._adapter;if(!this._adapterName)throw new Error("Thread has no adapter configured");let n=li().getAdapter(this._adapterName);if(!n)throw new Error(`Adapter "${this._adapterName}" not found in Chat singleton`);return this._adapter=n,n}get _stateAdapter(){if(this._stateAdapterInstance)return this._stateAdapterInstance;let t=li();return this._stateAdapterInstance=t.getState(),this._stateAdapterInstance}get recentMessages(){return this._recentMessages}set recentMessages(t){this._recentMessages=t}get state(){return this._stateAdapter.get(`${Kf}${this.id}`)}async setState(t,n){let r=`${Kf}${this.id}`;if(n!=null&&n.replace)await this._stateAdapter.set(r,t,si);else{let a={...await this._stateAdapter.get(r),...t};await this._stateAdapter.set(r,a,si)}}get channel(){if(!this._channel){let t=rm(this.adapter,this.id);this._channel=new nm({id:t,adapter:this.adapter,stateAdapter:this._stateAdapter,isDM:this.isDM,channelVisibility:this.channelVisibility,threadHistory:this._threadHistory})}return this._channel}get messages(){let t=this.adapter,n=this.id,r=this._threadHistory;return{async*[Symbol.asyncIterator](){let i,a=!1;for(;;){let o=await t.fetchMessages(n,{cursor:i,direction:"backward"}),s=[...o.messages].reverse();for(let l of s)a=!0,yield l;if(!o.nextCursor||o.messages.length===0)break;i=o.nextCursor}if(!a&&r){let o=await r.getMessages(n);for(let s=o.length-1;s>=0;s--)yield o[s]}}}}get allMessages(){let t=this.adapter,n=this.id,r=this._threadHistory;return{async*[Symbol.asyncIterator](){let i,a=!1;for(;;){let o=await t.fetchMessages(n,{limit:100,cursor:i,direction:"forward"});for(let s of o.messages)a=!0,yield s;if(!o.nextCursor||o.messages.length===0)break;i=o.nextCursor}if(!a&&r){let o=await r.getMessages(n);for(let s of o)yield s}}}}async getParticipants(){let t=new Map;this._currentMessage&&!this._currentMessage.author.isMe&&!this._currentMessage.author.isBot&&t.set(this._currentMessage.author.userId,this._currentMessage.author);for await(let n of this.allMessages)n.author.isMe||n.author.isBot||t.has(n.author.userId)||t.set(n.author.userId,n.author);return[...t.values()]}async isSubscribed(){return this._isSubscribedContext?!0:this._stateAdapter.isSubscribed(this.id)}async subscribe(){await this._stateAdapter.subscribe(this.id),this.adapter.onThreadSubscribe&&await this.adapter.onThreadSubscribe(this.id)}async unsubscribe(){await this._stateAdapter.unsubscribe(this.id)}async post(t){if(lc(t)){if(t.kind==="stream"){let a=t.getPostData(),o={...a.options.updateIntervalMs?{updateIntervalMs:a.options.updateIntervalMs}:{},...a.options.groupTasks?{taskDisplayMode:a.options.groupTasks}:{},...a.options.endWith?{stopBlocks:a.options.endWith}:{},...a.options.sessionStatus?{sessionStatus:a.options.sessionStatus}:{}};return await this.handleStream(a.stream,o),t}return await this.handlePostableObject(t),t}if(Xf(t))return this.handleStream(t);let n=t;if(Pt(t)){let a=It(t);if(!a)throw new Error("Invalid JSX element: must be a Card element");n=a}n=await this.processCallbackUrls(n);let r;try{r=await this.adapter.postMessage(this.id,n)}finally{await this.finishTyping()}let i=this.createSentMessage(r.id,n,r.threadId);return this._threadHistory&&await this._threadHistory.append(this.id,new rn(i)),i}async handlePostableObject(t){try{await Zf(t,this.adapter,this.id,(n,r)=>this.adapter.postMessage(n,r),this._logger)}finally{await this.finishTyping()}}async postEphemeral(t,n,r){let{fallbackToDM:i}=r,a=typeof t=="string"?t:t.userId,o;if(Pt(n)){let s=It(n);if(!s)throw new Error("Invalid JSX element: must be a Card element");o=s}else o=n;if(this.adapter.postEphemeral)return o=await this.processCallbackUrls(o),this.adapter.postEphemeral(this.id,a,o);if(!i)return null;if(this.adapter.openDM){let s=await this.adapter.openDM(a);o=await this.processCallbackUrls(o,{id:this.adapter.channelIdFromThreadId(s),type:"channel"});let l=await this.adapter.postMessage(s,o);return{id:l.id,threadId:s,usedFallback:!0,raw:l.raw}}return null}async reply(t,n){if(!this.adapter.reply)throw new oi("Message replies are not supported by this adapter","replies");let r=t instanceof rn?t:this.findKnownMessage(t);if(r&&r.threadId!==this.id)throw new Error("Cannot reply to a message from another thread");let i;if(Xf(n)){let l="";for await(let p of ao(n))typeof p=="string"?l+=p:p.type==="markdown_text"&&(l+=p.text);i={markdown:l.trim()?l:" "}}else if(Pt(n)){let l=It(n);if(!l)throw new Error("Invalid JSX element: must be a Card element");i=l}else i=n;i=await this.processCallbackUrls(i);let a=typeof t=="string"?t:t.id,o=await this.adapter.reply(this.id,a,i),s=this.createSentMessage(o.id,i,o.threadId,r);return this._threadHistory&&await this._threadHistory.append(this.id,new rn(s)),s}findKnownMessage(t){var n;return((n=this._currentMessage)==null?void 0:n.id)===t?this._currentMessage:this._recentMessages.find(r=>r.id===t)}async processCallbackUrls(t,n={id:this.id,type:"thread"}){var r;if(typeof t=="string")return t;if("type"in t&&t.type==="card")return so(t,this._stateAdapter,n);if("card"in t&&((r=t.card)==null?void 0:r.type)==="card"){let i=await so(t.card,this._stateAdapter,n);if(i!==t.card)return{...t,card:i}}return t}async schedule(t,n){let r;if(Pt(t)){let i=It(t);if(!i)throw new Error("Invalid JSX element: must be a Card element");r=i}else r=t;if(r=await this.processCallbackUrls(r),!this.adapter.scheduleMessage)throw new oi("Scheduled messages are not supported by this adapter","scheduling");return this.adapter.scheduleMessage(this.id,r,n)}async handleStream(t,n){let r=bx(ao(t),this.signal),i={signal:this.signal,updateIntervalMs:this._streamingUpdateIntervalMs,...n,...this._fallbackStreamingPlaceholderText!==void 0?{fallbackStreamingPlaceholderText:this._fallbackStreamingPlaceholderText}:{}};if(this._currentMessage&&(i.recipientUserId=this._currentMessage.author.userId,i.recipientTeamId=this.extractSlackRecipientTeamId(this._currentMessage.raw)),this.adapter.stream){let o="",s={[Symbol.asyncIterator]:()=>{let p=r[Symbol.asyncIterator]();return{async next(){let d=await p.next();if(!d.done){let h=d.value;typeof h=="string"?o+=h:h.type==="markdown_text"&&(o+=h.text)}return d}}}},l;try{l=await this.adapter.stream(this.id,s,i)}catch(p){throw await this.finishTyping(),p}if(l){this._typingStarted=!1;let p=this.createSentMessage(l.id,{markdown:o},l.threadId);return this._threadHistory&&await this._threadHistory.append(this.id,new rn(p)),p}}let a={[Symbol.asyncIterator]:()=>{let o=r[Symbol.asyncIterator]();return{async next(){for(;;){let s=await o.next();if(s.done)return{value:void 0,done:!0};let l=s.value;if(typeof l=="string")return{value:l,done:!1};if(l.type==="markdown_text")return{value:l.text,done:!1}}}}}};return this.fallbackStream(a,i)}extractSlackRecipientTeamId(t){var r;if(!t||typeof t!="object")return;let n=t;if(typeof n.team_id=="string"&&n.team_id)return n.team_id;if(typeof n.team=="string"&&n.team)return n.team;if(n.team&&typeof n.team=="object"&&typeof n.team.id=="string"&&n.team.id)return n.team.id;if(typeof((r=n.user)==null?void 0:r.team_id)=="string"&&n.user.team_id)return n.user.team_id}async startTyping(t){var r;let n=(r=this._currentMessage)==null?void 0:r.author.userId;if(n){await this.adapter.startTyping(this.id,t,{initiatorUserId:n}),this._typingStarted=!0;return}await this.adapter.startTyping(this.id,t),this._typingStarted=!0}async finishTyping(t="active"){var n,r;this._typingStarted&&(this._typingStarted=!1,await((r=(n=this.adapter).endTyping)==null?void 0:r.call(n,this.id,t)))}async markAsRead(t){if(!this.adapter.markAsRead)throw new oi("Read receipts are not supported by this adapter","read-receipts");let n=t!=null?t:this._currentMessage;if(!n)throw new oo("A message is required outside a message handler","MESSAGE_REQUIRED");if(typeof n!="string"&&n.threadId!==this.id)throw new oo("Cannot mark a message from another thread as read","THREAD_MISMATCH");await this.adapter.markAsRead(this.id,typeof n=="string"?n:n.id,typeof n=="string"?void 0:n)}async fallbackStream(t,n){try{return await this.runFallbackStream(t,n)}finally{await this.finishTyping(n==null?void 0:n.sessionStatus)}}async runFallbackStream(t,n){var H;let r=(H=n==null?void 0:n.updateIntervalMs)!=null?H:this._streamingUpdateIntervalMs,i=this._fallbackStreamingPlaceholderText===void 0?"...":this._fallbackStreamingPlaceholderText,a=i===null?null:await this.adapter.postMessage(this.id,i),o=this.id,s=new im,l="",p=!1,d=null,h=null;a&&(o=a.threadId||this.id,l=i!=null?i:"");let y=()=>{h=setTimeout(()=>{d=g()},r)},g=async()=>{var ne;if(p||!a)return;let ue=s.render();if(ue.trim()&&ue!==l)try{await this.adapter.editMessage(o,a.id,{markdown:ue}),l=ue}catch(ve){(ne=this._logger)==null||ne.warn("fallbackStream edit failed",ve)}p||y()};a&&y();try{for await(let ue of t)if(s.push(ue),!a){let ne=s.render();ne.trim()&&(a=await this.adapter.postMessage(this.id,{markdown:ne}),o=a.threadId||this.id,l=ne,y())}}finally{p=!0,h&&(clearTimeout(h),h=null)}d&&await d;let I=s.getText(),K=s.finish();a||(a=await this.adapter.postMessage(this.id,{markdown:I.trim()?I:" "}),o=a.threadId||this.id,l=I),K.trim()&&K!==l&&await this.adapter.editMessage(o,a.id,{markdown:I});let Z=this.createSentMessage(a.id,{markdown:I},o);return this._threadHistory&&await this._threadHistory.append(this.id,new rn(Z)),Z}async refresh(){let t=await this.adapter.fetchMessages(this.id,{limit:50});t.messages.length>0?this._recentMessages=t.messages:this._threadHistory?this._recentMessages=await this._threadHistory.getMessages(this.id,50):this._recentMessages=[]}mentionUser(t){return`<@${t}>`}toJSON(){var t,n;return{_type:"chat:Thread",id:this.id,channelId:this.channelId,channelVisibility:this.channelVisibility,currentMessage:(t=this._currentMessage)==null?void 0:t.toJSON(),isDM:this.isDM,adapterName:(n=this._adapterName)!=null?n:this.adapter.name}}static fromJSON(t,n){let r=new sc({id:t.id,adapterName:t.adapterName,channelId:t.channelId,channelVisibility:t.channelVisibility,currentMessage:t.currentMessage?rn.fromJSON(t.currentMessage):void 0,isDM:t.isDM});return n&&(r._adapter=n),r}static[lr](t){return t.toJSON()}static[cr](t){return sc.fromJSON(t)}createSentMessage(t,n,r,i){let a=this.adapter,o=r||this.id,s=this,{plainText:l,formatted:p,attachments:d}=Sx(n);return{id:t,threadId:o,text:l,formatted:p,raw:null,links:[],author:{userId:"self",userName:a.userName,fullName:a.userName,isBot:!0,isMe:!0},metadata:{dateSent:new Date,edited:!1},attachments:d,replyTo:i,toJSON(){return new rn(this).toJSON()},async edit(y){let g=y;if(Pt(y)){let I=It(y);if(!I)throw new Error("Invalid JSX element: must be a Card element");g=I}return g=await s.processCallbackUrls(g),await a.editMessage(o,t,g),s.createSentMessage(t,g,o,i)},async delete(){await a.deleteMessage(o,t)},async addReaction(y){await a.addReaction(o,t,y)},async removeReaction(y){await a.removeReaction(o,t,y)}}}createSentMessageFromMessage(t){let n=this.adapter,r=this.id,i=t.id,a=this;return{id:t.id,threadId:t.threadId,text:t.text,formatted:t.formatted,raw:t.raw,author:t.author,metadata:t.metadata,attachments:t.attachments,replyTo:t.replyTo,links:t.links,isMention:t.isMention,toJSON(){return t.toJSON()},async edit(o){let s=o;if(Pt(o)){let l=It(o);if(!l)throw new Error("Invalid JSX element: must be a Card element");s=l}return s=await a.processCallbackUrls(s),await n.editMessage(r,i,s),a.createSentMessage(i,s,r,t.replyTo)},async delete(){await n.deleteMessage(r,i)},async addReaction(o){await n.addReaction(r,i,o)},async removeReaction(o){await n.removeReaction(r,i,o)}}}};function Sx(e){if(typeof e=="string")return{plainText:e,formatted:nn([tn([en(e)])]),attachments:[]};if("raw"in e)return{plainText:e.raw,formatted:nn([tn([en(e.raw)])]),attachments:e.attachments||[]};if("markdown"in e){let t=Wa(e.markdown);return{plainText:sr(t),formatted:t,attachments:e.attachments||[]}}if("ast"in e)return{plainText:sr(e.ast),formatted:e.ast,attachments:e.attachments||[]};if("card"in e){let t=e.fallbackText||ri(e.card);return{plainText:t,formatted:nn([tn([en(t)])]),attachments:[]}}if("type"in e&&e.type==="card"){let t=ri(e);return{plainText:t,formatted:nn([tn([en(t)])]),attachments:[]}}throw new Error("Invalid PostableMessage format")}no();var am=require("async_hooks");var f1=new am.AsyncLocalStorage;ii();cc();var pM=10080*60*1e3;var dM=3600*1e3;var hM=600*1e3,fM=1440*60*1e3;var om=new Map;function ur(e){let t=om.get(e);return t||(t=Object.freeze({name:e,toString:()=>`{{emoji:${e}}}`,toJSON:()=>`{{emoji:${e}}}`}),om.set(e,t)),t}var Tx={thumbs_up:{slack:["+1","thumbsup"],gchat:"\u{1F44D}"},thumbs_down:{slack:["-1","thumbsdown"],gchat:"\u{1F44E}"},clap:{slack:"clap",gchat:"\u{1F44F}"},wave:{slack:"wave",gchat:"\u{1F44B}"},pray:{slack:"pray",gchat:"\u{1F64F}"},muscle:{slack:"muscle",gchat:"\u{1F4AA}"},ok_hand:{slack:"ok_hand",gchat:"\u{1F44C}"},point_up:{slack:"point_up",gchat:"\u{1F446}"},point_down:{slack:"point_down",gchat:"\u{1F447}"},point_left:{slack:"point_left",gchat:"\u{1F448}"},point_right:{slack:"point_right",gchat:"\u{1F449}"},raised_hands:{slack:"raised_hands",gchat:"\u{1F64C}"},shrug:{slack:"shrug",gchat:"\u{1F937}"},facepalm:{slack:"facepalm",gchat:"\u{1F926}"},heart:{slack:"heart",gchat:["\u2764\uFE0F","\u2764"]},smile:{slack:["smile","slightly_smiling_face"],gchat:"\u{1F60A}"},laugh:{slack:["laughing","satisfied","joy"],gchat:["\u{1F602}","\u{1F606}"]},thinking:{slack:"thinking_face",gchat:"\u{1F914}"},sad:{slack:["cry","sad","white_frowning_face"],gchat:"\u{1F622}"},cry:{slack:"sob",gchat:"\u{1F62D}"},angry:{slack:"angry",gchat:"\u{1F620}"},love_eyes:{slack:"heart_eyes",gchat:"\u{1F60D}"},cool:{slack:"sunglasses",gchat:"\u{1F60E}"},wink:{slack:"wink",gchat:"\u{1F609}"},surprised:{slack:"open_mouth",gchat:"\u{1F62E}"},worried:{slack:"worried",gchat:"\u{1F61F}"},confused:{slack:"confused",gchat:"\u{1F615}"},neutral:{slack:"neutral_face",gchat:"\u{1F610}"},sleeping:{slack:"sleeping",gchat:"\u{1F634}"},sick:{slack:"nauseated_face",gchat:"\u{1F922}"},mind_blown:{slack:"exploding_head",gchat:"\u{1F92F}"},relieved:{slack:"relieved",gchat:"\u{1F60C}"},grimace:{slack:"grimacing",gchat:"\u{1F62C}"},rolling_eyes:{slack:"rolling_eyes",gchat:"\u{1F644}"},hug:{slack:"hugging_face",gchat:"\u{1F917}"},zany:{slack:"zany_face",gchat:"\u{1F92A}"},check:{slack:["white_check_mark","heavy_check_mark"],gchat:["\u2705","\u2714\uFE0F"]},x:{slack:["x","heavy_multiplication_x"],gchat:["\u274C","\u2716\uFE0F"]},question:{slack:"question",gchat:["\u2753","?"]},exclamation:{slack:"exclamation",gchat:"\u2757"},warning:{slack:"warning",gchat:"\u26A0\uFE0F"},stop:{slack:"octagonal_sign",gchat:"\u{1F6D1}"},info:{slack:"information_source",gchat:"\u2139\uFE0F"},100:{slack:"100",gchat:"\u{1F4AF}"},fire:{slack:"fire",gchat:"\u{1F525}"},star:{slack:"star",gchat:"\u2B50"},sparkles:{slack:"sparkles",gchat:"\u2728"},lightning:{slack:"zap",gchat:"\u26A1"},boom:{slack:"boom",gchat:"\u{1F4A5}"},eyes:{slack:"eyes",gchat:"\u{1F440}"},green_circle:{slack:"large_green_circle",gchat:"\u{1F7E2}"},yellow_circle:{slack:"large_yellow_circle",gchat:"\u{1F7E1}"},red_circle:{slack:"red_circle",gchat:"\u{1F534}"},blue_circle:{slack:"large_blue_circle",gchat:"\u{1F535}"},white_circle:{slack:"white_circle",gchat:"\u26AA"},black_circle:{slack:"black_circle",gchat:"\u26AB"},rocket:{slack:"rocket",gchat:"\u{1F680}"},party:{slack:["tada","partying_face"],gchat:["\u{1F389}","\u{1F973}"]},confetti:{slack:"confetti_ball",gchat:"\u{1F38A}"},balloon:{slack:"balloon",gchat:"\u{1F388}"},gift:{slack:"gift",gchat:"\u{1F381}"},trophy:{slack:"trophy",gchat:"\u{1F3C6}"},medal:{slack:"first_place_medal",gchat:"\u{1F947}"},lightbulb:{slack:"bulb",gchat:"\u{1F4A1}"},gear:{slack:"gear",gchat:"\u2699\uFE0F"},wrench:{slack:"wrench",gchat:"\u{1F527}"},hammer:{slack:"hammer",gchat:"\u{1F528}"},bug:{slack:"bug",gchat:"\u{1F41B}"},link:{slack:"link",gchat:"\u{1F517}"},lock:{slack:"lock",gchat:"\u{1F512}"},unlock:{slack:"unlock",gchat:"\u{1F513}"},key:{slack:"key",gchat:"\u{1F511}"},pin:{slack:"pushpin",gchat:"\u{1F4CC}"},memo:{slack:"memo",gchat:"\u{1F4DD}"},clipboard:{slack:"clipboard",gchat:"\u{1F4CB}"},calendar:{slack:"calendar",gchat:"\u{1F4C5}"},clock:{slack:"clock1",gchat:"\u{1F550}"},hourglass:{slack:"hourglass",gchat:"\u23F3"},bell:{slack:"bell",gchat:"\u{1F514}"},megaphone:{slack:"mega",gchat:"\u{1F4E2}"},speech_bubble:{slack:"speech_balloon",gchat:"\u{1F4AC}"},email:{slack:"email",gchat:"\u{1F4E7}"},inbox:{slack:"inbox_tray",gchat:"\u{1F4E5}"},outbox:{slack:"outbox_tray",gchat:"\u{1F4E4}"},package:{slack:"package",gchat:"\u{1F4E6}"},folder:{slack:"file_folder",gchat:"\u{1F4C1}"},file:{slack:"page_facing_up",gchat:"\u{1F4C4}"},chart_up:{slack:"chart_with_upwards_trend",gchat:"\u{1F4C8}"},chart_down:{slack:"chart_with_downwards_trend",gchat:"\u{1F4C9}"},coffee:{slack:"coffee",gchat:"\u2615"},pizza:{slack:"pizza",gchat:"\u{1F355}"},beer:{slack:"beer",gchat:"\u{1F37A}"},arrow_up:{slack:"arrow_up",gchat:"\u2B06\uFE0F"},arrow_down:{slack:"arrow_down",gchat:"\u2B07\uFE0F"},arrow_left:{slack:"arrow_left",gchat:"\u2B05\uFE0F"},arrow_right:{slack:"arrow_right",gchat:"\u27A1\uFE0F"},refresh:{slack:"arrows_counterclockwise",gchat:"\u{1F504}"},sun:{slack:"sunny",gchat:"\u2600\uFE0F"},cloud:{slack:"cloud",gchat:"\u2601\uFE0F"},rain:{slack:"rain_cloud",gchat:"\u{1F327}\uFE0F"},snow:{slack:"snowflake",gchat:"\u2744\uFE0F"},rainbow:{slack:"rainbow",gchat:"\u{1F308}"}},xx=class{constructor(e){Se(this,"emojiMap");Se(this,"slackToNormalized");Se(this,"gchatToNormalized");this.emojiMap={...Tx,...e},this.slackToNormalized=new Map,this.gchatToNormalized=new Map,this.buildReverseMaps()}buildReverseMaps(){for(let[e,t]of Object.entries(this.emojiMap)){let n=Array.isArray(t.slack)?t.slack:[t.slack];for(let i of n)this.slackToNormalized.set(i.toLowerCase(),e);let r=Array.isArray(t.gchat)?t.gchat:[t.gchat];for(let i of r)this.gchatToNormalized.set(i,e)}}fromSlack(e){var r;let t=e.replace(/^:|:$/g,"").toLowerCase(),n=(r=this.slackToNormalized.get(t))!=null?r:e;return ur(n)}fromGChat(e){var n;let t=(n=this.gchatToNormalized.get(e))!=null?n:e;return ur(t)}fromTeams(e){var r;let n=(r={like:"thumbs_up",heart:"heart",laugh:"laugh",surprised:"surprised",sad:"sad",angry:"angry"}[e])!=null?r:e;return ur(n)}toSlack(e){let t=typeof e=="string"?e:e.name,n=this.emojiMap[t];return n?Array.isArray(n.slack)?n.slack[0]:n.slack:t}toGChat(e){let t=typeof e=="string"?e:e.name,n=this.emojiMap[t];return n?Array.isArray(n.gchat)?n.gchat[0]:n.gchat:t}toDiscord(e){return this.toGChat(e)}matches(e,t){let n=typeof t=="string"?t:t.name,r=this.emojiMap[n];if(!r)return e===n;let i=Array.isArray(r.slack)?r.slack:[r.slack],a=Array.isArray(r.gchat)?r.gchat:[r.gchat],o=e.replace(/^:|:$/g,"").toLowerCase();return i.some(s=>s.toLowerCase()===o)||a.includes(e)}extend(e){Object.assign(this.emojiMap,e),this.buildReverseMaps()}},Ax=new xx;function vx(e){let t=["thumbs_up","thumbs_down","clap","wave","pray","muscle","ok_hand","point_up","point_down","point_left","point_right","raised_hands","shrug","facepalm","heart","smile","laugh","thinking","sad","cry","angry","love_eyes","cool","wink","surprised","worried","confused","neutral","sleeping","sick","mind_blown","relieved","grimace","rolling_eyes","hug","zany","check","x","question","exclamation","warning","stop","info","100","fire","star","sparkles","lightning","boom","eyes","green_circle","yellow_circle","red_circle","blue_circle","white_circle","black_circle","rocket","party","confetti","balloon","gift","trophy","medal","lightbulb","gear","wrench","hammer","bug","link","lock","unlock","key","pin","memo","clipboard","calendar","clock","hourglass","bell","megaphone","speech_bubble","email","inbox","outbox","package","folder","file","chart_up","chart_down","coffee","pizza","beer","arrow_up","arrow_down","arrow_left","arrow_right","refresh","sun","cloud","rain","snow","rainbow"],n={custom:r=>ur(r)};for(let r of t)n[r]=ur(r);if(e){for(let r of Object.keys(e))n[r]=ur(r);Ax.extend(e)}return n}var mM=vx(),ci=Gr,ui=Kr,pi=Ya;var di=ni,hi=kf,fi=ti,mi=Yr,sm=Qr,lm=Zr;var gi=Wr;var yi=Xr,cm=Jr,bi=ei;var um=Qa,pm=Ga;var dm=eo,wi=Xa,Si=Za,Ti=Ka;function pr(e){return"type"in e&&e.type==="card"}function hm(e){return typeof e=="object"&&e!==null&&e.type==="tool-approval-card"}function fm(e){if(typeof e!="object"||e===null)return!1;let t=e.type;return t==="human-ask-card"||t==="human-approve-card"||t==="human-choose-card"||t==="human-tell-card"}function uc(e,t){return(e==null?void 0:e.workflowId)===t.id}var kx=Symbol.for("chat.jsx.element"),Ex=new Set([ci,ui,pi,di,hi,fi,mi,um,sm,lm,gi,yi,pm,dm,cm,wi,Si,bi,Ti]);function Rx(e){return typeof e=="object"&&e!==null&&"type"in e}function Cx(e){return typeof e=="object"&&e!==null&&e.$$typeof===kx}async function co(e){let t=lo(e);if(t&&typeof t=="object"&&pr(t))return t;let{isJSX:n,toCardElement:r}=await Promise.resolve().then(()=>(gm(),mm));return n(t)?r(t):null}function lo(e){var t;if(Array.isArray(e))return e.map(n=>lo(n));if(!Cx(e))return Ox(e);if(typeof e.type=="function"&&!Ex.has(e.type)){let n={...(t=e.props)!=null?t:{}};return e.children!==void 0&&(n.children=e.children),lo(e.type(n))}return{...e,children:lo(e.children)}}function Ox(e){return typeof e=="string"||typeof e=="number"||Rx(e)?e:null}var ym=async(e,t)=>{let n=new TextEncoder,r=n.encode(e),i=n.encode(t),a=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("HMAC",a,i);return Array.from(new Uint8Array(o)).map(s=>s.toString(16).padStart(2,"0")).join("")},bm=(e,t)=>{if(typeof e!="string"||typeof t!="string"||e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0};var wm=require("cross-fetch"),Sm=()=>typeof Response!="undefined"?Response:wm.Response,Tm=async()=>{if(process.env.NOVU_BRIDGE_ORIGIN)return`${process.env.NOVU_BRIDGE_ORIGIN}/api/novu`;if(process.env.NEXT_PUBLIC_VERCEL_ENV==="preview"&&process.env.NEXT_PUBLIC_VERCEL_URL)return`https://${process.env.NEXT_PUBLIC_VERCEL_URL}/api/novu`;try{if(process.env.NODE_ENV==="development"||process.env.NODE_ENV==="dev"){let t=await(await fetch("http://localhost:2022/.well-known/novu")).json();return`${t.tunnelOrigin}${t.route}`}}catch(e){console.error(e)}return""};function xm(e){return!!e&&typeof e=="object"&&"error"in e&&"message"in e&&"statusCode"in e}var uo=(e,t)=>{if(!e)throw new ea;return{post:async(n,r)=>{let i=await fetch(`${t}/v1${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`},body:JSON.stringify(r)}),a=await i.json();if(i.ok)return a;throw xm(a)?new ta(a.statusCode,a.error,a.message):new Xn(a)},delete:async n=>(await fetch(`${t}/v1${n}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`}})).json()}};var Cm=require("liquidjs");function pc(e,t){let n={...e};for(let r of Object.keys(t)){let i=t[r];i&&typeof i=="object"&&!Array.isArray(i)?n[r]=pc(n[r]||{},i):(Array.isArray(i),n[r]=i)}return n}function po(e,t){let n=t.split(".").reduce((r,i)=>{if(r&&typeof r=="object")return r[i]},e);if(n==null)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);if(typeof n=="object"){let r=JSON.stringify(n);return r==="{}"?"":r}return""}function Am(e,t=2,n,r=", "){if(!Array.isArray(e)||e.length===0)return"";let i=n?e.map(s=>typeof s!="object"||!s?"":po(s,n)):e;if(i.length===1)return i[0];if(i.length===2)return`${i[0]} and ${i[1]}`;if(t>=i.length){let s=i.slice(0,-1),l=i[i.length-1];return`${s.join(r)} and ${l}`}let a=i.slice(0,t),o=i.length-t;return`${a.join(r)} and ${o} ${o===1?"other":"others"}`}var vm=Bt(require("pluralize"),1);function km(e,t="",n="",r="true"){if(e==null)return"";let i=0;if(Array.isArray(e)?i=e.length:typeof e=="object"?i=Object.keys(e).length:typeof e=="string"?i=+e:typeof e=="number"?i=e:i=Number(e),Number.isNaN(i)&&(i=0),i<=0)return"";let a;return n?a=i===1?t:n:a=(0,vm.default)(t,i),r==="true"?`${i} ${a}`:a}var _x=require("liquidjs"),Em=Bt(require("pluralize"),1),Ix=require("zod");var Px="",Mx=2,Nx="other",Lx=", ",Dx=" and ",Fx=", and ";function Rm(e,t=Px,n=Mx,r=Nx,i=Lx,a=Dx,o=Fx){if(!Array.isArray(e)||e.length===0)return"";let s=t?e.map(y=>typeof y!="object"||!y?"":po(y,t)):e,l=s.length;if(l===1)return s[0];if(l===2)return`${s[0]}${a}${s[1]}`;if(n>=l){let y=s.slice(0,l-1),g=s[l-1];return`${y.join(i)}${o}${g}`}let p=s.slice(0,n),d=l-n,h=n===1?a:o;return`${p.join(i)}${h}${d} ${(0,Em.default)(r,d)}`}function Ux(e){return Array.isArray(e)||typeof e=="object"&&e!==null?Om(e):typeof e=="string"?e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"):e==null?"":String(e)}var Om=(e,t=0)=>Array.isArray(e)||typeof e=="object"&&e!==null?JSON.stringify(e,null,t).replace(/"/g,"'").replace(/\n/g,"\\n"):e==null?"":String(e);function _m(e){let t=new Cm.Liquid({outputEscape:Ux,...e});return t.registerFilter("json",(n,r)=>Om(n,r)),t.registerFilter("digest",Am),t.registerFilter("toSentence",Rm),t.registerFilter("pluralize",km),t}var Vn=Bt(require("chalk"),1),et={info:e=>Vn.default.blue(e),warning:e=>Vn.default.yellow(e),error:e=>Vn.default.red(e),success:e=>Vn.default.green(e),underline:e=>Vn.default.underline(e),bold:e=>Vn.default.bold(e)},lt={SUCCESS:et.success("\u2714"),ERROR:et.error("\u2717"),WARNING:et.warning("\u26A0"),INFO:et.info("\u2139"),ARROW:et.bold("\u2192"),MOCK:et.info("\u25CB"),HYDRATED:et.bold(et.info("\u2192")),STEP:et.info("\u03C3"),ACTION:et.info("\u03B1"),DURATION:et.info("\u0394"),PROVIDER:et.info("\u2699"),OUTPUT:et.info("\u21E2"),INPUT:et.info("\u21E0"),WORKFLOW:et.info("\u03C9"),STATE:et.info("\u03C3"),EXECUTE:et.info("\u03B5"),PREVIEW:et.info("\u03C1")};function ho(e){return e||process.env.NOVU_API_URL||"https://api.novu.co"}function fo(e){return e||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY||""}var dc=Bt(require("sanitize-html"),1),Hx=["src","alt","width","height","loading","srcset","sizes","crossorigin","usemap","ismap","class","id","style","title","dir","lang"];function $x(e){return e.toLowerCase().startsWith("on")}function qx(e){return e.replace(/<\/([a-zA-Z][a-zA-Z0-9]*)\s*\/[^>]*>/g,"</$1>")}var jx={allowedTags:dc.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,transformTags:{"*":(e,t)=>{let n={};for(let[r,i]of Object.entries(t))$x(r)||(n[r]=i);return{tagName:e,attribs:n}},img:(e,t)=>{let n={};for(let[r,i]of Object.entries(t))Hx.includes(r.toLowerCase())&&(n[r]=i);return{tagName:e,attribs:n}}},allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Im=e=>{if(!e)return e;let t=qx(e),n=/^<!DOCTYPE .*?>/,r=t.match(n),i=(0,dc.default)(t,jx);return r?r[0]+i:i},mo=e=>Object.keys(e).reduce((t,n)=>{let r=e[n];return typeof r=="string"?t[n]=Im(r):Array.isArray(r)?t[n]=r.map(i=>typeof i=="string"?Im(i):typeof i=="object"?mo(i):i):typeof r=="object"&&r!==null?t[n]=mo(r):t[n]=r,t},{});function Pm(e,t=!0,n=console){t&&(n.info(`
156
- ${et.bold(et.underline("Discovered workflowId:"))} '${e.workflowId}'`),e.steps.forEach((r,i)=>{let a=i===e.steps.length-1,o=a?"\u2514":"\u251C";n.info(`${o} ${lt.STEP} Discovered stepId: '${r.stepId}' Type: '${r.type}'`),r.providers.forEach((s,l)=>{let p=l===r.providers.length-1,d=a?" ":"\u2502",h=p?"\u2514":"\u251C";n.info(`${d} ${h} ${lt.PROVIDER} Discovered provider: '${s.type}'`)})}))}var Mm=require("jsonrepair");function Nm(e){let t=e.trim();return(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))&&t.length>2}var Lm="__novuJsonString";function Bx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[Lm]===!0}function xi(e){if(typeof e=="string"){if(!Nm(e))return e;try{let t=JSON.parse(e);return{[Lm]:!0,value:xi(t)}}catch{return e}}if(Array.isArray(e))return e.map(t=>xi(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=xi(r);return t}return e}function Ai(e){if(Bx(e))return JSON.stringify(Ai(e.value));if(Array.isArray(e))return e.map(t=>Ai(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Ai(r);return t}return e}function zx(e){try{return JSON.parse(e),e}catch{try{return(0,Mm.jsonrepair)(e)}catch{return e}}}function Dm(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="string"?[t,Nm(n)?zx(n):n]:typeof n=="object"&&n!==null&&!Array.isArray(n)?[t,Dm(n)]:[t,n]))}function Fm(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:Dm(e.data)}}var Hm=Bt(require("ajv"),1),$m=Bt(require("ajv-formats"),1);var Um=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var go=class extends xn{constructor(n,r){let i=r.length===1?"it":"them";super(`Tried to use a ${n} in @novu/framework without ${r.join(", ")} installed. Please install ${i} by running \`npm install ${r.join(" ")}\`.`);this.statusCode=500;this.code="MissingDependencyError"}};var yo=async(e,t)=>{let n=new Set;if((await Promise.allSettled(e.map(i=>i.import))).forEach((i,a)=>{let o=e[a];i.status==="fulfilled"&&o.exports.every(l=>i.value[l]!==void 0)||n.add(o.name)}),n.size>0)throw new go(t,Array.from(n))};var bo=class{constructor(){this.requiredImports=[];this.ajv=new Hm.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,$m.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(t){let n=t.type==="object"||!!t.anyOf||!!t.allOf||!!t.oneOf;return n&&await yo(this.requiredImports,"JSON schema"),n}async validate(t,n){let r=this.compiledSchemas.get(n);r||(r=this.ajv.compile(n),this.compiledSchemas.set(n,r));let i=Um(t);return r(i)?{success:!0,data:i}:{success:!1,errors:r.errors.map(o=>({path:o.instancePath,message:o.message}))}}async transformToJsonSchema(t){return t}};var wo=class{constructor(){this.requiredImports=[{name:"zod",import:import("zod"),exports:["ZodType"]},{name:"zod-to-json-schema",import:import("zod-to-json-schema"),exports:["zodToJsonSchema"]}]}async canHandle(t){let n=t.safeParseAsync!==void 0;return n&&await yo(this.requiredImports,"Zod schema"),n}async validate(t,n){let r=await n.safeParseAsync(t);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.issues.map(i=>({path:`/${i.path.join("/")}`,message:i.message}))}}async transformToJsonSchema(t){let{zodToJsonSchema:n}=await import("zod-to-json-schema");return n(t)}};var So=new wo,To=new bo,vi=async(e,t)=>{if(await So.canHandle(e))return So.validate(t,e);if(await To.canHandle(e))return To.validate(t,e);throw new Error("Invalid schema")},bt=async e=>{if(await So.canHandle(e))return So.transformToJsonSchema(e);if(await To.canHandle(e))return To.transformToJsonSchema(e);throw new Error("Invalid schema")};function qm(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var dr=class{constructor(t){this.discoveredWorkflows=new Map;this.discoverWorkflowPromises=new Map;this.registeredAgents=new Map;this.version="2.14.0-rc.5ea799b171";let n=this.buildOptions(t);this.apiUrl=n.apiUrl,this.secretKey=n.secretKey,this.strictAuthentication=n.strictAuthentication,this.verbose=n.verbose,this.logger=n.logger,this.templateEngine=_m()}buildOptions(t){let n={apiUrl:ho(t==null?void 0:t.apiUrl),secretKey:fo(t==null?void 0:t.secretKey),strictAuthentication:!qm(),verbose:qm(),logger:console};return(t==null?void 0:t.strictAuthentication)!==void 0?n.strictAuthentication=t.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(n.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),(t==null?void 0:t.verbose)!==void 0&&(n.verbose=t.verbose),(t==null?void 0:t.logger)!==void 0&&(n.logger=t.logger),n}log(...t){this.verbose&&this.logger.info(...t)}async addWorkflows(t){for(let n of t){if(this.discoveredWorkflows.has(n.id))continue;let r=this.discoverWorkflowPromises.get(n.id);if(r){await r;continue}let i=this.addWorkflow(n);this.discoverWorkflowPromises.set(n.id,i),await i}}addAgents(t){for(let n of t)this.registeredAgents.set(n.id,n)}getAgent(t){return this.registeredAgents.get(t)}async addWorkflow(t){try{let n=await t.discover();Pm(n,this.verbose,this.logger),this.discoveredWorkflows.set(t.id,n)}finally{this.discoverWorkflowPromises.delete(t.id)}}healthCheck(){let t=this.getRegisteredWorkflows(),n=t.length,r=t.reduce((i,a)=>i+a.steps.length,0);return{status:"ok",sdkVersion:"2.14.0-rc.5ea799b171",frameworkVersion:"2024-06-26",discovered:{workflows:n,steps:r}}}getWorkflow(t){let n=this.discoveredWorkflows.get(t);if(n)return n;throw new Mr(t)}getStep(t,n){let i=this.getWorkflow(t).steps.find(a=>a.stepId===n);if(i)return i;throw new ca(n)}getRegisteredWorkflows(){return Array.from(this.discoveredWorkflows.values())}discover(){return{workflows:this.getRegisteredWorkflows(),agents:Array.from(this.registeredAgents.keys()).map(t=>({agentId:t}))}}mock(t){try{return Pu(t)}catch(n){return this.logger.warn("Failed to mock schema, returning empty object:",n),{}}}async validate(t,n,r,i,a,o,s){let l=await vi(n,t);if(l.success)return l.data;switch(r){case"event":this.throwInvalidEvent(i,a,l.errors);case"step":this.throwInvalidStep(o,i,a,l.errors);case"provider":this.throwInvalidProvider(o,s,i,a,l.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(t,n,r,i,a){throw t?n?r==="output"?new Ki(i,t,n,a):new Error(`Invalid payload type: '${r}'`):new Error("providerId is required"):new Error("stepId is required")}throwInvalidStep(t,n,r,i){if(!t)throw new Error("stepId is required");switch(n){case"output":throw new Yi(r,t,i);case"result":throw new Ji(r,t,i);case"controls":throw new Wi(r,t,i);default:throw new Error(`Invalid payload type: '${n}'`)}}throwInvalidEvent(t,n,r){switch(t){case"controls":throw new Vi(n,r);case"payload":throw new _r(n,r);default:throw new Error(`Invalid payload type: '${t}'`)}}executeStepFactory(t,n,r){return async(i,a,o)=>{if(r())return;let s=this.getStep(t.workflowId,i),l=t.action==="preview";if(!l&&i===t.stepId){let g=await this.createStepControls(s,t),I=await this.compileControls(g,t);if(await this.shouldSkip(o==null?void 0:o.skip,I))return n({options:{skip:!0},outputs:{},providers:{}}),{}}let p=this.previewStep.bind(this),d=this.executeStep.bind(this),y=await(l?p:d)(t,{...s,providers:s.providers.map(g=>{var K;let I=(K=o==null?void 0:o.providers)==null?void 0:K[g.type];if(!I)throw new na(g.type);return{...g,resolve:I}}),resolve:a});return this.shouldSanitize({stepType:s.type,options:o})&&(y={...y,outputs:mo(y.outputs)}),i===t.stepId&&n({...y,options:{skip:!1}}),y.outputs}}shouldSanitize({stepType:t,options:n}){return(n==null?void 0:n.disableOutputSanitization)===!0?!1:["email","in_app"].includes(t)}async shouldSkip(t,n){return t?t(n):!1}async executeWorkflow(t){let i=`${{execute:"Executing",preview:"Previewing"}[t.action]||t.action} workflowId:`;this.log(`
156
+ ${et.bold(et.underline("Discovered workflowId:"))} '${e.workflowId}'`),e.steps.forEach((r,i)=>{let a=i===e.steps.length-1,o=a?"\u2514":"\u251C";n.info(`${o} ${lt.STEP} Discovered stepId: '${r.stepId}' Type: '${r.type}'`),r.providers.forEach((s,l)=>{let p=l===r.providers.length-1,d=a?" ":"\u2502",h=p?"\u2514":"\u251C";n.info(`${d} ${h} ${lt.PROVIDER} Discovered provider: '${s.type}'`)})}))}var Mm=require("jsonrepair");function Nm(e){let t=e.trim();return(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))&&t.length>2}var Lm="__novuJsonString";function Bx(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[Lm]===!0}function xi(e){if(typeof e=="string"){if(!Nm(e))return e;try{let t=JSON.parse(e);return{[Lm]:!0,value:xi(t)}}catch{return e}}if(Array.isArray(e))return e.map(t=>xi(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=xi(r);return t}return e}function Ai(e){if(Bx(e))return JSON.stringify(Ai(e.value));if(Array.isArray(e))return e.map(t=>Ai(t));if(e&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Ai(r);return t}return e}function zx(e){try{return JSON.parse(e),e}catch{try{return(0,Mm.jsonrepair)(e)}catch{return e}}}function Dm(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="string"?[t,Nm(n)?zx(n):n]:typeof n=="object"&&n!==null&&!Array.isArray(n)?[t,Dm(n)]:[t,n]))}function Fm(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:Dm(e.data)}}var Hm=Bt(require("ajv"),1),$m=Bt(require("ajv-formats"),1);var Um=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var go=class extends xn{constructor(n,r){let i=r.length===1?"it":"them";super(`Tried to use a ${n} in @novu/framework without ${r.join(", ")} installed. Please install ${i} by running \`npm install ${r.join(" ")}\`.`);this.statusCode=500;this.code="MissingDependencyError"}};var yo=async(e,t)=>{let n=new Set;if((await Promise.allSettled(e.map(i=>i.import))).forEach((i,a)=>{let o=e[a];i.status==="fulfilled"&&o.exports.every(l=>i.value[l]!==void 0)||n.add(o.name)}),n.size>0)throw new go(t,Array.from(n))};var bo=class{constructor(){this.requiredImports=[];this.ajv=new Hm.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,$m.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(t){let n=t.type==="object"||!!t.anyOf||!!t.allOf||!!t.oneOf;return n&&await yo(this.requiredImports,"JSON schema"),n}async validate(t,n){let r=this.compiledSchemas.get(n);r||(r=this.ajv.compile(n),this.compiledSchemas.set(n,r));let i=Um(t);return r(i)?{success:!0,data:i}:{success:!1,errors:r.errors.map(o=>({path:o.instancePath,message:o.message}))}}async transformToJsonSchema(t){return t}};var wo=class{constructor(){this.requiredImports=[{name:"zod",import:import("zod"),exports:["ZodType"]},{name:"zod-to-json-schema",import:import("zod-to-json-schema"),exports:["zodToJsonSchema"]}]}async canHandle(t){let n=t.safeParseAsync!==void 0;return n&&await yo(this.requiredImports,"Zod schema"),n}async validate(t,n){let r=await n.safeParseAsync(t);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.issues.map(i=>({path:`/${i.path.join("/")}`,message:i.message}))}}async transformToJsonSchema(t){let{zodToJsonSchema:n}=await import("zod-to-json-schema");return n(t)}};var So=new wo,To=new bo,vi=async(e,t)=>{if(await So.canHandle(e))return So.validate(t,e);if(await To.canHandle(e))return To.validate(t,e);throw new Error("Invalid schema")},bt=async e=>{if(await So.canHandle(e))return So.transformToJsonSchema(e);if(await To.canHandle(e))return To.transformToJsonSchema(e);throw new Error("Invalid schema")};function qm(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var dr=class{constructor(t){this.discoveredWorkflows=new Map;this.discoverWorkflowPromises=new Map;this.registeredAgents=new Map;this.version="2.14.0";let n=this.buildOptions(t);this.apiUrl=n.apiUrl,this.secretKey=n.secretKey,this.strictAuthentication=n.strictAuthentication,this.verbose=n.verbose,this.logger=n.logger,this.templateEngine=_m()}buildOptions(t){let n={apiUrl:ho(t==null?void 0:t.apiUrl),secretKey:fo(t==null?void 0:t.secretKey),strictAuthentication:!qm(),verbose:qm(),logger:console};return(t==null?void 0:t.strictAuthentication)!==void 0?n.strictAuthentication=t.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(n.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),(t==null?void 0:t.verbose)!==void 0&&(n.verbose=t.verbose),(t==null?void 0:t.logger)!==void 0&&(n.logger=t.logger),n}log(...t){this.verbose&&this.logger.info(...t)}async addWorkflows(t){for(let n of t){if(this.discoveredWorkflows.has(n.id))continue;let r=this.discoverWorkflowPromises.get(n.id);if(r){await r;continue}let i=this.addWorkflow(n);this.discoverWorkflowPromises.set(n.id,i),await i}}addAgents(t){for(let n of t)this.registeredAgents.set(n.id,n)}getAgent(t){return this.registeredAgents.get(t)}async addWorkflow(t){try{let n=await t.discover();Pm(n,this.verbose,this.logger),this.discoveredWorkflows.set(t.id,n)}finally{this.discoverWorkflowPromises.delete(t.id)}}healthCheck(){let t=this.getRegisteredWorkflows(),n=t.length,r=t.reduce((i,a)=>i+a.steps.length,0);return{status:"ok",sdkVersion:"2.14.0",frameworkVersion:"2024-06-26",discovered:{workflows:n,steps:r}}}getWorkflow(t){let n=this.discoveredWorkflows.get(t);if(n)return n;throw new Mr(t)}getStep(t,n){let i=this.getWorkflow(t).steps.find(a=>a.stepId===n);if(i)return i;throw new ca(n)}getRegisteredWorkflows(){return Array.from(this.discoveredWorkflows.values())}discover(){return{workflows:this.getRegisteredWorkflows(),agents:Array.from(this.registeredAgents.keys()).map(t=>({agentId:t}))}}mock(t){try{return Pu(t)}catch(n){return this.logger.warn("Failed to mock schema, returning empty object:",n),{}}}async validate(t,n,r,i,a,o,s){let l=await vi(n,t);if(l.success)return l.data;switch(r){case"event":this.throwInvalidEvent(i,a,l.errors);case"step":this.throwInvalidStep(o,i,a,l.errors);case"provider":this.throwInvalidProvider(o,s,i,a,l.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(t,n,r,i,a){throw t?n?r==="output"?new Ki(i,t,n,a):new Error(`Invalid payload type: '${r}'`):new Error("providerId is required"):new Error("stepId is required")}throwInvalidStep(t,n,r,i){if(!t)throw new Error("stepId is required");switch(n){case"output":throw new Yi(r,t,i);case"result":throw new Ji(r,t,i);case"controls":throw new Wi(r,t,i);default:throw new Error(`Invalid payload type: '${n}'`)}}throwInvalidEvent(t,n,r){switch(t){case"controls":throw new Vi(n,r);case"payload":throw new _r(n,r);default:throw new Error(`Invalid payload type: '${t}'`)}}executeStepFactory(t,n,r){return async(i,a,o)=>{if(r())return;let s=this.getStep(t.workflowId,i),l=t.action==="preview";if(!l&&i===t.stepId){let g=await this.createStepControls(s,t),I=await this.compileControls(g,t);if(await this.shouldSkip(o==null?void 0:o.skip,I))return n({options:{skip:!0},outputs:{},providers:{}}),{}}let p=this.previewStep.bind(this),d=this.executeStep.bind(this),y=await(l?p:d)(t,{...s,providers:s.providers.map(g=>{var K;let I=(K=o==null?void 0:o.providers)==null?void 0:K[g.type];if(!I)throw new na(g.type);return{...g,resolve:I}}),resolve:a});return this.shouldSanitize({stepType:s.type,options:o})&&(y={...y,outputs:mo(y.outputs)}),i===t.stepId&&n({...y,options:{skip:!1}}),y.outputs}}shouldSanitize({stepType:t,options:n}){return(n==null?void 0:n.disableOutputSanitization)===!0?!1:["email","in_app"].includes(t)}async shouldSkip(t,n){return t?t(n):!1}async executeWorkflow(t){let i=`${{execute:"Executing",preview:"Previewing"}[t.action]||t.action} workflowId:`;this.log(`
157
157
  ${et.bold(et.underline(i))} '${t.workflowId}'`);let a=this.getWorkflow(t.workflowId),o=process.hrtime(),s={outputs:{},providers:{},options:{skip:!1}},l,p=!1,d=new Promise(Oe=>{l=Oe}),h=Oe=>{if(p)throw new Error("setResult can only be called once per workflow execution");l(),p=!0,s=Oe},y=()=>p,g;try{if(t.action==="execute"&&!t.payload)throw new _r(t.workflowId,{message:"Event `payload` is required"});let Oe=await this.createExecutionPayload(t,a),$={...t,payload:Oe};await Promise.race([d,a.execute({payload:Oe,env:t.env,controls:{},subscriber:t.subscriber,context:t.context,step:{email:this.executeStepFactory($,h,y),sms:this.executeStepFactory($,h,y),inApp:this.executeStepFactory($,h,y),digest:this.executeStepFactory($,h,y),delay:this.executeStepFactory($,h,y),push:this.executeStepFactory($,h,y),chat:this.executeStepFactory($,h,y),custom:this.executeStepFactory($,h,y),throttle:this.executeStepFactory($,h,y),tool:this.executeStepFactory($,h,y)}})])}catch(Oe){g=Oe}let I=process.hrtime(o),K=I[0],Z=I[1],H=K*1e3+Z/1e6,ue=g?lt.ERROR:lt.SUCCESS,ve={execute:"Executed",preview:"Previewed"}[t.action]||t.action;if(this.log(`${ue} ${ve} workflowId: \`${t.workflowId}\``),this.prettyPrintExecute(t,H,g),g)throw g;return{outputs:s.outputs,providers:s.providers,options:s.options,metadata:{status:"success",error:!1,duration:H}}}async createExecutionPayload(t,n){let{payload:r}=t;if(t.action==="preview"){let a=this.mock(n.payload.schema);r=Object.assign(a,r)}return await this.validate(r,n.payload.unknownSchema,"event","payload",t.workflowId)}prettyPrintExecute(t,n,r){if(!this.verbose)return;let i=r?lt.ERROR:lt.SUCCESS,o={execute:"Executed",preview:"Previewed"}[t.action]||t.action,s=r?"Failed to execute":o,l=r?et.error:et.success,p=`${i} ${s} workflowId: '${t.workflowId}`;this.logger.info(`
158
158
  ${et.bold(l(p))}'
159
159
  \u251C ${lt.STEP} stepId: '${t.stepId}'
160
160
  \u251C ${lt.ACTION} action: '${t.action}'
161
161
  \u2514 ${lt.DURATION} duration: '${n.toFixed(2)}ms'
162
- `)}async executeProviders(t,n,r,i){return n.providers.reduce(async(a,o)=>{let s=await a,l=await this.runProvider(t,n,o,r,i);return{...s,[o.type]:l}},Promise.resolve({}))}async runProvider(t,n,r,i,a){let o=t.action==="preview";if(t.stepId!==n.stepId)return o?(this.log(` ${lt.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)):(this.log(` ${lt.HYDRATED} Hydrated provider: \`${r.type}\``),{});try{return await this.resolveProviderOutput(t,n,r,a,i)}catch(s){if(this.log(` ${lt.ERROR} Failed to execute provider: \`${r.type}\``),o)return this.log(` ${lt.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema);throw new ra(r.type,t.action,s)}}async resolveProviderOutput(t,n,r,i,a){let o=await r.resolve({controls:i,outputs:a}),s=await this.validate(o,r.outputs.unknownSchema,"step","output",t.workflowId,n.stepId,r.type);return this.log(` ${lt.SUCCESS} Executed provider: \`${r.type}\``),{...s,_passthrough:o._passthrough}}async executeStep(t,n){if(t.stepId===n.stepId)try{let r=await this.createStepControls(n,t),i=await this.compileControls(r,t),a=await n.resolve(i),o=await this.normalizeChatCardOutput(n,a),s=await this.validate(o,n.outputs.unknownSchema,"step","output",t.workflowId,n.stepId),l=await this.executeProviders(t,n,s,i);return this.log(` ${lt.SUCCESS} Executed stepId: \`${n.stepId}\``),{outputs:s,providers:l}}catch(r){throw this.log(` ${lt.ERROR} Failed to execute stepId: \`${n.stepId}\``),Mn(r)?r:new Pr(n.stepId,t.action,r)}else try{let r=this.getStepState(t,n.stepId);if(r){let i=await this.validate(r.outputs,n.results.unknownSchema,"step","result",t.workflowId,n.stepId);return this.log(` ${lt.HYDRATED} Hydrated stepId: \`${n.stepId}\``),{outputs:i,providers:await this.executeProviders(t,n,i,{})}}else throw new zi(t.workflowId,n.stepId)}catch(r){throw this.log(` ${lt.ERROR} Failed to hydrate stepId: \`${n.stepId}\``),r}}async normalizeChatCardOutput(t,n){if(t.type!=="chat"||(n==null?void 0:n.card)==null)return n;let r=await co(n.card);return r?{...n,card:r}:n}async compileControls(t,n){var r;try{let i=xi(t),a=this.preprocessTranslationPatterns(JSON.stringify(i));a=this.preprocessFilterTranslationArgs(a);let o=this.templateEngine.parse(a),s=this.getWorkflow(n.workflowId),l={workflow:{workflowId:s.workflowId,name:s.name,description:s.description,tags:s.tags,severity:s.severity},payload:n.payload,subscriber:n.subscriber,...n.actor&&{actor:n.actor},context:n.context,steps:Wx(n.state),env:(r=n.env)!=null?r:{}},p=await this.templateEngine.render(o,l),d=this.postprocessTranslationMarkers(p),h=(0,jm.jsonrepair)(d),y=JSON.parse(h),g=Ai(y);return Fm(g)}catch(i){throw new Gi(n.workflowId,n.stepId,i)}}preprocessTranslationPatterns(t){return t.replace(/\{\{\s*t\.([\p{L}\p{N}_.-]+)\s*\}\}/gu,"[T:$1]")}preprocessFilterTranslationArgs(t){return t.replace(/'t\.([\p{L}\p{N}_.-]+)'/gu,"'[T:$1]'")}postprocessTranslationMarkers(t){return t.replace(/\[T:([\p{L}\p{N}_.-]+)\]/gu,"{{t.$1}}")}async createStepControls(t,n){return await this.validate(n.controls,t.controls.unknownSchema,"step","controls",n.workflowId,t.stepId)}async previewStep(t,n){try{return await this.constructStepForPreview(t,n)}catch(r){throw this.log(` ${lt.ERROR} Failed to preview stepId: \`${n.stepId}\``),Mn(r)?r:new Pr(n.stepId,t.action,r)}}async constructStepForPreview(t,n){return t.stepId===n.stepId?await this.previewRequiredStep(n,t):await this.extractMockDataForPreviousSteps(t,n)}async extractMockDataForPreviousSteps(t,n){let r={},i=this.getStepState(t,n.stepId),a=this.mock(n.results.schema);return{outputs:pc(a,(i==null?void 0:i.outputs)||{}),providers:await this.executeProviders(t,n,r,{})}}async previewRequiredStep(t,n){let r=await this.createStepControls(t,n),i=await this.compileControls(r,n),a=await t.resolve(i),o=await this.normalizeChatCardOutput(t,a),s=await this.validate(o,t.outputs.unknownSchema,"step","output",n.workflowId,t.stepId);return this.log(` ${lt.MOCK} Mocked stepId: \`${t.stepId}\``),{outputs:s,providers:await this.executeProviders(n,t,s,i)}}getStepState(t,n){return t.state.find(r=>r.stepId===n)}getStepCode(t,n){return{code:this.getStep(t,n).resolve.toString()}}getWorkflowCode(t){return{code:this.getWorkflow(t).execute.toString()}}getCode(t,n){let r;if(t)n?r=this.getStepCode(t,n):r=this.getWorkflowCode(t);else throw new Mr(t);return r}};function Wx(e){let t={};for(let n of e)t[n.stepId]=n.outputs;return t}var Bm=Symbol.for("novu.agent.runtimeContext");var hc=(o=>(o.ON_MESSAGE="onMessage",o.ON_MESSAGE_UPDATED="onMessageUpdated",o.ON_MESSAGE_DELETED="onMessageDeleted",o.ON_ACTION="onAction",o.ON_RESOLVE="onResolve",o.ON_REACTION="onReaction",o))(hc||{});function fc(e){return typeof e=="object"&&e!==null&&"content"in e&&!("type"in e)}var hr=class{constructor(){this.__novuPendingApproval=!0}};function zm(e){return typeof e=="object"&&e!==null&&"suppress"in e&&e.suppress===!0}var Yx=5*1024*1024,Jx=5*1024*1024,Vm=32768,Gx=/^[A-Za-z0-9+/]*={0,2}$/;function Ei(e,t){return e.filename?`"${e.filename}"`:`at index ${t}`}function Wm(){return globalThis.Buffer}function Kx(e){var t,n,r;return(r=(n=(t=Wm())==null?void 0:t.isBuffer)==null?void 0:n.call(t,e))!=null?r:!1}function Xx(e){return typeof Blob!="undefined"&&e instanceof Blob}function mc(e){let t=Wm();if(t)return t.from(e).toString("base64");if(typeof btoa!="function")throw new Error("Unable to encode file data: base64 encoding is not available in this runtime.");let n="";for(let r=0;r<e.length;r+=Vm){let i=e.subarray(r,r+Vm);n+=String.fromCharCode(...i)}return btoa(n)}function Ym(e){let t=e.replace(/\s/g,""),n=t.length%4;if(!t||n===1||!Gx.test(t))return null;let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-r}function ki(e,t,n){if(e>Yx)throw new Error(`Invalid file ${Ei(t,n)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function Qx(e,t,n){if(typeof e=="string"){let r=Ym(e);if(r===null)throw new Error(`Invalid file ${Ei(t,n)}: data must be a base64-encoded string.`);return ki(r,t,n),e}if(Kx(e))return ki(e.byteLength,t,n),e.toString("base64");if(e instanceof Uint8Array)return ki(e.byteLength,t,n),mc(e);if(e instanceof ArrayBuffer)return ki(e.byteLength,t,n),mc(new Uint8Array(e));if(Xx(e))return ki(e.size,t,n),mc(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${Ei(t,n)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function Zx(e){if(!(e!=null&&e.length))return;let t=[],n=0;for(let[r,i]of e.entries()){let a=i.data,o=i.url,s=a!=null,l=o!=null;if(s===l)throw new Error(`Invalid file ${Ei(i,r)}: provide exactly one of data or url.`);if(s){let p=await Qx(a,i,r),d=Ym(p);if(n+=d!=null?d:0,n>Jx)throw new Error("Invalid files: total inline data must be 5 MB or smaller. Use publicly-accessible URLs for larger files.");t.push({...i,data:p});continue}if(l&&typeof o!="string")throw new Error(`Invalid file ${Ei(i,r)}: url must be a string.`);t.push(i)}return t}async function xo(e,t){let n=await Zx(t);if(typeof e=="string")return n?{markdown:e,files:n}:{markdown:e};let r=await co(e);if(r)return n?{card:r,files:n}:{card:r};throw new Error("Invalid message content \u2014 expected string or CardElement")}var Jm=1;var eA={400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",408:"Request Timeout",409:"Conflict",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"};function Ao(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:Ao(e.message)}function tA(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=Ao(n.message);if(r)return r;let i=Ao(n.error);if(i)return i;let a=n.errors;return Array.isArray(a)?Ao(a[0]):null}function nA(e,t){var i;let n=(i=eA[e])!=null?i:e,r=tA(t);return r?`Delivery failed: ${n}: ${r}`:`Delivery failed: ${n}`}var bn=class extends Error{constructor(t,n){super(t),this.name="AgentError",this.cause=n==null?void 0:n.cause,this.delivery=n==null?void 0:n.delivery}},an=class extends bn{constructor(t,n){let r={statusCode:t,responseBody:n};super(nA(t,n),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=t,this.responseBody=n}};function Ri(e){return e instanceof bn?e:e instanceof Error?new bn(e.message,{cause:e}):new bn("Turn failed",{cause:e})}function rA(e){return new Promise(t=>{setTimeout(t,e)})}function iA(e){return e>=500||e===408||e===429}var vo=class{constructor(t){this.sequence=0;this.buffer=[];this.chain=Promise.resolve();var n,r;this.runId=`run_${crypto.randomUUID()}`,this.eventsUrl=t.eventsUrl,this.secretKey=t.secretKey,this.conversationId=t.conversationId,this.agentId=t.agentId,this.turnId=t.turnId,this.fetchFn=(n=t.fetchFn)!=null?n:fetch,this.maxRetries=(r=t.maxRetries)!=null?r:3}enqueue(t){this.sequence+=1,this.buffer.push({version:Jm,conversationId:this.conversationId,agentId:this.agentId,runId:this.runId,turnId:this.turnId,sequence:this.sequence,timestamp:new Date().toISOString(),event:t})}flush(){if(this.buffer.length===0)return this.chain;let t=this.buffer;return this.buffer=[],this.chain=this.chain.then(()=>this.postBatchWithRetry(t)),this.chain}async emit(t){this.enqueue(t),await this.flush()}async postBatchWithRetry(t){let n;for(let r=1;r<=this.maxRetries;r+=1)try{await this.postBatch(t);return}catch(i){if(n=i,!aA(i))throw i;r<this.maxRetries&&await rA(250*r)}throw n}async postBatch(t){let n;try{n=await this.fetchFn(this.eventsUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this.secretKey}`},body:JSON.stringify({events:t})})}catch(i){throw oA(i)}let r=await n.text().catch(()=>"");if(!n.ok)throw new an(n.status,r)}};function aA(e){return!(e instanceof an)||e.statusCode===0?!0:iA(e.statusCode)}function oA(e){if(e instanceof an)return e;let t=e instanceof Error?e.message:"Network request failed";return new an(0,t)}var gc="human:";function ko(e){return`${gc}${e}:approve`}function Eo(e){return`${gc}${e}:deny`}function fr(e,t){return`${gc}${e}:opt:${t}`}function Gm(e){return typeof e=="string"?e:e.label}function sA(e){return typeof e=="string"?void 0:e.id}function lA(e){return typeof e=="string"?e:e.id}function Co(e,t){let n=t==null?void 0:t.trim();if(!n)throw new Error(`ctx.${e} requires a title (string argument or card.title)`);return n}function cA(e){if(!("title"in e))return;let t=e.title;return typeof t=="string"&&t.trim()?t.trim():void 0}function Oo(e){if(!e||e.length<2||e.length>10)throw new Error("ctx.choose requires between 2 and 10 options");if(e.some(t=>Gm(t).trim().length===0))throw new Error("ctx.choose options must be non-empty strings")}function _o(e){if(e.length>4)throw new Error("ctx.approve card.extraActions supports at most 4 buttons");for(let t of e){let n=sA(t);if(!Gm(t).trim())throw new Error("ctx.approve extraActions labels must be non-empty");if(n==="approve"||n==="deny")throw new Error("ctx.approve extraActions ids cannot be approve or deny")}}function uA(e){if(typeof e=="string")throw new Error("human render must return chrome (*Card()), a Card, or a chat element \u2014 not a markdown string")}function Ro(e,t=[]){if(Array.isArray(e)){for(let r of e)Ro(r,t);return t}if(!e||typeof e!="object")return t;let n=e;n.type==="button"&&typeof n.id=="string"&&n.id.trim()&&t.push({id:n.id,label:typeof n.label=="string"?n.label:""});for(let r of Object.values(n))r&&typeof r=="object"&&Ro(r,t);return t}function pA(e){return new Set(Ro(e).map(t=>t.id))}function dA(e,t){let n=fr(t,"");return e.startsWith(n)&&e.length>n.length?e.slice(n.length):e}function hA(e,t){let n=Ro(e),r=new Set(n.map(s=>s.id)),i=ko(t),a=Eo(t);if(!r.has(i))throw new Error("ctx.approve render must include a button with actionIds.approve");if(!r.has(a))throw new Error("ctx.approve render must include a button with actionIds.deny");let o=n.filter(s=>s.id!==i&&s.id!==a).map(s=>({id:dA(s.id,t),label:s.label}));o.length&&_o(o)}function fA(e,t,n){if(n){Oo(n);for(let i of n){let a=lA(i);if(!e.has(fr(t,a)))throw new Error(`ctx.choose render must include a button with actionIds.option('${a}')`)}return}let r=mA(e,t);if(r.length<2||r.length>10)throw new Error("ctx.choose render must include between 2 and 10 option action buttons")}function mA(e,t){let n=fr(t,"");return[...e].filter(r=>r.startsWith(n)&&r.length>n.length).map(r=>r.slice(n.length))}function Km(e,t,n){var r;switch(Co(e,t.title),e){case"ask":case"tell":return;case"approve":t.type==="human-approve-card"&&t.extraActions&&_o(t.extraActions);return;case"choose":Oo(t.type==="human-choose-card"&&(r=t.options)!=null?r:n);return;default:return}}function Xm(e,t,n,r){switch(uA(t),Co(e,cA(t)),e){case"ask":case"tell":return;case"approve":hA(t,n);return;case"choose":fA(pA(t),n,r);return;default:return}}function Io(e){let t=typeof e=="string"?[e]:e,n=[],r=new Set;for(let i of t){if(typeof i!="string")throw new Error("`to` must be a subscriberId string or an array of subscriberIds");let a=i.trim();!a||r.has(a)||(r.add(a),n.push(a))}if(n.length===0)throw new Error("`to` must include at least one subscriberId");if(n.length>50)throw new Error("`to` supports at most 50 subscriberIds");return n}var Qm="tool-approval";function gA(e){return e==="approve"||e==="deny"}function yc(e,t){return`${Qm}:${e}:${t}`}function Zm(e){let[t,n,...r]=(e!=null?e:"").split(":"),i=r.join(":");return t!==Qm||!gA(n)||!i?null:{approved:n==="approve",approvalId:i}}async function eg(e,t,n,r,i){var d,h;let a=r!=null?r:t.id,o={approve:yc("approve",a),deny:yc("deny",a)},s=y=>({type:"tool-approval-card",...y}),l=(h=(d=n==null?void 0:n.renderApproval)==null?void 0:d.call(n,{toolCall:t,actionIds:o,approvalCard:s}))!=null?h:s(),p={approvalId:a,toolCallId:t.id,name:t.name,input:t.input,...(i==null?void 0:i.to)!==void 0?{to:i.to}:{},...i!=null&&i.from?{from:i.from}:{},...(i==null?void 0:i.ttlSeconds)!==void 0?{ttlSeconds:i.ttlSeconds}:{}};if(e.emitToolApprovalRequest(p),hm(l)){await e.replyApprovalCard(l);return}await e.reply(l)}function Po(e){return t=>({type:e,...t})}function Mo(e,t){switch(e){case"ask":return{requestId:t,askCard:Po("human-ask-card")};case"approve":return{requestId:t,actionIds:{approve:ko(t),deny:Eo(t)},approveCard:Po("human-approve-card")};case"choose":return{requestId:t,actionIds:{option:n=>fr(t,n)},chooseCard:Po("human-choose-card")};case"tell":return{requestId:t,tellCard:Po("human-tell-card")};default:return e}}function Sc(e){return`${e}_${crypto.randomUUID()}`}function yA(e){let{type:t,...n}=e;return n}function bA(e){if(!(!e||!("card"in e)))return e.card}function No(e){if(!(!e||!("render"in e)))return e.render}function wA(e){return typeof e=="object"&&e!==null&&pr(e)?e:{type:"card",children:[e]}}function bc(e){if(!(!e||!("ttlSeconds"in e)||typeof e.ttlSeconds!="number"))return e.ttlSeconds}function tg(e){if(e.markdown!==void 0)return{markdown:e.markdown};if(e.card!==void 0)return{card:e.card};throw new Error("Invalid reply content \u2014 expected markdown or card")}function SA(e){let t="platformMessageId"in e?e.platformMessageId.trim():e.messageId.trim();if(!t)throw new Error("quoteReply requires a non-empty platform message id");return{messageId:t}}function ng(e){if(e!=null&&e.length)return e.map((t,n)=>({fileId:t.filename||`file_${n}`,name:t.filename,mediaType:t.mimeType,...t.data!==void 0?{data:typeof t.data=="string"?t.data:void 0}:{},...t.url!==void 0?{url:t.url}:{}}))}function wc(e,t){var r;let n=[];if(e.toolApprovalRequest){let i=e.toolApprovalRequest;n.push({type:"tool-approval-request",approvalId:i.approvalId,toolUseId:i.toolCallId,toolName:i.name,input:i.input,...i.ttlSeconds!==void 0?{ttlSeconds:i.ttlSeconds}:{},...i.to!==void 0?{to:i.to}:{},...i.from!==void 0?{from:i.from}:{},...t!=null&&t.deliverApprovalCard?{deliverCard:!0}:{}})}for(let i of e.toolResults)n.push({type:"tool-use-result",toolUseId:i.toolCallId,content:[{type:"text",text:String((r=i.preview)!=null?r:"")},{type:"json",value:i.output}]});for(let i of e.signals)n.push({type:"signal",signal:i});for(let i of e.addReactions)n.push({type:"channel.reaction",messageId:i.messageId,emoji:i.emojiName,op:"add"});for(let i of e.deleteMessages)n.push({type:"channel.delete",messageId:i.messageId});return e.resolve&&n.push({type:"resolve",summary:e.resolve.summary}),n}var Tc=class{constructor(t){this.outbox=t}async sendReply(t,n,r){let i=Sc("msg"),a=wc(n);return a.push({type:"message",role:"assistant",messageId:i,content:tg(t),files:ng(t.files),...r?{quoteReply:r}:{}}),await this._emitAndFlush(a),{messageId:i,platformThreadId:""}}async sendApprovalCard(t,n){return await this._emitAndFlush(wc(n,{deliverApprovalCard:!0})),"unaddressable"}async editMessage(t,n){return await this.outbox.emit({type:"channel.edit",messageId:t,content:tg(n),files:ng(n.files)}),{messageId:t,platformThreadId:""}}async deleteMessage(t){await this.outbox.emit({type:"channel.delete",messageId:t})}async setTyping(t){if(t==="stop"){await this.outbox.emit({type:"channel.typing",state:"off"});return}let n=typeof t=="object"&&"status"in t?t.status:void 0;await this.outbox.emit({type:"channel.typing",state:"on",status:n})}async flushSideEffects(t){await this._emitAndFlush(wc(t))}async emitCustom(t,n){await this.outbox.emit({type:"custom",name:t,data:n})}queueRunStart(){this.outbox.enqueue({type:"run-start"})}async emitRunFinish(t){await this.outbox.emit({type:"run-finish",outcome:t})}async reportTurnError(t){await this.outbox.emit({type:"run-error",message:t!=null?t:"agent handler failed"})}async _emitAndFlush(t){if(t.length!==0){for(let n of t)this.outbox.enqueue(n);await this.outbox.flush()}}},Lo=class{constructor(t,n,r){this.transport=r;this.editedByHandler=!1;this.messageId=t,this.platformThreadId=n}async edit(t,n){this.editedByHandler=!0;let r=await xo(t,n==null?void 0:n.files),i=await this.transport.editMessage(this.messageId,r);if(!i)throw new Error("Agent edit did not return a message handle");return this.messageId=i.messageId,this.platformThreadId=i.platformThreadId,this}async delete(){await this.transport.deleteMessage(this.messageId)}},xc=class{constructor(){this.messageId="";this.platformThreadId=""}async edit(){return this}async delete(){}},rg;rg=Bm;var Do=class{constructor(t,n,r){this[rg]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;this._pendingHumanRenders=[];var l,p,d,h,y,g;this.event=t.event,this.action=(l=t.action)!=null?l:null,this.message=t.message,this.previousMessage=(p=t.previousMessage)!=null?p:null,this.reaction=t.reaction,this.conversation=t.conversation,this.subscriber=t.subscriber,this.context=(d=t.context)!=null?d:null,this.notification=(h=t.notification)!=null?h:null,this.history=t.history,this.platform=t.platform,this.platformContext=t.platformContext,this.humanResponse=(y=t.humanResponse)!=null?y:null,this._toolApprovalConfig=r;let i=t.eventsUrl;if(!i)throw new Error("AgentBridgeRequest.eventsUrl is required");this._transport=new Tc(new vo({eventsUrl:i,secretKey:n,conversationId:t.conversationId,agentId:t.agentId,turnId:t.deliveryId})),this._metadataState={...(g=t.conversation.metadata)!=null?g:{}};let a=this;this.metadata={get(I){return a._metadataState[I]},set(I,K){a._metadataState[I]=K,a._signals.push({type:"metadata",action:"set",key:I,value:K})},delete(I){delete a._metadataState[I],a._signals.push({type:"metadata",action:"delete",key:I})},clear(){a._metadataState={},a._signals.push({type:"metadata",action:"clear"})},get current(){return{...a._metadataState}}};let o=I=>this._transport.setTyping(I),s=(I=>o(I===void 0?{}:{status:I}));s.stop=()=>o("stop"),this.typing=s,this.toolApproval={request:async(I,K)=>(await eg(this,I,this._toolApprovalConfig,void 0,K),new hr)}}asMessageContext(){return this}async reply(t,n){await this.materializePendingHumanRenders();let r=await xo(t,n==null?void 0:n.files),i=this._drainSideEffectsSnapshot(),a=n!=null&&n.quoteReply?SA(n.quoteReply):void 0,o=await this._transport.sendReply(r,i,a);if(!o)throw new Error("Agent reply did not return a message handle");return new Lo(o.messageId,o.platformThreadId,this._transport)}async replyApprovalCard(t){await this.materializePendingHumanRenders();let n=this._drainSideEffectsSnapshot();return await this._transport.sendApprovalCard(t,n),new xc}createReplyHandle(t){return new Lo(t,"",this._transport)}async emit(t){await this._transport.emitCustom(t.name,t.data)}resolve(t){this._resolveSignal={summary:t}}trigger(t,n){this._signals.push({...n,type:"trigger",workflowId:t})}ask(t,n){let i=typeof t!="string"?t:n,a=No(i);return a?this.queueRendered("ask",i,a):this.queueHumanSignal("ask",t,n)}approve(t,n){let i=typeof t!="string"?t:n,a=No(i);return a?this.queueRendered("approve",i,a):this.queueHumanSignal("approve",t,n)}choose(t,n,r){var l;let i=typeof t!="string",a,o;i?a=t:Array.isArray(n)?(a=r,o=n):a=n;let s=No(a);return s?this.queueRendered("choose",a,s):i?this.queueHumanSignal("choose",t,void 0,"card"in t?(l=t.card)==null?void 0:l.options:void 0):this.queueHumanSignal("choose",t,a,o)}tell(t,n){let r=typeof t!="string",i=r?t:n,a=No(i);if(a)return this.queueRendered("tell",i,a);if(r)throw new Error("ctx.tell requires a title (string argument) when render is omitted");return this.queueHumanSignal("tell",t,n)}queueHumanSignal(t,n,r,i){let a=typeof n!="string",o=a?void 0:n,s=a?n:r,l=bA(s),p=Co(t,(o==null?void 0:o.trim())||(l==null?void 0:l.title));if(t==="choose"){let I=i!=null?i:l==null?void 0:l.options;Oo(I)}t==="approve"&&(l!=null&&l.extraActions)&&_o(l.extraActions);let d=Sc("hr"),h=(s==null?void 0:s.to)!==void 0?Io(s.to):void 0,y={...l,title:p,...t==="choose"&&i?{options:i}:{}},g=bc(s);return this._signals.push({type:"human",kind:t,requestId:d,card:y,...s!=null&&s.from?{from:s.from}:{},...g!==void 0?{ttlSeconds:g}:{},...h!==void 0?{to:h}:{}}),d}queueRendered(t,n,r){let i=Sc("hr");return this._pendingHumanRenders.push(async()=>{let a=await this.invokeHumanRender(t,i,r);if(fm(a)){this.pushRenderedChrome(t,i,a,n);return}await this.pushRenderedContent(t,i,a,n)}),i}invokeHumanRender(t,n,r){switch(t){case"ask":return Promise.resolve(r(Mo("ask",n)));case"approve":return Promise.resolve(r(Mo("approve",n)));case"choose":return Promise.resolve(r(Mo("choose",n)));case"tell":return Promise.resolve(r(Mo("tell",n)));default:{let i=t;return Promise.resolve(i)}}}pushRenderedChrome(t,n,r,i){Km(t,r);let a=yA(r),o=bc(i),s=(i==null?void 0:i.to)!==void 0?Io(i.to):void 0,l=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...l?{actionIdentifier:n}:{},card:a,...i!=null&&i.from?{from:i.from}:{},...o!==void 0?{ttlSeconds:o}:{},...s!==void 0?{to:s}:{}})}async pushRenderedContent(t,n,r,i){Xm(t,r,n);let a=await xo(wA(r));if(!a.card)throw new Error("human render must return chrome (*Card()), a Card, or a chat element \u2014 not a markdown string");let o=bc(i),s=(i==null?void 0:i.to)!==void 0?Io(i.to):void 0,l=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...l?{actionIdentifier:n}:{},card:a.card,...i!=null&&i.from?{from:i.from}:{},...o!==void 0?{ttlSeconds:o}:{},...s!==void 0?{to:s}:{}})}emitToolApprovalRequest(t){if(this._pendingToolApprovalRequest)throw new Error("Only one tool approval request can be queued before the next reply");this._pendingToolApprovalRequest=t}emitToolResult(t){this._toolResults.push(t)}addReaction(t,n){this._pendingReactions.push({messageId:t,emojiName:n})}deleteMessage(t){this._pendingDeletes.push({messageId:t})}queueRunStart(){this._transport.queueRunStart()}async emitRunFinish(t){try{await this._transport.emitRunFinish(t.outcome)}catch(n){console.error("[agent] Failed to emit run finish:",n)}}async reportTurnError(t){try{await this._transport.reportTurnError(t)}catch(n){console.error("[agent] Failed to report turn error:",n)}}async flush(){if(await this.materializePendingHumanRenders(),!this._hasPendingSideEffects())return;let t=this._drainSideEffectsSnapshot();await this._transport.flushSideEffects(t)}async materializePendingHumanRenders(){let t=this._pendingHumanRenders.splice(0);for(let n of t)await n()}_hasPendingSideEffects(){return!!(this._pendingToolApprovalRequest||this._signals.length||this._toolResults.length||this._resolveSignal||this._pendingReactions.length||this._pendingDeletes.length)}_drainSideEffectsSnapshot(){let t={toolApprovalRequest:this._pendingToolApprovalRequest,signals:this._signals,toolResults:this._toolResults,addReactions:this._pendingReactions,deleteMessages:this._pendingDeletes,resolve:this._resolveSignal};return this._pendingToolApprovalRequest=null,this._signals=[],this._toolResults=[],this._pendingReactions=[],this._pendingDeletes=[],this._resolveSignal=null,t}};function TA(e){return!!(typeof e=="string"||typeof e=="object"&&e!==null&&pr(e)||typeof e=="object"&&e!==null&&("markdown"in e||"card"in e||"files"in e))}function xA(e,t){return e}var ig="tool_approval:";function AA(e){if(!(e!=null&&e.startsWith(ig)))return null;let t=e.slice(ig.length);return t.length>0?t:null}async function ag(e,t){await e.reply(t.content,{files:t.files,quoteReply:t.quoteReply})}async function Wn(e,t){if(!(t instanceof hr||t===void 0)){if(fc(t)){await ag(e,t);return}await e.reply(t)}}async function vA(e,t){return zm(t)?!0:fc(t)?(await ag(e,t),!0):TA(t)?(await e.reply(t),!0):!1}function kA(e,t){var n;for(let r of e){let i=r.toolData;if(r.type==="tool_approval_request"&&(i==null?void 0:i.approvalId)===t&&i.toolCallId)return{approvalId:i.approvalId,toolCallId:i.toolCallId,name:(n=i.toolName)!=null?n:"tool",input:i.input}}}async function og(e){var a;let t=new Do(e.bridge,e.secretKey,e.agent.handlers.toolApproval),{agent:n,event:r,logger:i}=e;try{t.queueRunStart(),await RA(n,r,t),await t.flush(),await t.emitRunFinish({outcome:"completed"})}catch(o){let s=Ri(o);i==null||i.error(`[agent:${n.id}] Turn failed (${r}): ${s.message}`,(a=s.cause)!=null?a:s);let l=!1;if(n.handlers.onError)try{let p=await n.handlers.onError(s,xA(t,r));l=await vA(t,p)}catch(p){i==null||i.error(`[agent:${n.id}] onError failed:`,p)}l?await t.emitRunFinish({outcome:"completed"}):await t.reportTurnError(s.message)}finally{try{await t.typing.stop(),await t.flush()}catch{}}}async function EA(e,t){var s,l,p,d,h,y;let n=AA((s=t.humanResponse)==null?void 0:s.requestId),r=Zm((l=t.action)==null?void 0:l.id),i=n!=null?n:r==null?void 0:r.approvalId,a=n?((p=t.humanResponse)==null?void 0:p.status)==="approved"&&!t.humanResponse.expired:r==null?void 0:r.approved;if(i&&a!==void 0&&e.handlers.onToolApproval){let g=kA(t.history,i),I=g?{id:g.toolCallId,name:g.name,input:g.input}:{id:i,name:""},K=t.createReplyHandle((h=(d=t.action)==null?void 0:d.sourceMessageId)!=null?h:""),Z={toolCall:I,approved:a,approvalMessage:K};e.userOnToolApproval===!1&&(await t.typing(),(y=t.action)!=null&&y.sourceMessageId&&await K.delete());let H=await e.handlers.onToolApproval(Z,t);await Wn(t,H);return}let o=t.action;o&&e.handlers.onAction&&await Wn(t,await e.handlers.onAction(o,t))}async function RA(e,t,n){switch(t){case"onMessage":{let r=n.message;r&&await Wn(n,await e.handlers.onMessage(r,n));break}case"onMessageUpdated":{let r=n.message;r&&e.handlers.onMessageUpdated&&await Wn(n,await e.handlers.onMessageUpdated(r,n));break}case"onMessageDeleted":{let r=n.message;r&&e.handlers.onMessageDeleted&&await Wn(n,await e.handlers.onMessageDeleted(r,n));break}case"onAction":{await EA(e,n);break}case"onReaction":{let r=n.reaction;r&&e.handlers.onReaction&&await Wn(n,await e.handlers.onReaction(r,n));break}case"onResolve":e.handlers.onResolve&&await Wn(n,await e.handlers.onResolve(n));break;default:throw new Nn(t,hc)}}function sg(e){let t={};for(let i of e.split(",")){let a=i.trim();if(!a)continue;let o=a.indexOf("=");if(o<=0)continue;let s=a.slice(0,o),l=a.slice(o+1);s&&l&&!(s in t)&&(t[s]=l)}let n=t.t,r=n!==void 0?Number(n):Number.NaN;return{t:Number.isFinite(r)?r:void 0,v1:t.v1}}var mr=class{constructor(t){this.handler=t.handler,this.client=t.client?t.client:new dr,this.workflows=t.workflows||[],this.agents=t.agents||[],this.http=uo(this.client.secretKey,this.client.apiUrl),this.frameworkName=t.frameworkName,this.hmacEnabled=this.client.strictAuthentication,this.waitUntil=t.waitUntil,this.client.addAgents(this.agents)}createHandler(){return async(...t)=>{await this.client.addWorkflows(this.workflows);let n=await this.handler(...t),r=await this.handleAction({actions:n});return n.transformResponse(r)}}getStaticHeaders(){let t=`novu-framework:v${this.client.version}`;return{"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-private-network":"true","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":"2024-06-26","novu-framework-sdk":"2.14.0-rc.5ea799b171","novu-framework-server":this.frameworkName,"user-agent":t}}createResponse(t,n){return{status:t,body:JSON.stringify(n),headers:{...this.getStaticHeaders()}}}createError(t){return{status:t.statusCode,body:JSON.stringify({message:t.message,data:t.data,code:t.code}),headers:this.getStaticHeaders()}}async handleAction({actions:t}){var h;let n=await t.url(),r=await t.method(),i=n.searchParams.get("action")||"health-check",a=n.searchParams.get("workflowId")||"",o=n.searchParams.get("stepId")||"",s=n.searchParams.get("agentId")||"",l=n.searchParams.get("event")||"",p=await t.headers("novu-signature")||"",d={};try{r==="POST"&&(d=await t.body())}catch{}try{i!=="health-check"&&await this.validateHmac(d,p);let y=this.getPostActionMap(d,a,o,i,s,l,(h=this.waitUntil)!=null?h:t.waitUntil),g=this.getGetActionMap(a,o);if(r==="POST")return await this.handlePostAction(i,y);if(r==="GET")return await this.handleGetAction(i,g);if(r==="OPTIONS")return this.createResponse(200,{})}catch(y){return this.handleError(y)}return this.createError(new Zi(r))}getPostActionMap(t,n,r,i,a,o,s){return{trigger:this.triggerAction({workflowId:n,...t}),execute:async()=>{let l=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,l)},preview:async()=>{let l=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,l)},"agent-event":async()=>{let l=this.client.getAgent(a);if(!l)return this.createResponse(404,{error:`Agent '${a}' not registered`});let p=og({agent:l,event:o,bridge:t,secretKey:this.client.secretKey,logger:this.client.logger});return s?s(p):this.warnOnUnprotectedServerlessRuntime(a),this.createResponse(200,{status:"ack"})}}}warnOnUnprotectedServerlessRuntime(t){let n;try{process.env.AWS_LAMBDA_FUNCTION_NAME?n="AWS Lambda":process.env.VERCEL&&(n="Vercel")}catch{}n&&this.client.logger.warn(`[agent:${t}] Agent event acknowledged without a \`waitUntil\` primitive while running on ${n}. The runtime may freeze once the response is sent, silently dropping the rest of the agent turn. Pass \`waitUntil\` to \`serve()\` (e.g. \`serve({ agents, waitUntil })\`) to extend the invocation lifetime.`)}triggerAction(t){return async()=>{let n={name:t.workflowId,to:t.to,payload:(t==null?void 0:t.payload)||{},transactionId:t.transactionId,overrides:t.overrides||{},...t.actor&&{actor:t.actor},...t.bridgeUrl&&{bridgeUrl:t.bridgeUrl},...t.controls&&{controls:t.controls},...t.context&&{context:t.context},...t.agentId!==void 0&&{agentId:t.agentId}},r=await this.http.post("/events/trigger",n);return this.createResponse(200,r)}}getGetActionMap(t,n){return{discover:async()=>{let r=await this.client.discover();return this.createResponse(200,r)},"health-check":async()=>{let r=await this.client.healthCheck();return this.createResponse(200,r)},code:async()=>{let r=await this.client.getCode(t,n);return this.createResponse(200,r)}}}async handlePostAction(t,n){if(Object.values(Cr).includes(t)){let r=n[t];return r()}else throw new Nn(t,Cr)}async handleGetAction(t,n){if(Object.values($i).includes(t)){let r=n[t];return r()}else throw new Nn(t,$i)}handleError(t){if(Mn(t))return t.statusCode>=500&&this.client.logger.error(t),this.createError(t);if(vu(t))return this.createError(t);{let n=new Xn(t);return this.client.logger.error(n),this.createError(n)}}async validateHmac(t,n){if(!this.hmacEnabled)return;if(!n)throw new aa;if(!this.client.secretKey)throw new la;let r=sg(n);if(!r.v1||r.t===void 0)throw new oa;let i=Date.now();if(r.t<i-3e5||r.t>i+3e5)throw new sa;let a=await ym(this.client.secretKey,`${r.t}.${JSON.stringify(t)}`);if(!bm(a,r.v1))throw new ia}};function Ac(e,t){if(!e)throw new Error("agent() requires a non-empty agentId");if(!(t!=null&&t.onMessage))throw new Error(`agent('${e}') requires an onMessage handler`);return{id:e,handlers:t,userOnToolApproval:typeof t.onToolApproval=="function"}}var ae={output:{type:"object",properties:{},required:[],additionalProperties:!0}};var CA={type:"object",properties:{text:{type:"string",description:"Overrides the step body text."},effect:{type:"string",description:"iMessage expressive effect: a friendly name (confetti, fireworks, balloons, heart, lasers, celebration, sparkles, spotlight, echo, slam, loud, gentle, invisible) or a raw com.apple.\u2026 effect id."},attachments:{type:"array",items:{type:"string",format:"uri"},description:"Attachment URLs sent alongside the message."},voice:{type:"string",format:"uri",description:"Audio URL sent as a native iMessage voice note (waveform bubble)."},replyToLast:{type:"boolean",description:"Reply-thread this send to the previous message sent to this recipient."},format:{type:"string",enum:["markdown","text"],description:"Force native styled text (markdown) or plain text for the body."}},additionalProperties:!0},cg={output:CA};var OA={type:"object",properties:{webhookUrl:{type:"string",format:"uri"},text:{type:"string"},blocks:{type:"array",items:{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!0}}},additionalProperties:!0},ug={output:OA};var pg={"chat-webhook":ae,discord:ae,"google-chat":ae,getstream:ae,"grafana-on-call":ae,line:ae,mattermost:ae,msteams:ae,"novu-slack":ae,"novu-web-chat":ae,"photon-imessage":cg,"rocket-chat":ae,ryver:ae,sendblue:ae,slack:ug,"webex-messaging":ae,"whatsapp-business":ae,zulip:ae,telegram:ae};var _A={type:"object",properties:{to:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:'Email address of the recipient(s). Example: "Bob bob@host.com". You can use commas to separate multiple recipients (e.g.: "test@example.com,test@example.com" or ["test@example.com", "test@example.com"]).'},from:{type:"string"},subject:{type:"string",description:"Subject of the message."},text:{type:"string",description:"Text version of the message."},html:{type:"string",description:"HTML version of the message."},message:{type:"string",description:"MIME string of the message. Make sure to use multipart/form-data to send this as a file upload."},cc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Same as To but for carbon copy"},bcc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Same as To but for blind carbon copy"},ampHtml:{type:"string"},tVersion:{type:"string"},tText:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},oTag:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Tag string. See Tagging for more information."},oDkim:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Enables/disabled DKIM signatures on per-message basis. Pass yes or no"},oDeliverytime:{type:"string",description:"Desired time of delivery. See Date Format. Note: Messages can be scheduled for a maximum of 3 days in the future."},oDeliverytimeOptimizePeriod:{type:"string"},oTimeZoneLocalize:{type:"string"},oTestmode:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Enables sending in test mode. Pass yes if needed. See Sending in Test Mode"},oTracking:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Toggles tracking on a per-message basis, see Tracking Messages for details. Pass yes or no."},oTrackingClicks:{anyOf:[{type:"string",enum:["yes","no","htmlonly"]},{type:"boolean"}],description:"Toggles clicks tracking on a per-message basis. Has higher priority than domain-level setting. Pass yes, no or htmlonly."},oTrackingOpens:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Toggles opens tracking on a per-message basis. Has higher priority than domain-level setting. Pass yes or no."},oRequireTls:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},oSkipVerification:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},recipientVariables:{type:"string"}},required:[],additionalProperties:!0},dg={output:_A};var Yn={type:"object",properties:{name:{type:"string"},email:{type:"string"}},description:'JSON object, containing 2 properties: Name and Email address of a previously validated and active sender. Including the Name property in the JSON is optional. This property is not mandatory in case you use TemplateID and you specified a From address for the template. Format : { "Email":"value", "Name":"value" }.',required:["Email"],additionalProperties:!0},IA={type:"object",properties:{contentType:{type:"string"},filename:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},PA={type:"object",properties:{filename:{type:"string"},contentType:{type:"string"},contentId:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},MA={type:"object",properties:{from:Yn,sender:Yn,to:{type:"array",items:Yn},cc:{type:"array",items:Yn},bcc:{type:"array",items:Yn},replyTo:Yn,subject:{type:"string"},textPart:{type:"string",description:"Content of the message, sent in Text and/or HTML format. At least one of these content types needs to be specified. When the HTML part is the only part provided, Mailjet will not generate a Text-part from the HTML version. The property can't be set when you use TemplateID"},htmlPart:{type:"string",description:"Content of the message, sent in Text and/or HTML format. At least one of these content types needs to be specified. When the HTML part is the only part provided, Mailjet will not generate a Text-part from the HTML version. The property can't be set when you use TemplateID"},templateId:{type:"number",description:"an ID for a template that is previously created and stored in Mailjet's system. It is mandatory when From and TextPart and/or HtmlPart are not provided. "},templateLanguage:{type:"boolean"},templateErrorReporting:Yn,templateErrorDeliver:{type:"boolean"},attachments:{type:"array",items:IA},inlineAttachments:{type:"array",items:PA},priority:{type:"number"},customCampaign:{type:"string"},deduplicateCampaign:{type:"boolean"},trackOpens:{type:"string",enum:["account_default","disabled","enabled"]},trackClicks:{type:"string",enum:["account_default","disabled","enabled"]},customId:{type:"string"},eventPayload:{type:"string"},urlTags:{type:"string"},headers:{type:"object",additionalProperties:!0},variables:{type:"object",additionalProperties:!0}},required:[],additionalProperties:!0},hg={output:MA};var Jt={type:"object",properties:{address:{type:"string"},name:{type:"string"}},additionalProperties:!0},Fo={type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0},NA={type:"object",properties:{from:{anyOf:[{type:"string"},Jt]},sender:{anyOf:[{type:"string"},Jt]},to:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},cc:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},bcc:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},replyTo:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},inReplyTo:{anyOf:[{type:"string"},Jt]},references:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},subject:{type:"string"},text:{anyOf:[{type:"string"},Fo]},html:{anyOf:[{type:"string"},Fo]},watchHtml:{anyOf:[{type:"string"},Fo]},amp:{anyOf:[{type:"string"},{type:"object",properties:{content:{type:"string"},path:{type:"string"},href:{type:"string"},encoding:{type:"string"},contentType:{type:"string"},raw:{anyOf:[{type:"string"},Fo]}}}]},icalEvent:{anyOf:[{type:"string"},{type:"object",properties:{content:{type:"string"},path:{type:"string"},method:{type:"string"},filename:{anyOf:[{type:"string"},{type:"boolean"}]},href:{type:"string"},encoding:{type:"string"}}}]},headers:{anyOf:[{type:"object",additionalProperties:!0},{type:"array",items:{type:"object",additionalProperties:!0}}]},list:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},attachments:{type:"array",items:{type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0}}},required:[],additionalProperties:!0},fg={output:NA};var LA={type:"object",properties:{},required:[],additionalProperties:!1},mg={output:LA};var DA={type:"object",properties:{personalizations:{type:"array",description:"An array of messages and their metadata. Each object within personalizations can be thought of as an envelope - it defines who should receive an individual message and how that message should be handled. See our [Personalizations documentation](https://sendgrid.com/docs/for-developers/sending-email/personalizations/) for examples.",uniqueItems:!1,maxItems:1e3,items:{type:"object",properties:{from:{title:"From Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The 'From' email address used to deliver the message. This address should be a verified sender in your Twilio SendGrid account."},name:{type:"string",description:"A name or title associated with the sending email address."}},required:["email"]},to:{title:"To Email Array",type:"array",items:{type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},cc:{type:"array",description:"An array of recipients who will receive a copy of your email. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name.",maxItems:1e3,items:{title:"CC BCC Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},bcc:{type:"array",description:"An array of recipients who will receive a blind carbon copy of your email. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name.",maxItems:1e3,items:{title:"CC BCC Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},subject:{type:"string",description:"The subject of your email. See character length requirements according to [RFC 2822](http://stackoverflow.com/questions/1592291/what-is-the-email-subject-length-limit#answer-1592310).",minLength:1},headers:{type:"object",description:"A collection of JSON key/value pairs allowing you to specify handling instructions for your email. You may not overwrite the following headers: `x-sg-id`, `x-sg-eid`, `received`, `dkim-signature`, `Content-Type`, `Content-Transfer-Encoding`, `To`, `From`, `Subject`, `Reply-To`, `CC`, `BCC`"},substitutions:{type:"object",description:'Substitutions allow you to insert data without using Dynamic Transactional Templates. This field should **not** be used in combination with a Dynamic Transactional Template, which can be identified by a `templateId` starting with `d-`. This field is a collection of key/value pairs following the pattern "substitutionTag":"value to substitute". The key/value pairs must be strings. These substitutions will apply to the text and html content of the body of your email, in addition to the `subject` and `reply-to` parameters. The total collective size of your substitutions may not exceed 10,000 bytes per personalization object.',maxProperties:1e4},dynamicTemplateData:{type:"object",description:'Dynamic template data is available using Handlebars syntax in Dynamic Transactional Templates. This field should be used in combination with a Dynamic Transactional Template, which can be identified by a `templateId` starting with `d-`. This field is a collection of key/value pairs following the pattern "variable_name":"value to insert".'},customArgs:{type:"object",description:"Values that are specific to this personalization that will be carried along with the email and its activity data. Substitutions will not be made on custom arguments, so any string that is entered into this parameter will be assumed to be the custom argument that you would like to be used. This field may not exceed 10,000 bytes.",maxProperties:1e4},sendAt:{type:"integer",description:"A unix timestamp allowing you to specify when your email should be delivered. Scheduling delivery more than 72 hours in advance is forbidden."}},required:["to"]}},from:{title:"From Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The 'From' email address used to deliver the message. This address should be a verified sender in your Twilio SendGrid account."},name:{type:"string",description:"A name or title associated with the sending email address."}},required:["email"]},replyTo:{title:"Reply_to Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The email address where any replies or bounces will be returned."},name:{type:"string",description:"A name or title associated with the `replyTo` email address."}},required:["email"]},replyToList:{type:"array",description:"An array of recipients who will receive replies and/or bounces. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name. You can either choose to use \u201CreplyTo\u201D field or \u201CreplyToList\u201D but not both.",uniqueItems:!0,maxItems:1e3,items:{type:"object",properties:{email:{type:"string",description:"The email address where any replies or bounces will be returned.",format:"email"},name:{type:"string",description:"A name or title associated with the `replyToList` email address."}},required:["email"]}},subject:{type:"string",description:"The global or 'message level' subject of your email. This may be overridden by subject lines set in personalizations.",minLength:1},content:{type:"array",description:"An array where you can specify the content of your email. You can include multiple [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of content, but you must specify at least one MIME type. To include more than one MIME type, add another object to the array containing the `type` and `value` parameters.",items:{type:"object",properties:{type:{type:"string",description:"The MIME type of the content you are including in your email (e.g., `\u201Ctext/plain\u201D` or `\u201Ctext/html\u201D`).",minLength:1},value:{type:"string",description:"The actual content of the specified MIME type that you are including in your email.",minLength:1}},required:["type","value"]}},attachments:{type:"array",description:"An array of objects where you can specify any attachments you want to include.",items:{type:"object",properties:{content:{type:"string",description:"The Base64 encoded content of the attachment.",minLength:1},type:{type:"string",description:"The MIME type of the content you are attaching (e.g., `\u201Ctext/plain\u201D` or `\u201Ctext/html\u201D`).",minLength:1},filename:{type:"string",description:"The attachment's filename."},disposition:{type:"string",default:"attachment",description:"The attachment's content-disposition, specifying how you would like the attachment to be displayed. For example, `\u201Cinline\u201D` results in the attached file are displayed automatically within the message while `\u201Cattachment\u201D` results in the attached file require some action to be taken before it is displayed, such as opening or downloading the file.",enum:["inline","attachment"]},contentId:{type:"string",description:"The attachment's content ID. This is used when the disposition is set to `\u201Cinline\u201D` and the attachment is an image, allowing the file to be displayed within the body of your email."}},required:["content","filename"]}},templateId:{type:"string",description:"An email template ID. A template that contains a subject and content \u2014 either text or html \u2014 will override any subject and content values specified at the personalizations or message level."},headers:{description:"An object containing key/value pairs of header names and the value to substitute for them. The key/value pairs must be strings. You must ensure these are properly encoded if they contain unicode characters. These headers cannot be one of the reserved headers.",type:"object"},categories:{type:"array",description:"An array of category names for this message. Each category name may not exceed 255 characters. ",uniqueItems:!0,maxItems:10,items:{type:"string",maxLength:255}},customArgs:{description:"Values that are specific to the entire send that will be carried along with the email and its activity data. Key/value pairs must be strings. Substitutions will not be made on custom arguments, so any string that is entered into this parameter will be assumed to be the custom argument that you would like to be used. This parameter is overridden by `customArgs` set at the personalizations level. Total `customArgs` size may not exceed 10,000 bytes.",type:"string"},sendAt:{type:"integer",description:"A unix timestamp allowing you to specify when you want your email to be delivered. This may be overridden by the `sendAt` parameter set at the personalizations level. Delivery cannot be scheduled more than 72 hours in advance. If you have the flexibility, it's better to schedule mail for off-peak times. Most emails are scheduled and sent at the top of the hour or half hour. Scheduling email to avoid peak times \u2014 for example, scheduling at 10:53 \u2014 can result in lower deferral rates due to the reduced traffic during off-peak times."},batchId:{type:"string",description:"An ID representing a batch of emails to be sent at the same time. Including a `batchId` in your request allows you include this email in that batch. It also enables you to cancel or pause the delivery of that batch. For more information, see the [Cancel Scheduled Sends API](https://sendgrid.com/docs/api-reference/)."},asm:{type:"object",description:"An object allowing you to specify how to handle unsubscribes.",properties:{groupId:{type:"integer",description:"The unsubscribe group to associate with this email."},groupsToDisplay:{type:"array",description:"An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page.",maxItems:25,items:{type:"integer"}}},required:["groupId"]},ipPoolName:{type:"string",description:"The IP Pool that you would like to send this email from.",minLength:2,maxLength:64},mailSettings:{type:"object",description:"A collection of different mail settings that you can use to specify how you would like this email to be handled.",properties:{bypassListManagement:{type:"object",description:"Allows you to bypass all unsubscribe groups and suppressions to ensure that the email is delivered to every single recipient. This should only be used in emergencies when it is absolutely necessary that every recipient receives your email. This filter cannot be combined with any other bypass filters. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassSpamManagement:{type:"object",description:"Allows you to bypass the spam report list to ensure that the email is delivered to recipients. Bounce and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassBounceManagement:{type:"object",description:"Allows you to bypass the bounce list to ensure that the email is delivered to recipients. Spam report and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassUnsubscribeManagement:{type:"object",description:"Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients. Bounce and spam report lists will still be checked; addresses on these other lists will not receive the message. This filter applies only to global unsubscribes and will not bypass group unsubscribes. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},footer:{type:"object",description:"The default footer that you would like included on every email.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},text:{type:"string",description:"The plain text content of your footer."},html:{type:"string",description:"The HTML content of your footer."}}},sandboxMode:{type:"object",description:"Sandbox Mode allows you to send a test email to ensure that your request body is valid and formatted correctly.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}}}},trackingSettings:{type:"object",description:"Settings to determine how you would like to track the metrics of how your recipients interact with your email.",properties:{clickTracking:{type:"object",description:"Allows you to track if a recipient clicked a link in your email.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},enableText:{type:"boolean",description:"Indicates if this setting should be included in the `text/plain` portion of your email."}}},openTracking:{type:"object",description:"Allows you to track if the email was opened by including a single pixel image in the body of the content. When the pixel is loaded, Twilio SendGrid can log that the email was opened.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},substitutionTag:{type:"string",description:"Allows you to specify a substitution tag that you can insert in the body of your email at a location that you desire. This tag will be replaced by the open tracking pixel."}}},subscriptionTracking:{type:"object",description:"Allows you to insert a subscription management link at the bottom of the text and HTML bodies of your email. If you would like to specify the location of the link within your email, you may use the `substitutionTag`.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},text:{type:"string",description:"Text to be appended to the email with the subscription tracking link. You may control where the link is by using the tag <% %>"},html:{type:"string",description:"HTML to be appended to the email with the subscription tracking link. You may control where the link is by using the tag <% %>"},substitutionTag:{type:"string",description:"A tag that will be replaced with the unsubscribe URL. for example: `[unsubscribe_url]`. If this parameter is used, it will override both the `text` and `html` parameters. The URL of the link will be placed at the substitution tag\u2019s location with no additional formatting."}}},ganalytics:{type:"object",description:"Allows you to enable tracking provided by Google Analytics.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},utmSource:{type:"string",description:"Name of the referrer source. (e.g. Google, SomeDomain.com, or Marketing Email)"},utmMedium:{type:"string",description:"Name of the marketing medium. (e.g. Email)"},utmTerm:{type:"string",description:"Used to identify any paid keywords."},utmContent:{type:"string",description:"Used to differentiate your campaign from advertisements."},utmCampaign:{type:"string",description:"The name of the campaign."}}}}}},required:[],additionalProperties:!1},gg={output:DA};var yg={anypost:ae,braze:ae,clickatell:ae,nodemailer:fg,emailjs:ae,"email-webhook":ae,"infobip-email":ae,mailersend:ae,mailgun:dg,mailjet:hg,mailtrap:ae,mandrill:ae,netcore:ae,"novu-email":mg,outlook365:ae,plunk:ae,postmark:ae,resend:ae,sendgrid:gg,sendinblue:ae,ses:ae,sparkpost:ae};var FA={type:"object",properties:{},required:[],additionalProperties:!1},bg={output:FA};var wg={novu:bg};var Sg={anyOf:[{type:"string"},{type:"object",additionalProperties:!0,properties:{name:{type:"string"},volume:{type:"number"},critical:{type:"number"}},required:["name","volume","critical"]}]},UA={type:"object",properties:{topic:{type:"string",description:"The destination topic for the notification."},id:{type:"string",description:"A UUID to identify the notification with APNS. If an id is not supplied, APNS will generate one automatically. If an error occurs the response will contain the id. This property populates the apns-id header."},expiry:{type:"number",description:"A UNIX timestamp when the notification should expire. If the notification cannot be delivered to the device, APNS will retry until it expires. An expiry of 0 indicates that the notification expires immediately, therefore no retries will be attempted."},priority:{type:"number",description:`Provide one of the following values:
162
+ `)}async executeProviders(t,n,r,i){return n.providers.reduce(async(a,o)=>{let s=await a,l=await this.runProvider(t,n,o,r,i);return{...s,[o.type]:l}},Promise.resolve({}))}async runProvider(t,n,r,i,a){let o=t.action==="preview";if(t.stepId!==n.stepId)return o?(this.log(` ${lt.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)):(this.log(` ${lt.HYDRATED} Hydrated provider: \`${r.type}\``),{});try{return await this.resolveProviderOutput(t,n,r,a,i)}catch(s){if(this.log(` ${lt.ERROR} Failed to execute provider: \`${r.type}\``),o)return this.log(` ${lt.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema);throw new ra(r.type,t.action,s)}}async resolveProviderOutput(t,n,r,i,a){let o=await r.resolve({controls:i,outputs:a}),s=await this.validate(o,r.outputs.unknownSchema,"step","output",t.workflowId,n.stepId,r.type);return this.log(` ${lt.SUCCESS} Executed provider: \`${r.type}\``),{...s,_passthrough:o._passthrough}}async executeStep(t,n){if(t.stepId===n.stepId)try{let r=await this.createStepControls(n,t),i=await this.compileControls(r,t),a=await n.resolve(i),o=await this.normalizeChatCardOutput(n,a),s=await this.validate(o,n.outputs.unknownSchema,"step","output",t.workflowId,n.stepId),l=await this.executeProviders(t,n,s,i);return this.log(` ${lt.SUCCESS} Executed stepId: \`${n.stepId}\``),{outputs:s,providers:l}}catch(r){throw this.log(` ${lt.ERROR} Failed to execute stepId: \`${n.stepId}\``),Mn(r)?r:new Pr(n.stepId,t.action,r)}else try{let r=this.getStepState(t,n.stepId);if(r){let i=await this.validate(r.outputs,n.results.unknownSchema,"step","result",t.workflowId,n.stepId);return this.log(` ${lt.HYDRATED} Hydrated stepId: \`${n.stepId}\``),{outputs:i,providers:await this.executeProviders(t,n,i,{})}}else throw new zi(t.workflowId,n.stepId)}catch(r){throw this.log(` ${lt.ERROR} Failed to hydrate stepId: \`${n.stepId}\``),r}}async normalizeChatCardOutput(t,n){if(t.type!=="chat"||(n==null?void 0:n.card)==null)return n;let r=await co(n.card);return r?{...n,card:r}:n}async compileControls(t,n){var r;try{let i=xi(t),a=this.preprocessTranslationPatterns(JSON.stringify(i));a=this.preprocessFilterTranslationArgs(a);let o=this.templateEngine.parse(a),s=this.getWorkflow(n.workflowId),l={workflow:{workflowId:s.workflowId,name:s.name,description:s.description,tags:s.tags,severity:s.severity},payload:n.payload,subscriber:n.subscriber,...n.actor&&{actor:n.actor},context:n.context,steps:Wx(n.state),env:(r=n.env)!=null?r:{}},p=await this.templateEngine.render(o,l),d=this.postprocessTranslationMarkers(p),h=(0,jm.jsonrepair)(d),y=JSON.parse(h),g=Ai(y);return Fm(g)}catch(i){throw new Gi(n.workflowId,n.stepId,i)}}preprocessTranslationPatterns(t){return t.replace(/\{\{\s*t\.([\p{L}\p{N}_.-]+)\s*\}\}/gu,"[T:$1]")}preprocessFilterTranslationArgs(t){return t.replace(/'t\.([\p{L}\p{N}_.-]+)'/gu,"'[T:$1]'")}postprocessTranslationMarkers(t){return t.replace(/\[T:([\p{L}\p{N}_.-]+)\]/gu,"{{t.$1}}")}async createStepControls(t,n){return await this.validate(n.controls,t.controls.unknownSchema,"step","controls",n.workflowId,t.stepId)}async previewStep(t,n){try{return await this.constructStepForPreview(t,n)}catch(r){throw this.log(` ${lt.ERROR} Failed to preview stepId: \`${n.stepId}\``),Mn(r)?r:new Pr(n.stepId,t.action,r)}}async constructStepForPreview(t,n){return t.stepId===n.stepId?await this.previewRequiredStep(n,t):await this.extractMockDataForPreviousSteps(t,n)}async extractMockDataForPreviousSteps(t,n){let r={},i=this.getStepState(t,n.stepId),a=this.mock(n.results.schema);return{outputs:pc(a,(i==null?void 0:i.outputs)||{}),providers:await this.executeProviders(t,n,r,{})}}async previewRequiredStep(t,n){let r=await this.createStepControls(t,n),i=await this.compileControls(r,n),a=await t.resolve(i),o=await this.normalizeChatCardOutput(t,a),s=await this.validate(o,t.outputs.unknownSchema,"step","output",n.workflowId,t.stepId);return this.log(` ${lt.MOCK} Mocked stepId: \`${t.stepId}\``),{outputs:s,providers:await this.executeProviders(n,t,s,i)}}getStepState(t,n){return t.state.find(r=>r.stepId===n)}getStepCode(t,n){return{code:this.getStep(t,n).resolve.toString()}}getWorkflowCode(t){return{code:this.getWorkflow(t).execute.toString()}}getCode(t,n){let r;if(t)n?r=this.getStepCode(t,n):r=this.getWorkflowCode(t);else throw new Mr(t);return r}};function Wx(e){let t={};for(let n of e)t[n.stepId]=n.outputs;return t}var Bm=Symbol.for("novu.agent.runtimeContext");var hc=(o=>(o.ON_MESSAGE="onMessage",o.ON_MESSAGE_UPDATED="onMessageUpdated",o.ON_MESSAGE_DELETED="onMessageDeleted",o.ON_ACTION="onAction",o.ON_RESOLVE="onResolve",o.ON_REACTION="onReaction",o))(hc||{});function fc(e){return typeof e=="object"&&e!==null&&"content"in e&&!("type"in e)}var hr=class{constructor(){this.__novuPendingApproval=!0}};function zm(e){return typeof e=="object"&&e!==null&&"suppress"in e&&e.suppress===!0}var Yx=5*1024*1024,Jx=5*1024*1024,Vm=32768,Gx=/^[A-Za-z0-9+/]*={0,2}$/;function Ei(e,t){return e.filename?`"${e.filename}"`:`at index ${t}`}function Wm(){return globalThis.Buffer}function Kx(e){var t,n,r;return(r=(n=(t=Wm())==null?void 0:t.isBuffer)==null?void 0:n.call(t,e))!=null?r:!1}function Xx(e){return typeof Blob!="undefined"&&e instanceof Blob}function mc(e){let t=Wm();if(t)return t.from(e).toString("base64");if(typeof btoa!="function")throw new Error("Unable to encode file data: base64 encoding is not available in this runtime.");let n="";for(let r=0;r<e.length;r+=Vm){let i=e.subarray(r,r+Vm);n+=String.fromCharCode(...i)}return btoa(n)}function Ym(e){let t=e.replace(/\s/g,""),n=t.length%4;if(!t||n===1||!Gx.test(t))return null;let r=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-r}function ki(e,t,n){if(e>Yx)throw new Error(`Invalid file ${Ei(t,n)}: inline data must be 5 MB or smaller. Use a publicly-accessible URL for larger files.`)}async function Qx(e,t,n){if(typeof e=="string"){let r=Ym(e);if(r===null)throw new Error(`Invalid file ${Ei(t,n)}: data must be a base64-encoded string.`);return ki(r,t,n),e}if(Kx(e))return ki(e.byteLength,t,n),e.toString("base64");if(e instanceof Uint8Array)return ki(e.byteLength,t,n),mc(e);if(e instanceof ArrayBuffer)return ki(e.byteLength,t,n),mc(new Uint8Array(e));if(Xx(e))return ki(e.size,t,n),mc(new Uint8Array(await e.arrayBuffer()));throw new Error(`Invalid file ${Ei(t,n)}: data must be a base64 string, Buffer, Uint8Array, ArrayBuffer, or Blob.`)}async function Zx(e){if(!(e!=null&&e.length))return;let t=[],n=0;for(let[r,i]of e.entries()){let a=i.data,o=i.url,s=a!=null,l=o!=null;if(s===l)throw new Error(`Invalid file ${Ei(i,r)}: provide exactly one of data or url.`);if(s){let p=await Qx(a,i,r),d=Ym(p);if(n+=d!=null?d:0,n>Jx)throw new Error("Invalid files: total inline data must be 5 MB or smaller. Use publicly-accessible URLs for larger files.");t.push({...i,data:p});continue}if(l&&typeof o!="string")throw new Error(`Invalid file ${Ei(i,r)}: url must be a string.`);t.push(i)}return t}async function xo(e,t){let n=await Zx(t);if(typeof e=="string")return n?{markdown:e,files:n}:{markdown:e};let r=await co(e);if(r)return n?{card:r,files:n}:{card:r};throw new Error("Invalid message content \u2014 expected string or CardElement")}var Jm=1;var eA={400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",408:"Request Timeout",409:"Conflict",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"};function Ao(e){return typeof e=="string"&&e.trim()?e:!e||typeof e!="object"?null:Ao(e.message)}function tA(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,r=Ao(n.message);if(r)return r;let i=Ao(n.error);if(i)return i;let a=n.errors;return Array.isArray(a)?Ao(a[0]):null}function nA(e,t){var i;let n=(i=eA[e])!=null?i:e,r=tA(t);return r?`Delivery failed: ${n}: ${r}`:`Delivery failed: ${n}`}var bn=class extends Error{constructor(t,n){super(t),this.name="AgentError",this.cause=n==null?void 0:n.cause,this.delivery=n==null?void 0:n.delivery}},an=class extends bn{constructor(t,n){let r={statusCode:t,responseBody:n};super(nA(t,n),{delivery:r}),this.name="AgentDeliveryError",this.statusCode=t,this.responseBody=n}};function Ri(e){return e instanceof bn?e:e instanceof Error?new bn(e.message,{cause:e}):new bn("Turn failed",{cause:e})}function rA(e){return new Promise(t=>{setTimeout(t,e)})}function iA(e){return e>=500||e===408||e===429}var vo=class{constructor(t){this.sequence=0;this.buffer=[];this.chain=Promise.resolve();var n,r;this.runId=`run_${crypto.randomUUID()}`,this.eventsUrl=t.eventsUrl,this.secretKey=t.secretKey,this.conversationId=t.conversationId,this.agentId=t.agentId,this.turnId=t.turnId,this.fetchFn=(n=t.fetchFn)!=null?n:fetch,this.maxRetries=(r=t.maxRetries)!=null?r:3}enqueue(t){this.sequence+=1,this.buffer.push({version:Jm,conversationId:this.conversationId,agentId:this.agentId,runId:this.runId,turnId:this.turnId,sequence:this.sequence,timestamp:new Date().toISOString(),event:t})}flush(){if(this.buffer.length===0)return this.chain;let t=this.buffer;return this.buffer=[],this.chain=this.chain.then(()=>this.postBatchWithRetry(t)),this.chain}async emit(t){this.enqueue(t),await this.flush()}async postBatchWithRetry(t){let n;for(let r=1;r<=this.maxRetries;r+=1)try{await this.postBatch(t);return}catch(i){if(n=i,!aA(i))throw i;r<this.maxRetries&&await rA(250*r)}throw n}async postBatch(t){let n;try{n=await this.fetchFn(this.eventsUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this.secretKey}`},body:JSON.stringify({events:t})})}catch(i){throw oA(i)}let r=await n.text().catch(()=>"");if(!n.ok)throw new an(n.status,r)}};function aA(e){return!(e instanceof an)||e.statusCode===0?!0:iA(e.statusCode)}function oA(e){if(e instanceof an)return e;let t=e instanceof Error?e.message:"Network request failed";return new an(0,t)}var gc="human:";function ko(e){return`${gc}${e}:approve`}function Eo(e){return`${gc}${e}:deny`}function fr(e,t){return`${gc}${e}:opt:${t}`}function Gm(e){return typeof e=="string"?e:e.label}function sA(e){return typeof e=="string"?void 0:e.id}function lA(e){return typeof e=="string"?e:e.id}function Co(e,t){let n=t==null?void 0:t.trim();if(!n)throw new Error(`ctx.${e} requires a title (string argument or card.title)`);return n}function cA(e){if(!("title"in e))return;let t=e.title;return typeof t=="string"&&t.trim()?t.trim():void 0}function Oo(e){if(!e||e.length<2||e.length>10)throw new Error("ctx.choose requires between 2 and 10 options");if(e.some(t=>Gm(t).trim().length===0))throw new Error("ctx.choose options must be non-empty strings")}function _o(e){if(e.length>4)throw new Error("ctx.approve card.extraActions supports at most 4 buttons");for(let t of e){let n=sA(t);if(!Gm(t).trim())throw new Error("ctx.approve extraActions labels must be non-empty");if(n==="approve"||n==="deny")throw new Error("ctx.approve extraActions ids cannot be approve or deny")}}function uA(e){if(typeof e=="string")throw new Error("human render must return chrome (*Card()), a Card, or a chat element \u2014 not a markdown string")}function Ro(e,t=[]){if(Array.isArray(e)){for(let r of e)Ro(r,t);return t}if(!e||typeof e!="object")return t;let n=e;n.type==="button"&&typeof n.id=="string"&&n.id.trim()&&t.push({id:n.id,label:typeof n.label=="string"?n.label:""});for(let r of Object.values(n))r&&typeof r=="object"&&Ro(r,t);return t}function pA(e){return new Set(Ro(e).map(t=>t.id))}function dA(e,t){let n=fr(t,"");return e.startsWith(n)&&e.length>n.length?e.slice(n.length):e}function hA(e,t){let n=Ro(e),r=new Set(n.map(s=>s.id)),i=ko(t),a=Eo(t);if(!r.has(i))throw new Error("ctx.approve render must include a button with actionIds.approve");if(!r.has(a))throw new Error("ctx.approve render must include a button with actionIds.deny");let o=n.filter(s=>s.id!==i&&s.id!==a).map(s=>({id:dA(s.id,t),label:s.label}));o.length&&_o(o)}function fA(e,t,n){if(n){Oo(n);for(let i of n){let a=lA(i);if(!e.has(fr(t,a)))throw new Error(`ctx.choose render must include a button with actionIds.option('${a}')`)}return}let r=mA(e,t);if(r.length<2||r.length>10)throw new Error("ctx.choose render must include between 2 and 10 option action buttons")}function mA(e,t){let n=fr(t,"");return[...e].filter(r=>r.startsWith(n)&&r.length>n.length).map(r=>r.slice(n.length))}function Km(e,t,n){var r;switch(Co(e,t.title),e){case"ask":case"tell":return;case"approve":t.type==="human-approve-card"&&t.extraActions&&_o(t.extraActions);return;case"choose":Oo(t.type==="human-choose-card"&&(r=t.options)!=null?r:n);return;default:return}}function Xm(e,t,n,r){switch(uA(t),Co(e,cA(t)),e){case"ask":case"tell":return;case"approve":hA(t,n);return;case"choose":fA(pA(t),n,r);return;default:return}}function Io(e){let t=typeof e=="string"?[e]:e,n=[],r=new Set;for(let i of t){if(typeof i!="string")throw new Error("`to` must be a subscriberId string or an array of subscriberIds");let a=i.trim();!a||r.has(a)||(r.add(a),n.push(a))}if(n.length===0)throw new Error("`to` must include at least one subscriberId");if(n.length>50)throw new Error("`to` supports at most 50 subscriberIds");return n}var Qm="tool-approval";function gA(e){return e==="approve"||e==="deny"}function yc(e,t){return`${Qm}:${e}:${t}`}function Zm(e){let[t,n,...r]=(e!=null?e:"").split(":"),i=r.join(":");return t!==Qm||!gA(n)||!i?null:{approved:n==="approve",approvalId:i}}async function eg(e,t,n,r,i){var d,h;let a=r!=null?r:t.id,o={approve:yc("approve",a),deny:yc("deny",a)},s=y=>({type:"tool-approval-card",...y}),l=(h=(d=n==null?void 0:n.renderApproval)==null?void 0:d.call(n,{toolCall:t,actionIds:o,approvalCard:s}))!=null?h:s(),p={approvalId:a,toolCallId:t.id,name:t.name,input:t.input,...(i==null?void 0:i.to)!==void 0?{to:i.to}:{},...i!=null&&i.from?{from:i.from}:{},...(i==null?void 0:i.ttlSeconds)!==void 0?{ttlSeconds:i.ttlSeconds}:{}};if(e.emitToolApprovalRequest(p),hm(l)){await e.replyApprovalCard(l);return}await e.reply(l)}function Po(e){return t=>({type:e,...t})}function Mo(e,t){switch(e){case"ask":return{requestId:t,askCard:Po("human-ask-card")};case"approve":return{requestId:t,actionIds:{approve:ko(t),deny:Eo(t)},approveCard:Po("human-approve-card")};case"choose":return{requestId:t,actionIds:{option:n=>fr(t,n)},chooseCard:Po("human-choose-card")};case"tell":return{requestId:t,tellCard:Po("human-tell-card")};default:return e}}function Sc(e){return`${e}_${crypto.randomUUID()}`}function yA(e){let{type:t,...n}=e;return n}function bA(e){if(!(!e||!("card"in e)))return e.card}function No(e){if(!(!e||!("render"in e)))return e.render}function wA(e){return typeof e=="object"&&e!==null&&pr(e)?e:{type:"card",children:[e]}}function bc(e){if(!(!e||!("ttlSeconds"in e)||typeof e.ttlSeconds!="number"))return e.ttlSeconds}function tg(e){if(e.markdown!==void 0)return{markdown:e.markdown};if(e.card!==void 0)return{card:e.card};throw new Error("Invalid reply content \u2014 expected markdown or card")}function SA(e){let t="platformMessageId"in e?e.platformMessageId.trim():e.messageId.trim();if(!t)throw new Error("quoteReply requires a non-empty platform message id");return{messageId:t}}function ng(e){if(e!=null&&e.length)return e.map((t,n)=>({fileId:t.filename||`file_${n}`,name:t.filename,mediaType:t.mimeType,...t.data!==void 0?{data:typeof t.data=="string"?t.data:void 0}:{},...t.url!==void 0?{url:t.url}:{}}))}function wc(e,t){var r;let n=[];if(e.toolApprovalRequest){let i=e.toolApprovalRequest;n.push({type:"tool-approval-request",approvalId:i.approvalId,toolUseId:i.toolCallId,toolName:i.name,input:i.input,...i.ttlSeconds!==void 0?{ttlSeconds:i.ttlSeconds}:{},...i.to!==void 0?{to:i.to}:{},...i.from!==void 0?{from:i.from}:{},...t!=null&&t.deliverApprovalCard?{deliverCard:!0}:{}})}for(let i of e.toolResults)n.push({type:"tool-use-result",toolUseId:i.toolCallId,content:[{type:"text",text:String((r=i.preview)!=null?r:"")},{type:"json",value:i.output}]});for(let i of e.signals)n.push({type:"signal",signal:i});for(let i of e.addReactions)n.push({type:"channel.reaction",messageId:i.messageId,emoji:i.emojiName,op:"add"});for(let i of e.deleteMessages)n.push({type:"channel.delete",messageId:i.messageId});return e.resolve&&n.push({type:"resolve",summary:e.resolve.summary}),n}var Tc=class{constructor(t){this.outbox=t}async sendReply(t,n,r){let i=Sc("msg"),a=wc(n);return a.push({type:"message",role:"assistant",messageId:i,content:tg(t),files:ng(t.files),...r?{quoteReply:r}:{}}),await this._emitAndFlush(a),{messageId:i,platformThreadId:""}}async sendApprovalCard(t,n){return await this._emitAndFlush(wc(n,{deliverApprovalCard:!0})),"unaddressable"}async editMessage(t,n){return await this.outbox.emit({type:"channel.edit",messageId:t,content:tg(n),files:ng(n.files)}),{messageId:t,platformThreadId:""}}async deleteMessage(t){await this.outbox.emit({type:"channel.delete",messageId:t})}async setTyping(t){if(t==="stop"){await this.outbox.emit({type:"channel.typing",state:"off"});return}let n=typeof t=="object"&&"status"in t?t.status:void 0;await this.outbox.emit({type:"channel.typing",state:"on",status:n})}async flushSideEffects(t){await this._emitAndFlush(wc(t))}async emitCustom(t,n){await this.outbox.emit({type:"custom",name:t,data:n})}queueRunStart(){this.outbox.enqueue({type:"run-start"})}async emitRunFinish(t){await this.outbox.emit({type:"run-finish",outcome:t})}async reportTurnError(t){await this.outbox.emit({type:"run-error",message:t!=null?t:"agent handler failed"})}async _emitAndFlush(t){if(t.length!==0){for(let n of t)this.outbox.enqueue(n);await this.outbox.flush()}}},Lo=class{constructor(t,n,r){this.transport=r;this.editedByHandler=!1;this.messageId=t,this.platformThreadId=n}async edit(t,n){this.editedByHandler=!0;let r=await xo(t,n==null?void 0:n.files),i=await this.transport.editMessage(this.messageId,r);if(!i)throw new Error("Agent edit did not return a message handle");return this.messageId=i.messageId,this.platformThreadId=i.platformThreadId,this}async delete(){await this.transport.deleteMessage(this.messageId)}},xc=class{constructor(){this.messageId="";this.platformThreadId=""}async edit(){return this}async delete(){}},rg;rg=Bm;var Do=class{constructor(t,n,r){this[rg]=!0;this._signals=[];this._toolResults=[];this._pendingToolApprovalRequest=null;this._pendingReactions=[];this._pendingDeletes=[];this._resolveSignal=null;this._pendingHumanRenders=[];var l,p,d,h,y,g;this.event=t.event,this.action=(l=t.action)!=null?l:null,this.message=t.message,this.previousMessage=(p=t.previousMessage)!=null?p:null,this.reaction=t.reaction,this.conversation=t.conversation,this.subscriber=t.subscriber,this.context=(d=t.context)!=null?d:null,this.notification=(h=t.notification)!=null?h:null,this.history=t.history,this.platform=t.platform,this.platformContext=t.platformContext,this.humanResponse=(y=t.humanResponse)!=null?y:null,this._toolApprovalConfig=r;let i=t.eventsUrl;if(!i)throw new Error("AgentBridgeRequest.eventsUrl is required");this._transport=new Tc(new vo({eventsUrl:i,secretKey:n,conversationId:t.conversationId,agentId:t.agentId,turnId:t.deliveryId})),this._metadataState={...(g=t.conversation.metadata)!=null?g:{}};let a=this;this.metadata={get(I){return a._metadataState[I]},set(I,K){a._metadataState[I]=K,a._signals.push({type:"metadata",action:"set",key:I,value:K})},delete(I){delete a._metadataState[I],a._signals.push({type:"metadata",action:"delete",key:I})},clear(){a._metadataState={},a._signals.push({type:"metadata",action:"clear"})},get current(){return{...a._metadataState}}};let o=I=>this._transport.setTyping(I),s=(I=>o(I===void 0?{}:{status:I}));s.stop=()=>o("stop"),this.typing=s,this.toolApproval={request:async(I,K)=>(await eg(this,I,this._toolApprovalConfig,void 0,K),new hr)}}asMessageContext(){return this}async reply(t,n){await this.materializePendingHumanRenders();let r=await xo(t,n==null?void 0:n.files),i=this._drainSideEffectsSnapshot(),a=n!=null&&n.quoteReply?SA(n.quoteReply):void 0,o=await this._transport.sendReply(r,i,a);if(!o)throw new Error("Agent reply did not return a message handle");return new Lo(o.messageId,o.platformThreadId,this._transport)}async replyApprovalCard(t){await this.materializePendingHumanRenders();let n=this._drainSideEffectsSnapshot();return await this._transport.sendApprovalCard(t,n),new xc}createReplyHandle(t){return new Lo(t,"",this._transport)}async emit(t){await this._transport.emitCustom(t.name,t.data)}resolve(t){this._resolveSignal={summary:t}}trigger(t,n){this._signals.push({...n,type:"trigger",workflowId:t})}ask(t,n){let i=typeof t!="string"?t:n,a=No(i);return a?this.queueRendered("ask",i,a):this.queueHumanSignal("ask",t,n)}approve(t,n){let i=typeof t!="string"?t:n,a=No(i);return a?this.queueRendered("approve",i,a):this.queueHumanSignal("approve",t,n)}choose(t,n,r){var l;let i=typeof t!="string",a,o;i?a=t:Array.isArray(n)?(a=r,o=n):a=n;let s=No(a);return s?this.queueRendered("choose",a,s):i?this.queueHumanSignal("choose",t,void 0,"card"in t?(l=t.card)==null?void 0:l.options:void 0):this.queueHumanSignal("choose",t,a,o)}tell(t,n){let r=typeof t!="string",i=r?t:n,a=No(i);if(a)return this.queueRendered("tell",i,a);if(r)throw new Error("ctx.tell requires a title (string argument) when render is omitted");return this.queueHumanSignal("tell",t,n)}queueHumanSignal(t,n,r,i){let a=typeof n!="string",o=a?void 0:n,s=a?n:r,l=bA(s),p=Co(t,(o==null?void 0:o.trim())||(l==null?void 0:l.title));if(t==="choose"){let I=i!=null?i:l==null?void 0:l.options;Oo(I)}t==="approve"&&(l!=null&&l.extraActions)&&_o(l.extraActions);let d=Sc("hr"),h=(s==null?void 0:s.to)!==void 0?Io(s.to):void 0,y={...l,title:p,...t==="choose"&&i?{options:i}:{}},g=bc(s);return this._signals.push({type:"human",kind:t,requestId:d,card:y,...s!=null&&s.from?{from:s.from}:{},...g!==void 0?{ttlSeconds:g}:{},...h!==void 0?{to:h}:{}}),d}queueRendered(t,n,r){let i=Sc("hr");return this._pendingHumanRenders.push(async()=>{let a=await this.invokeHumanRender(t,i,r);if(fm(a)){this.pushRenderedChrome(t,i,a,n);return}await this.pushRenderedContent(t,i,a,n)}),i}invokeHumanRender(t,n,r){switch(t){case"ask":return Promise.resolve(r(Mo("ask",n)));case"approve":return Promise.resolve(r(Mo("approve",n)));case"choose":return Promise.resolve(r(Mo("choose",n)));case"tell":return Promise.resolve(r(Mo("tell",n)));default:{let i=t;return Promise.resolve(i)}}}pushRenderedChrome(t,n,r,i){Km(t,r);let a=yA(r),o=bc(i),s=(i==null?void 0:i.to)!==void 0?Io(i.to):void 0,l=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...l?{actionIdentifier:n}:{},card:a,...i!=null&&i.from?{from:i.from}:{},...o!==void 0?{ttlSeconds:o}:{},...s!==void 0?{to:s}:{}})}async pushRenderedContent(t,n,r,i){Xm(t,r,n);let a=await xo(wA(r));if(!a.card)throw new Error("human render must return chrome (*Card()), a Card, or a chat element \u2014 not a markdown string");let o=bc(i),s=(i==null?void 0:i.to)!==void 0?Io(i.to):void 0,l=t==="approve"||t==="choose";this._signals.push({type:"human",kind:t,requestId:n,...l?{actionIdentifier:n}:{},card:a.card,...i!=null&&i.from?{from:i.from}:{},...o!==void 0?{ttlSeconds:o}:{},...s!==void 0?{to:s}:{}})}emitToolApprovalRequest(t){if(this._pendingToolApprovalRequest)throw new Error("Only one tool approval request can be queued before the next reply");this._pendingToolApprovalRequest=t}emitToolResult(t){this._toolResults.push(t)}addReaction(t,n){this._pendingReactions.push({messageId:t,emojiName:n})}deleteMessage(t){this._pendingDeletes.push({messageId:t})}queueRunStart(){this._transport.queueRunStart()}async emitRunFinish(t){try{await this._transport.emitRunFinish(t.outcome)}catch(n){console.error("[agent] Failed to emit run finish:",n)}}async reportTurnError(t){try{await this._transport.reportTurnError(t)}catch(n){console.error("[agent] Failed to report turn error:",n)}}async flush(){if(await this.materializePendingHumanRenders(),!this._hasPendingSideEffects())return;let t=this._drainSideEffectsSnapshot();await this._transport.flushSideEffects(t)}async materializePendingHumanRenders(){let t=this._pendingHumanRenders.splice(0);for(let n of t)await n()}_hasPendingSideEffects(){return!!(this._pendingToolApprovalRequest||this._signals.length||this._toolResults.length||this._resolveSignal||this._pendingReactions.length||this._pendingDeletes.length)}_drainSideEffectsSnapshot(){let t={toolApprovalRequest:this._pendingToolApprovalRequest,signals:this._signals,toolResults:this._toolResults,addReactions:this._pendingReactions,deleteMessages:this._pendingDeletes,resolve:this._resolveSignal};return this._pendingToolApprovalRequest=null,this._signals=[],this._toolResults=[],this._pendingReactions=[],this._pendingDeletes=[],this._resolveSignal=null,t}};function TA(e){return!!(typeof e=="string"||typeof e=="object"&&e!==null&&pr(e)||typeof e=="object"&&e!==null&&("markdown"in e||"card"in e||"files"in e))}function xA(e,t){return e}var ig="tool_approval:";function AA(e){if(!(e!=null&&e.startsWith(ig)))return null;let t=e.slice(ig.length);return t.length>0?t:null}async function ag(e,t){await e.reply(t.content,{files:t.files,quoteReply:t.quoteReply})}async function Wn(e,t){if(!(t instanceof hr||t===void 0)){if(fc(t)){await ag(e,t);return}await e.reply(t)}}async function vA(e,t){return zm(t)?!0:fc(t)?(await ag(e,t),!0):TA(t)?(await e.reply(t),!0):!1}function kA(e,t){var n;for(let r of e){let i=r.toolData;if(r.type==="tool_approval_request"&&(i==null?void 0:i.approvalId)===t&&i.toolCallId)return{approvalId:i.approvalId,toolCallId:i.toolCallId,name:(n=i.toolName)!=null?n:"tool",input:i.input}}}async function og(e){var a;let t=new Do(e.bridge,e.secretKey,e.agent.handlers.toolApproval),{agent:n,event:r,logger:i}=e;try{t.queueRunStart(),await RA(n,r,t),await t.flush(),await t.emitRunFinish({outcome:"completed"})}catch(o){let s=Ri(o);i==null||i.error(`[agent:${n.id}] Turn failed (${r}): ${s.message}`,(a=s.cause)!=null?a:s);let l=!1;if(n.handlers.onError)try{let p=await n.handlers.onError(s,xA(t,r));l=await vA(t,p)}catch(p){i==null||i.error(`[agent:${n.id}] onError failed:`,p)}l?await t.emitRunFinish({outcome:"completed"}):await t.reportTurnError(s.message)}finally{try{await t.typing.stop(),await t.flush()}catch{}}}async function EA(e,t){var s,l,p,d,h,y;let n=AA((s=t.humanResponse)==null?void 0:s.requestId),r=Zm((l=t.action)==null?void 0:l.id),i=n!=null?n:r==null?void 0:r.approvalId,a=n?((p=t.humanResponse)==null?void 0:p.status)==="approved"&&!t.humanResponse.expired:r==null?void 0:r.approved;if(i&&a!==void 0&&e.handlers.onToolApproval){let g=kA(t.history,i),I=g?{id:g.toolCallId,name:g.name,input:g.input}:{id:i,name:""},K=t.createReplyHandle((h=(d=t.action)==null?void 0:d.sourceMessageId)!=null?h:""),Z={toolCall:I,approved:a,approvalMessage:K};e.userOnToolApproval===!1&&(await t.typing(),(y=t.action)!=null&&y.sourceMessageId&&await K.delete());let H=await e.handlers.onToolApproval(Z,t);await Wn(t,H);return}let o=t.action;o&&e.handlers.onAction&&await Wn(t,await e.handlers.onAction(o,t))}async function RA(e,t,n){switch(t){case"onMessage":{let r=n.message;r&&await Wn(n,await e.handlers.onMessage(r,n));break}case"onMessageUpdated":{let r=n.message;r&&e.handlers.onMessageUpdated&&await Wn(n,await e.handlers.onMessageUpdated(r,n));break}case"onMessageDeleted":{let r=n.message;r&&e.handlers.onMessageDeleted&&await Wn(n,await e.handlers.onMessageDeleted(r,n));break}case"onAction":{await EA(e,n);break}case"onReaction":{let r=n.reaction;r&&e.handlers.onReaction&&await Wn(n,await e.handlers.onReaction(r,n));break}case"onResolve":e.handlers.onResolve&&await Wn(n,await e.handlers.onResolve(n));break;default:throw new Nn(t,hc)}}function sg(e){let t={};for(let i of e.split(",")){let a=i.trim();if(!a)continue;let o=a.indexOf("=");if(o<=0)continue;let s=a.slice(0,o),l=a.slice(o+1);s&&l&&!(s in t)&&(t[s]=l)}let n=t.t,r=n!==void 0?Number(n):Number.NaN;return{t:Number.isFinite(r)?r:void 0,v1:t.v1}}var mr=class{constructor(t){this.handler=t.handler,this.client=t.client?t.client:new dr,this.workflows=t.workflows||[],this.agents=t.agents||[],this.http=uo(this.client.secretKey,this.client.apiUrl),this.frameworkName=t.frameworkName,this.hmacEnabled=this.client.strictAuthentication,this.waitUntil=t.waitUntil,this.client.addAgents(this.agents)}createHandler(){return async(...t)=>{await this.client.addWorkflows(this.workflows);let n=await this.handler(...t),r=await this.handleAction({actions:n});return n.transformResponse(r)}}getStaticHeaders(){let t=`novu-framework:v${this.client.version}`;return{"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-private-network":"true","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":"2024-06-26","novu-framework-sdk":"2.14.0","novu-framework-server":this.frameworkName,"user-agent":t}}createResponse(t,n){return{status:t,body:JSON.stringify(n),headers:{...this.getStaticHeaders()}}}createError(t){return{status:t.statusCode,body:JSON.stringify({message:t.message,data:t.data,code:t.code}),headers:this.getStaticHeaders()}}async handleAction({actions:t}){var h;let n=await t.url(),r=await t.method(),i=n.searchParams.get("action")||"health-check",a=n.searchParams.get("workflowId")||"",o=n.searchParams.get("stepId")||"",s=n.searchParams.get("agentId")||"",l=n.searchParams.get("event")||"",p=await t.headers("novu-signature")||"",d={};try{r==="POST"&&(d=await t.body())}catch{}try{i!=="health-check"&&await this.validateHmac(d,p);let y=this.getPostActionMap(d,a,o,i,s,l,(h=this.waitUntil)!=null?h:t.waitUntil),g=this.getGetActionMap(a,o);if(r==="POST")return await this.handlePostAction(i,y);if(r==="GET")return await this.handleGetAction(i,g);if(r==="OPTIONS")return this.createResponse(200,{})}catch(y){return this.handleError(y)}return this.createError(new Zi(r))}getPostActionMap(t,n,r,i,a,o,s){return{trigger:this.triggerAction({workflowId:n,...t}),execute:async()=>{let l=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,l)},preview:async()=>{let l=await this.client.executeWorkflow({...t,workflowId:n,stepId:r,action:i});return this.createResponse(200,l)},"agent-event":async()=>{let l=this.client.getAgent(a);if(!l)return this.createResponse(404,{error:`Agent '${a}' not registered`});let p=og({agent:l,event:o,bridge:t,secretKey:this.client.secretKey,logger:this.client.logger});return s?s(p):this.warnOnUnprotectedServerlessRuntime(a),this.createResponse(200,{status:"ack"})}}}warnOnUnprotectedServerlessRuntime(t){let n;try{process.env.AWS_LAMBDA_FUNCTION_NAME?n="AWS Lambda":process.env.VERCEL&&(n="Vercel")}catch{}n&&this.client.logger.warn(`[agent:${t}] Agent event acknowledged without a \`waitUntil\` primitive while running on ${n}. The runtime may freeze once the response is sent, silently dropping the rest of the agent turn. Pass \`waitUntil\` to \`serve()\` (e.g. \`serve({ agents, waitUntil })\`) to extend the invocation lifetime.`)}triggerAction(t){return async()=>{let n={name:t.workflowId,to:t.to,payload:(t==null?void 0:t.payload)||{},transactionId:t.transactionId,overrides:t.overrides||{},...t.actor&&{actor:t.actor},...t.bridgeUrl&&{bridgeUrl:t.bridgeUrl},...t.controls&&{controls:t.controls},...t.context&&{context:t.context},...t.agentId!==void 0&&{agentId:t.agentId}},r=await this.http.post("/events/trigger",n);return this.createResponse(200,r)}}getGetActionMap(t,n){return{discover:async()=>{let r=await this.client.discover();return this.createResponse(200,r)},"health-check":async()=>{let r=await this.client.healthCheck();return this.createResponse(200,r)},code:async()=>{let r=await this.client.getCode(t,n);return this.createResponse(200,r)}}}async handlePostAction(t,n){if(Object.values(Cr).includes(t)){let r=n[t];return r()}else throw new Nn(t,Cr)}async handleGetAction(t,n){if(Object.values($i).includes(t)){let r=n[t];return r()}else throw new Nn(t,$i)}handleError(t){if(Mn(t))return t.statusCode>=500&&this.client.logger.error(t),this.createError(t);if(vu(t))return this.createError(t);{let n=new Xn(t);return this.client.logger.error(n),this.createError(n)}}async validateHmac(t,n){if(!this.hmacEnabled)return;if(!n)throw new aa;if(!this.client.secretKey)throw new la;let r=sg(n);if(!r.v1||r.t===void 0)throw new oa;let i=Date.now();if(r.t<i-3e5||r.t>i+3e5)throw new sa;let a=await ym(this.client.secretKey,`${r.t}.${JSON.stringify(t)}`);if(!bm(a,r.v1))throw new ia}};function Ac(e,t){if(!e)throw new Error("agent() requires a non-empty agentId");if(!(t!=null&&t.onMessage))throw new Error(`agent('${e}') requires an onMessage handler`);return{id:e,handlers:t,userOnToolApproval:typeof t.onToolApproval=="function"}}var ae={output:{type:"object",properties:{},required:[],additionalProperties:!0}};var CA={type:"object",properties:{text:{type:"string",description:"Overrides the step body text."},effect:{type:"string",description:"iMessage expressive effect: a friendly name (confetti, fireworks, balloons, heart, lasers, celebration, sparkles, spotlight, echo, slam, loud, gentle, invisible) or a raw com.apple.\u2026 effect id."},attachments:{type:"array",items:{type:"string",format:"uri"},description:"Attachment URLs sent alongside the message."},voice:{type:"string",format:"uri",description:"Audio URL sent as a native iMessage voice note (waveform bubble)."},replyToLast:{type:"boolean",description:"Reply-thread this send to the previous message sent to this recipient."},format:{type:"string",enum:["markdown","text"],description:"Force native styled text (markdown) or plain text for the body."}},additionalProperties:!0},cg={output:CA};var OA={type:"object",properties:{webhookUrl:{type:"string",format:"uri"},text:{type:"string"},blocks:{type:"array",items:{type:"object",properties:{type:{type:"string"}},required:["type"],additionalProperties:!0}}},additionalProperties:!0},ug={output:OA};var pg={"chat-webhook":ae,discord:ae,"google-chat":ae,getstream:ae,"grafana-on-call":ae,line:ae,mattermost:ae,msteams:ae,"novu-slack":ae,"novu-web-chat":ae,"photon-imessage":cg,"rocket-chat":ae,ryver:ae,sendblue:ae,slack:ug,"webex-messaging":ae,"whatsapp-business":ae,zulip:ae,telegram:ae};var _A={type:"object",properties:{to:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:'Email address of the recipient(s). Example: "Bob bob@host.com". You can use commas to separate multiple recipients (e.g.: "test@example.com,test@example.com" or ["test@example.com", "test@example.com"]).'},from:{type:"string"},subject:{type:"string",description:"Subject of the message."},text:{type:"string",description:"Text version of the message."},html:{type:"string",description:"HTML version of the message."},message:{type:"string",description:"MIME string of the message. Make sure to use multipart/form-data to send this as a file upload."},cc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Same as To but for carbon copy"},bcc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Same as To but for blind carbon copy"},ampHtml:{type:"string"},tVersion:{type:"string"},tText:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},oTag:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}],description:"Tag string. See Tagging for more information."},oDkim:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Enables/disabled DKIM signatures on per-message basis. Pass yes or no"},oDeliverytime:{type:"string",description:"Desired time of delivery. See Date Format. Note: Messages can be scheduled for a maximum of 3 days in the future."},oDeliverytimeOptimizePeriod:{type:"string"},oTimeZoneLocalize:{type:"string"},oTestmode:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Enables sending in test mode. Pass yes if needed. See Sending in Test Mode"},oTracking:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Toggles tracking on a per-message basis, see Tracking Messages for details. Pass yes or no."},oTrackingClicks:{anyOf:[{type:"string",enum:["yes","no","htmlonly"]},{type:"boolean"}],description:"Toggles clicks tracking on a per-message basis. Has higher priority than domain-level setting. Pass yes, no or htmlonly."},oTrackingOpens:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}],description:"Toggles opens tracking on a per-message basis. Has higher priority than domain-level setting. Pass yes or no."},oRequireTls:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},oSkipVerification:{anyOf:[{type:"string",enum:["yes","no"]},{type:"boolean"}]},recipientVariables:{type:"string"}},required:[],additionalProperties:!0},dg={output:_A};var Yn={type:"object",properties:{name:{type:"string"},email:{type:"string"}},description:'JSON object, containing 2 properties: Name and Email address of a previously validated and active sender. Including the Name property in the JSON is optional. This property is not mandatory in case you use TemplateID and you specified a From address for the template. Format : { "Email":"value", "Name":"value" }.',required:["Email"],additionalProperties:!0},IA={type:"object",properties:{contentType:{type:"string"},filename:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},PA={type:"object",properties:{filename:{type:"string"},contentType:{type:"string"},contentId:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},MA={type:"object",properties:{from:Yn,sender:Yn,to:{type:"array",items:Yn},cc:{type:"array",items:Yn},bcc:{type:"array",items:Yn},replyTo:Yn,subject:{type:"string"},textPart:{type:"string",description:"Content of the message, sent in Text and/or HTML format. At least one of these content types needs to be specified. When the HTML part is the only part provided, Mailjet will not generate a Text-part from the HTML version. The property can't be set when you use TemplateID"},htmlPart:{type:"string",description:"Content of the message, sent in Text and/or HTML format. At least one of these content types needs to be specified. When the HTML part is the only part provided, Mailjet will not generate a Text-part from the HTML version. The property can't be set when you use TemplateID"},templateId:{type:"number",description:"an ID for a template that is previously created and stored in Mailjet's system. It is mandatory when From and TextPart and/or HtmlPart are not provided. "},templateLanguage:{type:"boolean"},templateErrorReporting:Yn,templateErrorDeliver:{type:"boolean"},attachments:{type:"array",items:IA},inlineAttachments:{type:"array",items:PA},priority:{type:"number"},customCampaign:{type:"string"},deduplicateCampaign:{type:"boolean"},trackOpens:{type:"string",enum:["account_default","disabled","enabled"]},trackClicks:{type:"string",enum:["account_default","disabled","enabled"]},customId:{type:"string"},eventPayload:{type:"string"},urlTags:{type:"string"},headers:{type:"object",additionalProperties:!0},variables:{type:"object",additionalProperties:!0}},required:[],additionalProperties:!0},hg={output:MA};var Jt={type:"object",properties:{address:{type:"string"},name:{type:"string"}},additionalProperties:!0},Fo={type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0},NA={type:"object",properties:{from:{anyOf:[{type:"string"},Jt]},sender:{anyOf:[{type:"string"},Jt]},to:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},cc:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},bcc:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},replyTo:{anyOf:[{type:"string"},Jt,{type:"array",items:Jt}]},inReplyTo:{anyOf:[{type:"string"},Jt]},references:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},subject:{type:"string"},text:{anyOf:[{type:"string"},Fo]},html:{anyOf:[{type:"string"},Fo]},watchHtml:{anyOf:[{type:"string"},Fo]},amp:{anyOf:[{type:"string"},{type:"object",properties:{content:{type:"string"},path:{type:"string"},href:{type:"string"},encoding:{type:"string"},contentType:{type:"string"},raw:{anyOf:[{type:"string"},Fo]}}}]},icalEvent:{anyOf:[{type:"string"},{type:"object",properties:{content:{type:"string"},path:{type:"string"},method:{type:"string"},filename:{anyOf:[{type:"string"},{type:"boolean"}]},href:{type:"string"},encoding:{type:"string"}}}]},headers:{anyOf:[{type:"object",additionalProperties:!0},{type:"array",items:{type:"object",additionalProperties:!0}}]},list:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},attachments:{type:"array",items:{type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0}}},required:[],additionalProperties:!0},fg={output:NA};var LA={type:"object",properties:{},required:[],additionalProperties:!1},mg={output:LA};var DA={type:"object",properties:{personalizations:{type:"array",description:"An array of messages and their metadata. Each object within personalizations can be thought of as an envelope - it defines who should receive an individual message and how that message should be handled. See our [Personalizations documentation](https://sendgrid.com/docs/for-developers/sending-email/personalizations/) for examples.",uniqueItems:!1,maxItems:1e3,items:{type:"object",properties:{from:{title:"From Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The 'From' email address used to deliver the message. This address should be a verified sender in your Twilio SendGrid account."},name:{type:"string",description:"A name or title associated with the sending email address."}},required:["email"]},to:{title:"To Email Array",type:"array",items:{type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},cc:{type:"array",description:"An array of recipients who will receive a copy of your email. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name.",maxItems:1e3,items:{title:"CC BCC Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},bcc:{type:"array",description:"An array of recipients who will receive a blind carbon copy of your email. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name.",maxItems:1e3,items:{title:"CC BCC Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The intended recipient's email address."},name:{type:"string",description:"The intended recipient's name."}},required:["email"]}},subject:{type:"string",description:"The subject of your email. See character length requirements according to [RFC 2822](http://stackoverflow.com/questions/1592291/what-is-the-email-subject-length-limit#answer-1592310).",minLength:1},headers:{type:"object",description:"A collection of JSON key/value pairs allowing you to specify handling instructions for your email. You may not overwrite the following headers: `x-sg-id`, `x-sg-eid`, `received`, `dkim-signature`, `Content-Type`, `Content-Transfer-Encoding`, `To`, `From`, `Subject`, `Reply-To`, `CC`, `BCC`"},substitutions:{type:"object",description:'Substitutions allow you to insert data without using Dynamic Transactional Templates. This field should **not** be used in combination with a Dynamic Transactional Template, which can be identified by a `templateId` starting with `d-`. This field is a collection of key/value pairs following the pattern "substitutionTag":"value to substitute". The key/value pairs must be strings. These substitutions will apply to the text and html content of the body of your email, in addition to the `subject` and `reply-to` parameters. The total collective size of your substitutions may not exceed 10,000 bytes per personalization object.',maxProperties:1e4},dynamicTemplateData:{type:"object",description:'Dynamic template data is available using Handlebars syntax in Dynamic Transactional Templates. This field should be used in combination with a Dynamic Transactional Template, which can be identified by a `templateId` starting with `d-`. This field is a collection of key/value pairs following the pattern "variable_name":"value to insert".'},customArgs:{type:"object",description:"Values that are specific to this personalization that will be carried along with the email and its activity data. Substitutions will not be made on custom arguments, so any string that is entered into this parameter will be assumed to be the custom argument that you would like to be used. This field may not exceed 10,000 bytes.",maxProperties:1e4},sendAt:{type:"integer",description:"A unix timestamp allowing you to specify when your email should be delivered. Scheduling delivery more than 72 hours in advance is forbidden."}},required:["to"]}},from:{title:"From Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The 'From' email address used to deliver the message. This address should be a verified sender in your Twilio SendGrid account."},name:{type:"string",description:"A name or title associated with the sending email address."}},required:["email"]},replyTo:{title:"Reply_to Email Object",type:"object",properties:{email:{type:"string",format:"email",description:"The email address where any replies or bounces will be returned."},name:{type:"string",description:"A name or title associated with the `replyTo` email address."}},required:["email"]},replyToList:{type:"array",description:"An array of recipients who will receive replies and/or bounces. Each object in this array must contain the recipient's email address. Each object in the array may optionally contain the recipient's name. You can either choose to use \u201CreplyTo\u201D field or \u201CreplyToList\u201D but not both.",uniqueItems:!0,maxItems:1e3,items:{type:"object",properties:{email:{type:"string",description:"The email address where any replies or bounces will be returned.",format:"email"},name:{type:"string",description:"A name or title associated with the `replyToList` email address."}},required:["email"]}},subject:{type:"string",description:"The global or 'message level' subject of your email. This may be overridden by subject lines set in personalizations.",minLength:1},content:{type:"array",description:"An array where you can specify the content of your email. You can include multiple [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of content, but you must specify at least one MIME type. To include more than one MIME type, add another object to the array containing the `type` and `value` parameters.",items:{type:"object",properties:{type:{type:"string",description:"The MIME type of the content you are including in your email (e.g., `\u201Ctext/plain\u201D` or `\u201Ctext/html\u201D`).",minLength:1},value:{type:"string",description:"The actual content of the specified MIME type that you are including in your email.",minLength:1}},required:["type","value"]}},attachments:{type:"array",description:"An array of objects where you can specify any attachments you want to include.",items:{type:"object",properties:{content:{type:"string",description:"The Base64 encoded content of the attachment.",minLength:1},type:{type:"string",description:"The MIME type of the content you are attaching (e.g., `\u201Ctext/plain\u201D` or `\u201Ctext/html\u201D`).",minLength:1},filename:{type:"string",description:"The attachment's filename."},disposition:{type:"string",default:"attachment",description:"The attachment's content-disposition, specifying how you would like the attachment to be displayed. For example, `\u201Cinline\u201D` results in the attached file are displayed automatically within the message while `\u201Cattachment\u201D` results in the attached file require some action to be taken before it is displayed, such as opening or downloading the file.",enum:["inline","attachment"]},contentId:{type:"string",description:"The attachment's content ID. This is used when the disposition is set to `\u201Cinline\u201D` and the attachment is an image, allowing the file to be displayed within the body of your email."}},required:["content","filename"]}},templateId:{type:"string",description:"An email template ID. A template that contains a subject and content \u2014 either text or html \u2014 will override any subject and content values specified at the personalizations or message level."},headers:{description:"An object containing key/value pairs of header names and the value to substitute for them. The key/value pairs must be strings. You must ensure these are properly encoded if they contain unicode characters. These headers cannot be one of the reserved headers.",type:"object"},categories:{type:"array",description:"An array of category names for this message. Each category name may not exceed 255 characters. ",uniqueItems:!0,maxItems:10,items:{type:"string",maxLength:255}},customArgs:{description:"Values that are specific to the entire send that will be carried along with the email and its activity data. Key/value pairs must be strings. Substitutions will not be made on custom arguments, so any string that is entered into this parameter will be assumed to be the custom argument that you would like to be used. This parameter is overridden by `customArgs` set at the personalizations level. Total `customArgs` size may not exceed 10,000 bytes.",type:"string"},sendAt:{type:"integer",description:"A unix timestamp allowing you to specify when you want your email to be delivered. This may be overridden by the `sendAt` parameter set at the personalizations level. Delivery cannot be scheduled more than 72 hours in advance. If you have the flexibility, it's better to schedule mail for off-peak times. Most emails are scheduled and sent at the top of the hour or half hour. Scheduling email to avoid peak times \u2014 for example, scheduling at 10:53 \u2014 can result in lower deferral rates due to the reduced traffic during off-peak times."},batchId:{type:"string",description:"An ID representing a batch of emails to be sent at the same time. Including a `batchId` in your request allows you include this email in that batch. It also enables you to cancel or pause the delivery of that batch. For more information, see the [Cancel Scheduled Sends API](https://sendgrid.com/docs/api-reference/)."},asm:{type:"object",description:"An object allowing you to specify how to handle unsubscribes.",properties:{groupId:{type:"integer",description:"The unsubscribe group to associate with this email."},groupsToDisplay:{type:"array",description:"An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page.",maxItems:25,items:{type:"integer"}}},required:["groupId"]},ipPoolName:{type:"string",description:"The IP Pool that you would like to send this email from.",minLength:2,maxLength:64},mailSettings:{type:"object",description:"A collection of different mail settings that you can use to specify how you would like this email to be handled.",properties:{bypassListManagement:{type:"object",description:"Allows you to bypass all unsubscribe groups and suppressions to ensure that the email is delivered to every single recipient. This should only be used in emergencies when it is absolutely necessary that every recipient receives your email. This filter cannot be combined with any other bypass filters. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassSpamManagement:{type:"object",description:"Allows you to bypass the spam report list to ensure that the email is delivered to recipients. Bounce and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassBounceManagement:{type:"object",description:"Allows you to bypass the bounce list to ensure that the email is delivered to recipients. Spam report and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},bypassUnsubscribeManagement:{type:"object",description:"Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients. Bounce and spam report lists will still be checked; addresses on these other lists will not receive the message. This filter applies only to global unsubscribes and will not bypass group unsubscribes. This filter cannot be combined with the `bypassListManagement` filter. See our [documentation](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}},footer:{type:"object",description:"The default footer that you would like included on every email.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},text:{type:"string",description:"The plain text content of your footer."},html:{type:"string",description:"The HTML content of your footer."}}},sandboxMode:{type:"object",description:"Sandbox Mode allows you to send a test email to ensure that your request body is valid and formatted correctly.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."}}}}},trackingSettings:{type:"object",description:"Settings to determine how you would like to track the metrics of how your recipients interact with your email.",properties:{clickTracking:{type:"object",description:"Allows you to track if a recipient clicked a link in your email.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},enableText:{type:"boolean",description:"Indicates if this setting should be included in the `text/plain` portion of your email."}}},openTracking:{type:"object",description:"Allows you to track if the email was opened by including a single pixel image in the body of the content. When the pixel is loaded, Twilio SendGrid can log that the email was opened.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},substitutionTag:{type:"string",description:"Allows you to specify a substitution tag that you can insert in the body of your email at a location that you desire. This tag will be replaced by the open tracking pixel."}}},subscriptionTracking:{type:"object",description:"Allows you to insert a subscription management link at the bottom of the text and HTML bodies of your email. If you would like to specify the location of the link within your email, you may use the `substitutionTag`.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},text:{type:"string",description:"Text to be appended to the email with the subscription tracking link. You may control where the link is by using the tag <% %>"},html:{type:"string",description:"HTML to be appended to the email with the subscription tracking link. You may control where the link is by using the tag <% %>"},substitutionTag:{type:"string",description:"A tag that will be replaced with the unsubscribe URL. for example: `[unsubscribe_url]`. If this parameter is used, it will override both the `text` and `html` parameters. The URL of the link will be placed at the substitution tag\u2019s location with no additional formatting."}}},ganalytics:{type:"object",description:"Allows you to enable tracking provided by Google Analytics.",properties:{enable:{type:"boolean",description:"Indicates if this setting is enabled."},utmSource:{type:"string",description:"Name of the referrer source. (e.g. Google, SomeDomain.com, or Marketing Email)"},utmMedium:{type:"string",description:"Name of the marketing medium. (e.g. Email)"},utmTerm:{type:"string",description:"Used to identify any paid keywords."},utmContent:{type:"string",description:"Used to differentiate your campaign from advertisements."},utmCampaign:{type:"string",description:"The name of the campaign."}}}}}},required:[],additionalProperties:!1},gg={output:DA};var yg={anypost:ae,braze:ae,clickatell:ae,nodemailer:fg,emailjs:ae,"email-webhook":ae,"infobip-email":ae,mailersend:ae,mailgun:dg,mailjet:hg,mailtrap:ae,mandrill:ae,netcore:ae,"novu-email":mg,outlook365:ae,plunk:ae,postmark:ae,resend:ae,sendgrid:gg,sendinblue:ae,ses:ae,sparkpost:ae};var FA={type:"object",properties:{},required:[],additionalProperties:!1},bg={output:FA};var wg={novu:bg};var Sg={anyOf:[{type:"string"},{type:"object",additionalProperties:!0,properties:{name:{type:"string"},volume:{type:"number"},critical:{type:"number"}},required:["name","volume","critical"]}]},UA={type:"object",properties:{topic:{type:"string",description:"The destination topic for the notification."},id:{type:"string",description:"A UUID to identify the notification with APNS. If an id is not supplied, APNS will generate one automatically. If an error occurs the response will contain the id. This property populates the apns-id header."},expiry:{type:"number",description:"A UNIX timestamp when the notification should expire. If the notification cannot be delivered to the device, APNS will retry until it expires. An expiry of 0 indicates that the notification expires immediately, therefore no retries will be attempted."},priority:{type:"number",description:`Provide one of the following values:
163
163
 
164
164
  10 - The push notification is sent to the device immediately. (Default)
165
165
  The push notification must trigger an alert, sound, or badge on the device. It is an error to use this priority for a push notification that contains only the content-available key.