@novu/framework 2.10.1-alpha.0 → 2.10.1-alpha.1
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.
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/servers/express.cjs +2 -2
- package/dist/cjs/servers/h3.cjs +2 -2
- package/dist/cjs/servers/lambda.cjs +2 -2
- package/dist/cjs/servers/nest.cjs +2 -2
- package/dist/cjs/servers/next.cjs +2 -2
- package/dist/cjs/servers/nuxt.cjs +2 -2
- package/dist/cjs/servers/remix.cjs +2 -2
- package/dist/cjs/servers/sveltekit.cjs +2 -2
- package/dist/esm/{chunk-WUP5SBTV.js → chunk-TW2732SM.js} +2 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/servers/express.js +1 -1
- package/dist/esm/servers/h3.js +1 -1
- package/dist/esm/servers/lambda.js +1 -1
- package/dist/esm/servers/nest.js +1 -1
- package/dist/esm/servers/next.js +1 -1
- package/dist/esm/servers/nuxt.js +1 -1
- package/dist/esm/servers/remix.js +1 -1
- package/dist/esm/servers/sveltekit.js +1 -1
- package/package.json +1 -1
package/dist/cjs/index.cjs
CHANGED
|
@@ -89,7 +89,7 @@ et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco
|
|
|
89
89
|
commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
|
|
90
90
|
pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est
|
|
91
91
|
laborum`.split(/\W/),zr=Dr,Vr={type:Ht.ALLOWED_TYPES},vl=Fr,$a=xa,El=Ur,Wr=$r,Al=Ta,Ol=ka,qa="[a-zA-Z][a-zA-Z0-9+-.]*",Hr=`https?://{hostname}(?:${qa})+`,_l="(?:\\?([a-z]{1,7}(=\\w{1,5})?&){0,3})?",Ft={email:"[a-zA-Z\\d][a-zA-Z\\d-]{1,13}[a-zA-Z\\d]@{hostname}",hostname:"[a-zA-Z]{1,33}\\.[a-z]{2,4}",ipv6:"[a-f\\d]{4}(:[a-f\\d]{4}){7}",uri:Hr,slug:"[a-zA-Z\\d_-]+","uri-reference":`${Hr}${_l}`,"uri-template":Hr.replace("(?:","(?:/\\{[a-z][:a-zA-Z0-9-]*\\}|"),"json-pointer":`(/(?:${qa.replace("]*","/]*")}|~[01]))+`,uuid:"^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$",duration:"^P(?!$)((\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+S)?)?|(\\d+W)?)$"},Ft.iri=Ft["uri-reference"],Ft["iri-reference"]=Ft["uri-reference"],Ft["idn-email"]=Ft.email,Ft["idn-hostname"]=Ft.hostname,Rl=new RegExp(`\\{(${Object.keys(Ft).join("|")})\\}`),Il=va,Cl=Aa,Pl={boolean:yl,null:Sl,array:xl,integer:Tl,number:Ua,object:vl,string:Cl},ur=Pl,Ml=ne,Nl=({refs:l,schema:c,container:f,synchronous:S,refDepthMax:x,refDepthMin:v})=>{let k={},N={},X=0,M,re;return k.resolveSchema=(q,de,se)=>{if(q==null)return null;if(typeof q.generate=="function")return q;if(typeof(q.$id||q.id)=="string"&&(delete q.id,delete q.$id,delete q.$schema),typeof q.$ref=="string"){let xe=Math.max(v,x)-1;if(q.$ref==="#"||N[q.$ref]<0||M===q.$ref&&++X>xe)return q.$ref!=="#"&&re&&re.length===se.length?We.getLocalRef(c,q.$ref,S&&l):(delete q.$ref,q);typeof N[q.$ref]=="undefined"&&(N[q.$ref]=ke.number(v,x)-1),re=se,M=q.$ref;let Oe;q.$ref.indexOf("#/")===-1?Oe=l[q.$ref]||null:Oe=We.getLocalRef(c,q.$ref,S&&l)||null;let Ye;if(typeof Oe!="undefined"){if(!Oe&&Ae("ignoreMissingRefs")!==!0)throw new Error(`Reference not found: ${q.$ref}`);N[q.$ref]-=1,We.merge(q,Oe||{}),Ye=S&&Oe&&Oe.$ref}return Ye||delete q.$ref,q}if(Array.isArray(q.allOf)){let xe=q.allOf;delete q.allOf,xe.forEach(Oe=>{let Ye=k.resolveSchema(Oe,null,se);We.merge(q,typeof Ye.thunk=="function"?Ye.thunk(q):Ye),Array.isArray(q.allOf)&&k.resolveSchema(q,de,se)})}if(Array.isArray(q.oneOf||q.anyOf)&&se[se.length-2]!=="dependencies"){let xe=q.oneOf||q.anyOf;return q.enum&&q.oneOf&&(q.enum=q.enum.filter(Oe=>We.validate(Oe,xe))),{thunk(Oe){let Ye=We.omitProps(q,["anyOf","oneOf"]),Ke=ke.pick(xe);return We.merge(Ye,Ke),xe.forEach(ie=>{ie.required&&ie!==Ke&&ie.required.forEach(I=>{if(Ke.required&&Ke.required.includes(I))return;let C=Ye.required&&Ye.required.includes(I);Ye.properties&&!C&&delete Ye.properties[I],Oe&&Oe.properties&&delete Oe.properties[I]})}),Ye}}}if(Object.keys(q).forEach(xe=>{(Array.isArray(q[xe])||typeof q[xe]=="object")&&!We.isKey(xe)&&(q[xe]=k.resolveSchema(q[xe],xe,se.concat(xe)))}),se){let xe=se[se.length-1];if(xe==="properties"||xe==="items")return q}return f.wrap(q)},k},Ll=Nl,ja=Ct,Ba=Zt,Tt=Ra(Qs(),1),Zp=Tt.default.binaryOptions,ed=Tt.default.boolOptions,td=Tt.default.intOptions,nd=Tt.default.nullOptions,rd=Tt.default.strOptions,id=Tt.default.Schema,ad=Tt.default.Alias,od=Tt.default.Collection,sd=Tt.default.Merge,ld=Tt.default.Node,cd=Tt.default.Pair,ud=Tt.default.Scalar,Dl=Tt.default.YAMLMap,Fl=Tt.default.YAMLSeq,pr=An,nn=new pl,tt=(l,c,f)=>(console.debug("[json-schema-faker] calling JSONSchemaFaker() is deprecated, call either .generate() or .resolve()"),f&&console.debug("[json-schema-faker] local references are only supported by calling .resolve()"),tt.generate(l,c)),tt.generateWithContext=(l,c)=>{let f=tn(c,l);return ja(f,l,nn,!0)},tt.generate=(l,c)=>Ba(tt.generateWithContext(l,c)),tt.generateYAML=(l,c)=>pr(tt.generateWithContext(l,c)),tt.resolveWithContext=(l,c,f)=>{typeof c=="string"&&(f=c,c={}),f=f||(typeof process!="undefined"&&typeof process.cwd=="function"?process.cwd():""),f=`${f.replace(/\/+$/,"")}/`;let S=tn(c,l),x={order:1,canRead(k){let N=k.url.replace("/:",":");return S[N]||S[N.split("/").pop()]},read(k,N){try{N(null,this.canRead(k))}catch(X){N(X)}}},{$RefParser:v}=Pa();return v.bundle(f,l,{resolve:{file:{order:100},http:{order:200},fixedRefs:x},dereference:{circular:"ignore"}}).then(k=>ja(S,k,nn)).catch(k=>{throw new Error(`Error while resolving schema (${k.message})`)})},tt.resolve=(l,c,f)=>tt.resolveWithContext(l,c,f).then(Ba),tt.resolveYAML=(l,c,f)=>tt.resolveWithContext(l,c,f).then(pr),yt(),tt.format=Fa,tt.option=Ae,tt.random=ke,tt.extend=(l,c)=>(nn.extend(l,c),tt),tt.define=(l,c)=>(nn.define(l,c),tt),tt.reset=l=>(nn.reset(l),yt(),tt),tt.locate=l=>nn.get(l),tt.VERSION="0.5.5",Ul={...tt},$l=tt}}),dd=o({"src/src/main.iife.js"(l,c){var f=(pd(),u(p));typeof $RefParser!="undefined"&&typeof JSONPath!="undefined"&&f.setDependencies({...JSONPath,$RefParser}),typeof window!="undefined"&&(window.JSONSchemaFaker=f.default),c.exports=f.default,c.exports.JSONSchemaFaker=f.JSONSchemaFaker}});return dd()})();((e,n)=>{e.JSONSchemaFaker=n()})(typeof self!="undefined"?self:typeof window!="undefined"?window:globalThis,()=>wi);wi.random.shuffle=function(){return["[placeholder]"]};wi.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Kl(e){return wi.generate(e)}var Xl=async(e,n)=>{let t=new TextEncoder,r=t.encode(e),i=t.encode(n),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),a=await crypto.subtle.sign("HMAC",o,i);return Array.from(new Uint8Array(a)).map(s=>s.toString(16).padStart(2,"0")).join("")};var Fd=require("cross-fetch");var Ql=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 n=await(await fetch("http://localhost:2022/.well-known/novu")).json();return`${n.tunnelOrigin}${n.route}`}}catch(e){console.error(e)}return""};function Zl(e){return!!e&&typeof e=="object"&&"error"in e&&"message"in e&&"statusCode"in e}var Si=(e,n)=>{if(!e)throw new li;return{post:async(t,r)=>{let i=await fetch(`${n}/v1${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`},body:JSON.stringify(r)}),o=await i.json();if(i.ok)return o;throw Zl(o)?new ci(o.statusCode,o.error,o.message):new Bn(o)},delete:async t=>(await fetch(`${n}/v1${t}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${e}`}})).json()}};var ac=require("liquidjs");function Ha(e,n){let t={...e};for(let r of Object.keys(n)){let i=n[r];i&&typeof i=="object"&&!Array.isArray(i)?t[r]=Ha(t[r]||{},i):(Array.isArray(i),t[r]=i)}return t}function xi(e,n){let t=n.split(".").reduce((r,i)=>{if(r&&typeof r=="object")return r[i]},e);if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(typeof t=="object"){let r=JSON.stringify(t);return r==="{}"?"":r}return""}function ec(e,n=2,t,r=", "){if(!Array.isArray(e)||e.length===0)return"";let i=t?e.map(s=>typeof s!="object"||!s?"":xi(s,t)):e;if(i.length===1)return i[0];if(i.length===2)return`${i[0]} and ${i[1]}`;if(i.length===3&&n>=3)return`${i[0]}, ${r}${i[1]} and ${i[2]}`;let o=i.slice(0,n),a=i.length-n;return`${o.join(r)} and ${a} ${a===1?"other":"others"}`}var tc=$t(require("pluralize"),1);function nc(e,n="",t="",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 o;return t?o=i===1?n:t:o=(0,tc.default)(n,i),r==="true"?`${i} ${o}`:o}var Ud=require("liquidjs"),rc=$t(require("pluralize"),1),$d=require("zod");var qd="",jd=2,Bd="other",zd=", ",Vd=" and ",Wd=", and ";function ic(e,n=qd,t=jd,r=Bd,i=zd,o=Vd,a=Wd){if(!Array.isArray(e)||e.length===0)return"";let s=n?e.map(y=>typeof y!="object"||!y?"":xi(y,n)):e,u=s.length;if(u===1)return s[0];if(u===2)return`${s[0]}${o}${s[1]}`;if(t>=u){let y=s.slice(0,u-1),g=s[u-1];return`${y.join(i)}${a}${g}`}let p=s.slice(0,t),d=u-t,h=t===1?o:a;return`${p.join(i)}${h}${d} ${(0,rc.default)(r,d)}`}function Hd(e){return Array.isArray(e)||typeof e=="object"&&e!==null?oc(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 oc=(e,n=0)=>Array.isArray(e)||typeof e=="object"&&e!==null?JSON.stringify(e,null,n).replace(/"/g,"'").replace(/\n/g,"\\n"):e==null?"":String(e);function sc(e){let n=new ac.Liquid({outputEscape:Hd,...e});return n.registerFilter("json",(t,r)=>oc(t,r)),n.registerFilter("digest",ec),n.registerFilter("toSentence",ic),n.registerFilter("pluralize",nc),n}var Rn=$t(require("chalk"),1),Qe={info:e=>Rn.default.blue(e),warning:e=>Rn.default.yellow(e),error:e=>Rn.default.red(e),success:e=>Rn.default.green(e),underline:e=>Rn.default.underline(e),bold:e=>Rn.default.bold(e)},st={SUCCESS:Qe.success("\u2714"),ERROR:Qe.error("\u2717"),WARNING:Qe.warning("\u26A0"),INFO:Qe.info("\u2139"),ARROW:Qe.bold("\u2192"),MOCK:Qe.info("\u25CB"),HYDRATED:Qe.bold(Qe.info("\u2192")),STEP:Qe.info("\u03C3"),ACTION:Qe.info("\u03B1"),DURATION:Qe.info("\u0394"),PROVIDER:Qe.info("\u2699"),OUTPUT:Qe.info("\u21E2"),INPUT:Qe.info("\u21E0"),WORKFLOW:Qe.info("\u03C9"),STATE:Qe.info("\u03C3"),EXECUTE:Qe.info("\u03B5"),PREVIEW:Qe.info("\u03C1")};function Ti(e){return e||process.env.NOVU_API_URL||"https://api.novu.co"}function ki(e){return e||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY||""}var Ya=$t(require("sanitize-html"),1),Yd=["src","alt","width","height","loading","srcset","sizes","crossorigin","usemap","ismap","class","id","style","title","dir","lang"];function Jd(e){return e.toLowerCase().startsWith("on")}function Gd(e){return e.replace(/<\/([a-zA-Z][a-zA-Z0-9]*)\s*\/[^>]*>/g,"</$1>")}var Kd={allowedTags:Ya.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,transformTags:{"*":(e,n)=>{let t={};for(let[r,i]of Object.entries(n))Jd(r)||(t[r]=i);return{tagName:e,attribs:t}},img:(e,n)=>{let t={};for(let[r,i]of Object.entries(n))Yd.includes(r.toLowerCase())&&(t[r]=i);return{tagName:e,attribs:t}}},allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},lc=e=>{if(!e)return e;let n=Gd(e),t=/^<!DOCTYPE .*?>/,r=n.match(t),i=(0,Ya.default)(n,Kd);return r?r[0]+i:i},vi=e=>Object.keys(e).reduce((n,t)=>{let r=e[t];return typeof r=="string"?n[t]=lc(r):Array.isArray(r)?n[t]=r.map(i=>typeof i=="string"?lc(i):typeof i=="object"?vi(i):i):typeof r=="object"&&r!==null?n[t]=vi(r):n[t]=r,n},{});function cc(e,n=!0){n&&(console.log(`
|
|
92
|
-
${Qe.bold(Qe.underline("Discovered workflowId:"))} '${e.workflowId}'`),e.steps.forEach((t,r)=>{let i=r===e.steps.length-1;console.log(`${i?"\u2514":"\u251C"} ${st.STEP} Discovered stepId: '${t.stepId}' Type: '${t.type}'`),t.providers.forEach((a,s)=>{let u=s===t.providers.length-1;console.log(`${i?" ":"\u2502"} ${u?"\u2514":"\u251C"} ${st.PROVIDER} Discovered provider: '${a.type}'`)})}))}var uc=require("jsonrepair");function Xd(e){let n=e.trim();return(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))&&n.length>2}function Qd(e){try{return JSON.parse(e),e}catch{try{return(0,uc.jsonrepair)(e)}catch{return e}}}function pc(e){return Object.fromEntries(Object.entries(e).map(([n,t])=>typeof t=="string"?[n,Xd(t)?Qd(t):t]:typeof t=="object"&&t!==null&&!Array.isArray(t)?[n,pc(t)]:[n,t]))}function dc(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:pc(e.data)}}var fc=$t(require("ajv"),1),mc=$t(require("ajv-formats"),1);var hc=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var Ei=class extends gn{constructor(t,r){let i=r.length===1?"it":"them";super(`Tried to use a ${t} in @novu/framework without ${r.join(", ")} installed. Please install ${i} by running \`npm install ${r.join(" ")}\`.`);this.statusCode=500;this.code="MissingDependencyError"}};var Ai=async(e,n)=>{let t=new Set;if((await Promise.allSettled(e.map(i=>i.import))).forEach((i,o)=>{let a=e[o];i.status==="fulfilled"&&a.exports.every(u=>i.value[u]!==void 0)||t.add(a.name)}),t.size>0)throw new Ei(n,Array.from(t))};var Oi=class{constructor(){this.requiredImports=[];this.ajv=new fc.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,mc.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(n){let t=n.type==="object"||!!n.anyOf||!!n.allOf||!!n.oneOf;return t&&await Ai(this.requiredImports,"JSON schema"),t}async validate(n,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let i=hc(n);return r(i)?{success:!0,data:i}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}async transformToJsonSchema(n){return n}};var _i=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(n){let t=n.safeParseAsync!==void 0;return t&&await Ai(this.requiredImports,"Zod schema"),t}async validate(n,t){let r=await t.safeParseAsync(n);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(i=>({path:`/${i.path.join("/")}`,message:i.message}))}}async transformToJsonSchema(n){let{zodToJsonSchema:t}=await import("zod-to-json-schema");return t(n)}};var Ri=new _i,Ii=new Oi,Tr=async(e,n)=>{if(await Ri.canHandle(e))return Ri.validate(n,e);if(await Ii.canHandle(e))return Ii.validate(n,e);throw new Error("Invalid schema")},ft=async e=>{if(await Ri.canHandle(e))return Ri.transformToJsonSchema(e);if(await Ii.canHandle(e))return Ii.transformToJsonSchema(e);throw new Error("Invalid schema")};function gc(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var Hn=class{constructor(n){this.discoveredWorkflows=new Map;this.discoverWorkflowPromises=new Map;this.registeredAgents=new Map;this.version="2.10.1-alpha.
|
|
92
|
+
${Qe.bold(Qe.underline("Discovered workflowId:"))} '${e.workflowId}'`),e.steps.forEach((t,r)=>{let i=r===e.steps.length-1;console.log(`${i?"\u2514":"\u251C"} ${st.STEP} Discovered stepId: '${t.stepId}' Type: '${t.type}'`),t.providers.forEach((a,s)=>{let u=s===t.providers.length-1;console.log(`${i?" ":"\u2502"} ${u?"\u2514":"\u251C"} ${st.PROVIDER} Discovered provider: '${a.type}'`)})}))}var uc=require("jsonrepair");function Xd(e){let n=e.trim();return(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))&&n.length>2}function Qd(e){try{return JSON.parse(e),e}catch{try{return(0,uc.jsonrepair)(e)}catch{return e}}}function pc(e){return Object.fromEntries(Object.entries(e).map(([n,t])=>typeof t=="string"?[n,Xd(t)?Qd(t):t]:typeof t=="object"&&t!==null&&!Array.isArray(t)?[n,pc(t)]:[n,t]))}function dc(e){return!(e!=null&&e.data)||typeof e.data!="object"||Array.isArray(e.data)?e:{...e,data:pc(e.data)}}var fc=$t(require("ajv"),1),mc=$t(require("ajv-formats"),1);var hc=e=>typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e));var Ei=class extends gn{constructor(t,r){let i=r.length===1?"it":"them";super(`Tried to use a ${t} in @novu/framework without ${r.join(", ")} installed. Please install ${i} by running \`npm install ${r.join(" ")}\`.`);this.statusCode=500;this.code="MissingDependencyError"}};var Ai=async(e,n)=>{let t=new Set;if((await Promise.allSettled(e.map(i=>i.import))).forEach((i,o)=>{let a=e[o];i.status==="fulfilled"&&a.exports.every(u=>i.value[u]!==void 0)||t.add(a.name)}),t.size>0)throw new Ei(n,Array.from(t))};var Oi=class{constructor(){this.requiredImports=[];this.ajv=new fc.default({useDefaults:!0,removeAdditional:"failing",strict:!1}),(0,mc.default)(this.ajv),this.compiledSchemas=new Map}async canHandle(n){let t=n.type==="object"||!!n.anyOf||!!n.allOf||!!n.oneOf;return t&&await Ai(this.requiredImports,"JSON schema"),t}async validate(n,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let i=hc(n);return r(i)?{success:!0,data:i}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}async transformToJsonSchema(n){return n}};var _i=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(n){let t=n.safeParseAsync!==void 0;return t&&await Ai(this.requiredImports,"Zod schema"),t}async validate(n,t){let r=await t.safeParseAsync(n);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(i=>({path:`/${i.path.join("/")}`,message:i.message}))}}async transformToJsonSchema(n){let{zodToJsonSchema:t}=await import("zod-to-json-schema");return t(n)}};var Ri=new _i,Ii=new Oi,Tr=async(e,n)=>{if(await Ri.canHandle(e))return Ri.validate(n,e);if(await Ii.canHandle(e))return Ii.validate(n,e);throw new Error("Invalid schema")},ft=async e=>{if(await Ri.canHandle(e))return Ri.transformToJsonSchema(e);if(await Ii.canHandle(e))return Ii.transformToJsonSchema(e);throw new Error("Invalid schema")};function gc(){return["development",void 0,"dev"].includes(process.env.NODE_ENV)}var Hn=class{constructor(n){this.discoveredWorkflows=new Map;this.discoverWorkflowPromises=new Map;this.registeredAgents=new Map;this.version="2.10.1-alpha.1";let t=this.buildOptions(n);this.apiUrl=t.apiUrl,this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication,this.verbose=t.verbose,this.templateEngine=sc()}buildOptions(n){let t={apiUrl:Ti(n==null?void 0:n.apiUrl),secretKey:ki(n==null?void 0:n.secretKey),strictAuthentication:!gc(),verbose:gc()};return(n==null?void 0:n.strictAuthentication)!==void 0?t.strictAuthentication=n.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),(n==null?void 0:n.verbose)!==void 0&&(t.verbose=n.verbose),t}log(...n){this.verbose&&console.log(...n)}async addWorkflows(n){for(let t of n){if(this.discoveredWorkflows.has(t.id))continue;let r=this.discoverWorkflowPromises.get(t.id);if(r){await r;continue}let i=this.addWorkflow(t);this.discoverWorkflowPromises.set(t.id,i),await i}}addAgents(n){for(let t of n)this.registeredAgents.set(t.id,t)}getAgent(n){return this.registeredAgents.get(n)}async addWorkflow(n){try{let t=await n.discover();cc(t,this.verbose),this.discoveredWorkflows.set(n.id,t)}finally{this.discoverWorkflowPromises.delete(n.id)}}healthCheck(){let n=this.getRegisteredWorkflows(),t=n.length,r=n.reduce((i,o)=>i+o.steps.length,0);return{status:"ok",sdkVersion:"2.10.1-alpha.1",frameworkVersion:"2024-06-26",discovered:{workflows:t,steps:r}}}getWorkflow(n){let t=this.discoveredWorkflows.get(n);if(t)return t;throw new wr(n)}getStep(n,t){let i=this.getWorkflow(n).steps.find(o=>o.stepId===t);if(i)return i;throw new yi(t)}getRegisteredWorkflows(){return Array.from(this.discoveredWorkflows.values())}discover(){return{workflows:this.getRegisteredWorkflows(),agents:Array.from(this.registeredAgents.keys()).map(n=>({agentId:n}))}}mock(n){try{return Kl(n)}catch(t){return console.warn("Failed to mock schema, returning empty object:",t),{}}}async validate(n,t,r,i,o,a,s){let u=await Tr(t,n);if(u.success)return u.data;switch(r){case"event":this.throwInvalidEvent(i,o,u.errors);case"step":this.throwInvalidStep(a,i,o,u.errors);case"provider":this.throwInvalidProvider(a,s,i,o,u.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(n,t,r,i,o){if(!n)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new ii(i,n,t,o);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(n,t,r,i){if(!n)throw new Error("stepId is required");switch(t){case"output":throw new ti(r,n,i);case"result":throw new ni(r,n,i);case"controls":throw new ei(r,n,i);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(n,t,r){switch(n){case"controls":throw new Zr(t,r);case"payload":throw new gr(t,r);default:throw new Error(`Invalid payload type: '${n}'`)}}executeStepFactory(n,t,r){return async(i,o,a)=>{if(r())return;let s=this.getStep(n.workflowId,i),u=n.action==="preview";if(!u&&i===n.stepId){let g=await this.createStepControls(s,n),P=await this.compileControls(g,n);if(await this.shouldSkip(a==null?void 0:a.skip,P))return t({options:{skip:!0},outputs:{},providers:{}}),{}}let p=this.previewStep.bind(this),d=this.executeStep.bind(this),y=await(u?p:d)(n,{...s,providers:s.providers.map(g=>{var Z;let P=(Z=a==null?void 0:a.providers)==null?void 0:Z[g.type];if(!P)throw new ui(g.type);return{...g,resolve:P}}),resolve:o});return this.shouldSanitize({stepType:s.type,options:a})&&(y={...y,outputs:vi(y.outputs)}),i===n.stepId&&t({...y,options:{skip:!1}}),y.outputs}}shouldSanitize({stepType:n,options:t}){return(t==null?void 0:t.disableOutputSanitization)===!0?!1:["email","in_app"].includes(n)}async shouldSkip(n,t){return n?n(t):!1}async executeWorkflow(n){let i=`${{execute:"Executing",preview:"Previewing"}[n.action]||n.action} workflowId:`;this.log(`
|
|
93
93
|
${Qe.bold(Qe.underline(i))} '${n.workflowId}'`);let o=this.getWorkflow(n.workflowId),a=process.hrtime(),s={outputs:{},providers:{},options:{skip:!1}},u,p=!1,d=new Promise(_e=>{u=_e}),h=_e=>{if(p)throw new Error("setResult can only be called once per workflow execution");u(),p=!0,s=_e},y=()=>p,g;try{if(n.action==="execute"&&!n.payload)throw new gr(n.workflowId,{message:"Event `payload` is required"});let _e=await this.createExecutionPayload(n,o),U={...n,payload:_e};await Promise.race([d,o.execute({payload:_e,env:n.env,controls:{},subscriber:n.subscriber,context:n.context,step:{email:this.executeStepFactory(U,h,y),sms:this.executeStepFactory(U,h,y),inApp:this.executeStepFactory(U,h,y),digest:this.executeStepFactory(U,h,y),delay:this.executeStepFactory(U,h,y),push:this.executeStepFactory(U,h,y),chat:this.executeStepFactory(U,h,y),custom:this.executeStepFactory(U,h,y),throttle:this.executeStepFactory(U,h,y)}})])}catch(_e){g=_e}let P=process.hrtime(a),Z=P[0],Q=P[1],j=Z*1e3+Q/1e6,pe=g?st.ERROR:st.SUCCESS,Te={execute:"Executed",preview:"Previewed"}[n.action]||n.action;if(this.log(`${pe} ${Te} workflowId: \`${n.workflowId}\``),this.prettyPrintExecute(n,j,g),g)throw g;return{outputs:s.outputs,providers:s.providers,options:s.options,metadata:{status:"success",error:!1,duration:j}}}async createExecutionPayload(n,t){let{payload:r}=n;if(n.action==="preview"){let o=this.mock(t.payload.schema);r=Object.assign(o,r)}return await this.validate(r,t.payload.unknownSchema,"event","payload",n.workflowId)}prettyPrintExecute(n,t,r){if(!this.verbose)return;let i=r?st.ERROR:st.SUCCESS,a={execute:"Executed",preview:"Previewed"}[n.action]||n.action,s=r?"Failed to execute":a,u=r?Qe.error:Qe.success,p=`${i} ${s} workflowId: '${n.workflowId}`;console.log(`
|
|
94
94
|
${Qe.bold(u(p))}'`),console.log(` \u251C ${st.STEP} stepId: '${n.stepId}'`),console.log(` \u251C ${st.ACTION} action: '${n.action}'`),console.log(` \u2514 ${st.DURATION} duration: '${t.toFixed(2)}ms'
|
|
95
95
|
`)}async executeProviders(n,t,r){return t.providers.reduce(async(i,o)=>{let a=await i,s=this.previewProvider.bind(this),u=this.executeProvider.bind(this),d=await(n.action==="preview"?s:u)(n,t,o,r);return{...a,[o.type]:d}},Promise.resolve({}))}previewProvider(n,t,r,i){return this.log(` ${st.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(n,t,r,i){try{if(n.stepId===t.stepId){let o=await this.createStepControls(t,n),a=await r.resolve({controls:o,outputs:i}),s=await this.validate(a,r.outputs.unknownSchema,"step","output",n.workflowId,t.stepId,r.type);return this.log(` ${st.SUCCESS} Executed provider: \`${r.type}\``),{...s,_passthrough:a._passthrough}}else return this.log(` ${st.HYDRATED} Hydrated provider: \`${r.type}\``),{}}catch(o){throw this.log(` ${st.ERROR} Failed to execute provider: \`${r.type}\``),new pi(r.type,n.action,o)}}async executeStep(n,t){if(n.stepId===t.stepId)try{let r=await this.createStepControls(t,n),i=await this.compileControls(r,n),o=await t.resolve(i),a=await this.validate(o,t.outputs.unknownSchema,"step","output",n.workflowId,t.stepId),s=await this.executeProviders(n,t,a);return this.log(` ${st.SUCCESS} Executed stepId: \`${t.stepId}\``),{outputs:a,providers:s}}catch(r){throw this.log(` ${st.ERROR} Failed to execute stepId: \`${t.stepId}\``),On(r)?r:new br(t.stepId,n.action,r)}else try{let r=this.getStepState(n,t.stepId);if(r){let i=await this.validate(r.outputs,t.results.unknownSchema,"step","result",n.workflowId,t.stepId);return this.log(` ${st.HYDRATED} Hydrated stepId: \`${t.stepId}\``),{outputs:i,providers:await this.executeProviders(n,t,i)}}else throw new Qr(n.workflowId,t.stepId)}catch(r){throw this.log(` ${st.ERROR} Failed to hydrate stepId: \`${t.stepId}\``),r}}async compileControls(n,t){var r;try{let i=this.preprocessTranslationPatterns(JSON.stringify(n));i=this.preprocessFilterTranslationArgs(i);let o=this.templateEngine.parse(i),a=this.getWorkflow(t.workflowId),s={workflow:{workflowId:a.workflowId,name:a.name,description:a.description,tags:a.tags,severity:a.severity},payload:t.payload,subscriber:t.subscriber,context:t.context,steps:Zd(t.state),env:(r=t.env)!=null?r:{}},u=await this.templateEngine.render(o,s),p=this.postprocessTranslationMarkers(u),d=(0,yc.jsonrepair)(p),h=JSON.parse(d);return dc(h)}catch(i){throw new ri(t.workflowId,t.stepId,i)}}preprocessTranslationPatterns(n){return n.replace(/\{\{\s*t\.([\p{L}\p{N}_.-]+)\s*\}\}/gu,"[T:$1]")}preprocessFilterTranslationArgs(n){return n.replace(/'t\.([\p{L}\p{N}_.-]+)'/gu,"'[T:$1]'")}postprocessTranslationMarkers(n){return n.replace(/\[T:([\p{L}\p{N}_.-]+)\]/gu,"{{t.$1}}")}async createStepControls(n,t){return await this.validate(t.controls,n.controls.unknownSchema,"step","controls",t.workflowId,n.stepId)}async previewStep(n,t){try{return await this.constructStepForPreview(n,t)}catch(r){throw this.log(` ${st.ERROR} Failed to preview stepId: \`${t.stepId}\``),On(r)?r:new br(t.stepId,n.action,r)}}async constructStepForPreview(n,t){return n.stepId===t.stepId?await this.previewRequiredStep(t,n):await this.extractMockDataForPreviousSteps(n,t)}async extractMockDataForPreviousSteps(n,t){let r={},i=this.getStepState(n,t.stepId),o=this.mock(t.results.schema);return{outputs:Ha(o,(i==null?void 0:i.outputs)||{}),providers:await this.executeProviders(n,t,r)}}async previewRequiredStep(n,t){let r=await this.createStepControls(n,t),i=await this.compileControls(r,t),o=await n.resolve(i),a=await this.validate(o,n.outputs.unknownSchema,"step","output",t.workflowId,n.stepId);return this.log(` ${st.MOCK} Mocked stepId: \`${n.stepId}\``),{outputs:a,providers:await this.executeProviders(t,n,a)}}getStepState(n,t){return n.state.find(r=>r.stepId===t)}getStepCode(n,t){return{code:this.getStep(n,t).resolve.toString()}}getWorkflowCode(n){return{code:this.getWorkflow(n).execute.toString()}}getCode(n,t){let r;if(n)t?r=this.getStepCode(n,t):r=this.getWorkflowCode(n);else throw new wr(n);return r}};function Zd(e){let n={};for(let t of e)n[t.stepId]=t.outputs;return n}var eh={};function ln(e,n){let t=n||eh,r=typeof t.includeImageAlt=="boolean"?t.includeImageAlt:!0,i=typeof t.includeHtml=="boolean"?t.includeHtml:!0;return wc(e,r,i)}function wc(e,n,t){if(th(e)){if("value"in e)return e.type==="html"&&!t?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return bc(e.children,n,t)}return Array.isArray(e)?bc(e,n,t):""}function bc(e,n,t){let r=[],i=-1;for(;++i<e.length;)r[i]=wc(e[i],n,t);return r.join("")}function th(e){return!!(e&&typeof e=="object")}function Ja(e,n){let t=String(e);if(typeof n!="string")throw new TypeError("Expected character");let r=0,i=t.indexOf(n);for(;i!==-1;)r++,i=t.indexOf(n,i+n.length);return r}var ut=bn(/[A-Za-z]/),pt=bn(/[\dA-Za-z]/),Sc=bn(/[#-'*+\--9=?A-Z^-~]/);function In(e){return e!==null&&(e<32||e===127)}var kr=bn(/\d/),xc=bn(/[\dA-Fa-f]/),Tc=bn(/[!-/:-@[-`{-~]/);function oe(e){return e!==null&&e<-2}function Ne(e){return e!==null&&(e<0||e===32)}function we(e){return e===-2||e===-1||e===32}var Cn=bn(/\p{P}|\p{S}/u),Jt=bn(/\s/);function bn(e){return n;function n(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function Ga(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}var wn=(function(e){if(e==null)return ah;if(typeof e=="function")return Ci(e);if(typeof e=="object")return Array.isArray(e)?nh(e):rh(e);if(typeof e=="string")return ih(e);throw new Error("Expected function, string, or object as test")});function nh(e){let n=[],t=-1;for(;++t<e.length;)n[t]=wn(e[t]);return Ci(r);function r(...i){let o=-1;for(;++o<n.length;)if(n[o].apply(this,i))return!0;return!1}}function rh(e){let n=e;return Ci(t);function t(r){let i=r,o;for(o in e)if(i[o]!==n[o])return!1;return!0}}function ih(e){return Ci(n);function n(t){return t&&t.type===e}}function Ci(e){return n;function n(t,r,i){return!!(oh(t)&&e.call(this,t,typeof r=="number"?r:void 0,i||void 0))}}function ah(){return!0}function oh(e){return e!==null&&typeof e=="object"&&"type"in e}function kc(e){return"\x1B[33m"+e+"\x1B[39m"}var vc=[],Pi=!0,Pn=!1,Mi="skip";function vr(e,n,t,r){let i;typeof n=="function"&&typeof t!="function"?(r=t,t=n):i=n;let o=wn(i),a=r?-1:1;s(e,void 0,[])();function s(u,p,d){let h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){let g=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(y,"name",{value:"node ("+kc(u.type+(g?"<"+g+">":""))+")"})}return y;function y(){let g=vc,P,Z,Q;if((!n||o(u,p,d[d.length-1]||void 0))&&(g=sh(t(u,d)),g[0]===Pn))return g;if("children"in u&&u.children){let j=u;if(j.children&&g[0]!==Mi)for(Z=(r?j.children.length:-1)+a,Q=d.concat(j);Z>-1&&Z<j.children.length;){let pe=j.children[Z];if(P=s(pe,Z,Q)(),P[0]===Pn)return P;Z=typeof P[1]=="number"?P[1]:Z+a}}return g}}}function sh(e){return Array.isArray(e)?e:typeof e=="number"?[Pi,e]:e==null?vc:[e]}function Ka(e,n,t){let i=wn((t||{}).ignore||[]),o=lh(n),a=-1;for(;++a<o.length;)vr(e,"text",s);function s(p,d){let h=-1,y;for(;++h<d.length;){let g=d[h],P=y?y.children:void 0;if(i(g,P?P.indexOf(g):void 0,y))return;y=g}if(y)return u(p,d)}function u(p,d){let h=d[d.length-1],y=o[a][0],g=o[a][1],P=0,Q=h.children.indexOf(p),j=!1,pe=[];y.lastIndex=0;let te=y.exec(p.value);for(;te;){let Te=te.index,_e={index:te.index,input:te.input,stack:[...d,p]},U=g(...te,_e);if(typeof U=="string"&&(U=U.length>0?{type:"text",value:U}:void 0),U===!1?y.lastIndex=Te+1:(P!==Te&&pe.push({type:"text",value:p.value.slice(P,Te)}),Array.isArray(U)?pe.push(...U):U&&pe.push(U),P=Te+te[0].length,j=!0),!y.global)break;te=y.exec(p.value)}return j?(P<p.value.length&&pe.push({type:"text",value:p.value.slice(P)}),h.children.splice(Q,1,...pe)):pe=[p],Q+pe.length}}function lh(e){let n=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");let t=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r<t.length;){let i=t[r];n.push([ch(i[0]),uh(i[1])])}return n}function ch(e){return typeof e=="string"?new RegExp(Ga(e),"g"):e}function uh(e){return typeof e=="function"?e:function(){return e}}var Xa="phrasing",Qa=["autolink","link","image","label"];function eo(){return{transforms:[gh],enter:{literalAutolink:ph,literalAutolinkEmail:Za,literalAutolinkHttp:Za,literalAutolinkWww:Za},exit:{literalAutolink:mh,literalAutolinkEmail:fh,literalAutolinkHttp:dh,literalAutolinkWww:hh}}}function to(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Xa,notInConstruct:Qa},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Xa,notInConstruct:Qa},{character:":",before:"[ps]",after:"\\/",inConstruct:Xa,notInConstruct:Qa}]}}function ph(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Za(e){this.config.enter.autolinkProtocol.call(this,e)}function dh(e){this.config.exit.autolinkProtocol.call(this,e)}function hh(e){this.config.exit.data.call(this,e);let n=this.stack[this.stack.length-1];n.type,n.url="http://"+this.sliceSerialize(e)}function fh(e){this.config.exit.autolinkEmail.call(this,e)}function mh(e){this.exit(e)}function gh(e){Ka(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,yh],[/([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/g,bh]],{ignore:["link","linkReference"]})}function yh(e,n,t,r,i){let o="";if(!Ec(i)||(/^w/i.test(n)&&(t=n+t,n="",o="http://"),!wh(t)))return!1;let a=Sh(t+r);if(!a[0])return!1;let s={type:"link",title:null,url:o+n+a[0],children:[{type:"text",value:n+a[0]}]};return a[1]?[s,{type:"text",value:a[1]}]:s}function bh(e,n,t,r){return!Ec(r,!0)||/[-\d_]$/.test(t)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+t,children:[{type:"text",value:n+"@"+t}]}}function wh(e){let n=e.split(".");return!(n.length<2||n[n.length-1]&&(/_/.test(n[n.length-1])||!/[a-zA-Z\d]/.test(n[n.length-1]))||n[n.length-2]&&(/_/.test(n[n.length-2])||!/[a-zA-Z\d]/.test(n[n.length-2])))}function Sh(e){let n=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!n)return[e,void 0];e=e.slice(0,n.index);let t=n[0],r=t.indexOf(")"),i=Ja(e,"("),o=Ja(e,")");for(;r!==-1&&i>o;)e+=t.slice(0,r+1),t=t.slice(r+1),r=t.indexOf(")"),o++;return[e,t]}function Ec(e,n){let t=e.input.charCodeAt(e.index-1);return(e.index===0||Jt(t)||Cn(t))&&(!n||t!==47)}function wt(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}Ac.peek=Rh;function no(){return{enter:{gfmFootnoteDefinition:xh,gfmFootnoteDefinitionLabelString:Th,gfmFootnoteCall:Eh,gfmFootnoteCallString:Ah},exit:{gfmFootnoteDefinition:vh,gfmFootnoteDefinitionLabelString:kh,gfmFootnoteCall:_h,gfmFootnoteCallString:Oh}}}function ro(){return{unsafe:[{character:"[",inConstruct:["phrasing","label","reference"]}],handlers:{footnoteDefinition:Ih,footnoteReference:Ac}}}function xh(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Th(){this.buffer()}function kh(e){let n=this.resume(),t=this.stack[this.stack.length-1];t.type,t.label=n,t.identifier=wt(this.sliceSerialize(e)).toLowerCase()}function vh(e){this.exit(e)}function Eh(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function Ah(){this.buffer()}function Oh(e){let n=this.resume(),t=this.stack[this.stack.length-1];t.type,t.label=n,t.identifier=wt(this.sliceSerialize(e)).toLowerCase()}function _h(e){this.exit(e)}function Ac(e,n,t,r){let i=t.createTracker(r),o=i.move("[^"),a=t.enter("footnoteReference"),s=t.enter("reference");return o+=i.move(t.safe(t.associationId(e),{...i.current(),before:o,after:"]"})),s(),a(),o+=i.move("]"),o}function Rh(){return"["}function Ih(e,n,t,r){let i=t.createTracker(r),o=i.move("[^"),a=t.enter("footnoteDefinition"),s=t.enter("label");return o+=i.move(t.safe(t.associationId(e),{...i.current(),before:o,after:"]"})),s(),o+=i.move("]:"+(e.children&&e.children.length>0?" ":"")),i.shift(4),o+=i.move(t.indentLines(t.containerFlow(e,i.current()),Ch)),a(),o}function Ch(e,n,t){return n===0?e:(t?"":" ")+e}var Ph=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Oc.peek=Lh;function io(){return{canContainEols:["delete"],enter:{strikethrough:Mh},exit:{strikethrough:Nh}}}function ao(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:Ph}],handlers:{delete:Oc}}}function Mh(e){this.enter({type:"delete",children:[]},e)}function Nh(e){this.exit(e)}function Oc(e,n,t,r){let i=t.createTracker(r),o=t.enter("strikethrough"),a=i.move("~~");return a+=t.containerPhrasing(e,{...i.current(),before:a,after:"~"}),a+=i.move("~~"),o(),a}function Lh(){return"~"}function Rc(e,n={}){let t=(n.align||[]).concat(),r=n.stringLength||Fh,i=[],o=[],a=[],s=[],u=0,p=-1;for(;++p<e.length;){let P=[],Z=[],Q=-1;for(e[p].length>u&&(u=e[p].length);++Q<e[p].length;){let j=Dh(e[p][Q]);if(n.alignDelimiters!==!1){let pe=r(j);Z[Q]=pe,(s[Q]===void 0||pe>s[Q])&&(s[Q]=pe)}P.push(j)}o[p]=P,a[p]=Z}let d=-1;if(typeof t=="object"&&"length"in t)for(;++d<u;)i[d]=_c(t[d]);else{let P=_c(t);for(;++d<u;)i[d]=P}d=-1;let h=[],y=[];for(;++d<u;){let P=i[d],Z="",Q="";P===99?(Z=":",Q=":"):P===108?Z=":":P===114&&(Q=":");let j=n.alignDelimiters===!1?1:Math.max(1,s[d]-Z.length-Q.length),pe=Z+"-".repeat(j)+Q;n.alignDelimiters!==!1&&(j=Z.length+j+Q.length,j>s[d]&&(s[d]=j),y[d]=j),h[d]=pe}o.splice(1,0,h),a.splice(1,0,y),p=-1;let g=[];for(;++p<o.length;){let P=o[p],Z=a[p];d=-1;let Q=[];for(;++d<u;){let j=P[d]||"",pe="",te="";if(n.alignDelimiters!==!1){let Te=s[d]-(Z[d]||0),_e=i[d];_e===114?pe=" ".repeat(Te):_e===99?Te%2?(pe=" ".repeat(Te/2+.5),te=" ".repeat(Te/2-.5)):(pe=" ".repeat(Te/2),te=pe):te=" ".repeat(Te)}n.delimiterStart!==!1&&!d&&Q.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&j==="")&&(n.delimiterStart!==!1||d)&&Q.push(" "),n.alignDelimiters!==!1&&Q.push(pe),Q.push(j),n.alignDelimiters!==!1&&Q.push(te),n.padding!==!1&&Q.push(" "),(n.delimiterEnd!==!1||d!==u-1)&&Q.push("|")}g.push(n.delimiterEnd===!1?Q.join("").replace(/ +$/,""):Q.join(""))}return g.join(`
|
|
@@ -148,7 +148,7 @@ $$`:`${e}$$`},uy=e=>sy(e)%2===0?e:cy(e),py=e=>ly(e)%2===1?`${e}$`:e,dy=(e,n,t)=>
|
|
|
148
148
|
`),r=e.split(`
|
|
149
149
|
`);t&&r.length>0&&r.at(-1)===""&&r.pop();let i=[],o=!1,a=!1;for(let u=0;u<r.length;u++){let p=r[u].trim();if(!o&&(p.startsWith("```")||p.startsWith("~~~"))){a=!a,i.push(r[u]);continue}if(a){i.push(r[u]);continue}let d=p!==""&&(_s.test(p)||Rs.test(p));if(d&&!o){let h=!1;for(let y=u;y<r.length;y++){let g=r[y].trim();if(Rs.test(g)){h=!0;break}if(g===""||!_s.test(g))break}h&&(i.push("```"),o=!0)}else!d&&o&&(i.push("```"),o=!1);i.push(r[u])}o&&n&&i.push("```");let s=i.join(`
|
|
150
150
|
`);return t&&(s+=`
|
|
151
|
-
`),s}function $y(e){return"adapterName"in e&&!("adapter"in e)}var gp="thread-state:";function qy(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}var jR=class Is{constructor(n){Ee(this,"id");Ee(this,"channelId");Ee(this,"isDM");Ee(this,"channelVisibility");Ee(this,"_adapter");Ee(this,"_adapterName");Ee(this,"_stateAdapterInstance");Ee(this,"_recentMessages",[]);Ee(this,"_isSubscribedContext");Ee(this,"_currentMessage");Ee(this,"_streamingUpdateIntervalMs");Ee(this,"_fallbackStreamingPlaceholderText");Ee(this,"_channel");Ee(this,"_messageHistory");Ee(this,"_logger");var t,r,i,o;this.id=n.id,this.channelId=n.channelId,this.isDM=(t=n.isDM)!=null?t:!1,this.channelVisibility=(r=n.channelVisibility)!=null?r:"unknown",this._isSubscribedContext=(i=n.isSubscribedContext)!=null?i:!1,this._currentMessage=n.currentMessage,this._logger=n.logger,this._streamingUpdateIntervalMs=(o=n.streamingUpdateIntervalMs)!=null?o:500,this._fallbackStreamingPlaceholderText=n.fallbackStreamingPlaceholderText!==void 0?n.fallbackStreamingPlaceholderText:"...",$y(n)?this._adapterName=n.adapterName:(this._adapter=n.adapter,this._stateAdapterInstance=n.stateAdapter,this._messageHistory=n.messageHistory),n.initialMessage&&(this._recentMessages=[n.initialMessage])}get adapter(){if(this._adapter)return this._adapter;if(!this._adapterName)throw new Error("Thread has no adapter configured");let t=ca().getAdapter(this._adapterName);if(!t)throw new Error(`Adapter "${this._adapterName}" not found in Chat singleton`);return this._adapter=t,t}get _stateAdapter(){if(this._stateAdapterInstance)return this._stateAdapterInstance;let n=ca();return this._stateAdapterInstance=n.getState(),this._stateAdapterInstance}get recentMessages(){return this._recentMessages}set recentMessages(n){this._recentMessages=n}get state(){return this._stateAdapter.get(`${gp}${this.id}`)}async setState(n,t){let r=`${gp}${this.id}`;if(t!=null&&t.replace)await this._stateAdapter.set(r,n,ua);else{let o={...await this._stateAdapter.get(r),...n};await this._stateAdapter.set(r,o,ua)}}get channel(){if(!this._channel){let n=My(this.adapter,this.id);this._channel=new Py({id:n,adapter:this.adapter,stateAdapter:this._stateAdapter,isDM:this.isDM,channelVisibility:this.channelVisibility,messageHistory:this._messageHistory})}return this._channel}get messages(){let n=this.adapter,t=this.id,r=this._messageHistory;return{async*[Symbol.asyncIterator](){let i,o=!1;for(;;){let a=await n.fetchMessages(t,{cursor:i,direction:"backward"}),s=[...a.messages].reverse();for(let u of s)o=!0,yield u;if(!a.nextCursor||a.messages.length===0)break;i=a.nextCursor}if(!o&&r){let a=await r.getMessages(t);for(let s=a.length-1;s>=0;s--)yield a[s]}}}}get allMessages(){let n=this.adapter,t=this.id,r=this._messageHistory;return{async*[Symbol.asyncIterator](){let i,o=!1;for(;;){let a=await n.fetchMessages(t,{limit:100,cursor:i,direction:"forward"});for(let s of a.messages)o=!0,yield s;if(!a.nextCursor||a.messages.length===0)break;i=a.nextCursor}if(!o&&r){let a=await r.getMessages(t);for(let s of a)yield s}}}}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(n){if(wp(n))return await this.handlePostableObject(n),n;if(qy(n))return this.handleStream(n);let t=n;if(Nt(n)){let o=Mt(n);if(!o)throw new Error("Invalid JSX element: must be a Card element");t=o}let r=await this.adapter.postMessage(this.id,t),i=this.createSentMessage(r.id,t,r.threadId);return this._messageHistory&&await this._messageHistory.append(this.id,new Un(i)),i}async handlePostableObject(n){await Sp(n,this.adapter,this.id,(t,r)=>this.adapter.postMessage(t,r),this._logger)}async postEphemeral(n,t,r){let{fallbackToDM:i}=r,o=typeof n=="string"?n:n.userId,a;if(Nt(t)){let s=Mt(t);if(!s)throw new Error("Invalid JSX element: must be a Card element");a=s}else a=t;if(this.adapter.postEphemeral)return this.adapter.postEphemeral(this.id,o,a);if(!i)return null;if(this.adapter.openDM){let s=await this.adapter.openDM(o),u=await this.adapter.postMessage(s,a);return{id:u.id,threadId:s,usedFallback:!0,raw:u.raw}}return null}async schedule(n,t){let r;if(Nt(n)){let i=Mt(n);if(!i)throw new Error("Invalid JSX element: must be a Card element");r=i}else r=n;if(!this.adapter.scheduleMessage)throw new xp("Scheduled messages are not supported by this adapter","scheduling");return this.adapter.scheduleMessage(this.id,r,t)}async handleStream(n){var o;let t=bp(n),r={};if(this._currentMessage){r.recipientUserId=this._currentMessage.author.userId;let a=this._currentMessage.raw;r.recipientTeamId=(o=a==null?void 0:a.team_id)!=null?o:a==null?void 0:a.team}if(this.adapter.stream){let a="",s={[Symbol.asyncIterator]:()=>{let d=t[Symbol.asyncIterator]();return{async next(){let h=await d.next();if(!h.done){let y=h.value;typeof y=="string"?a+=y:y.type==="markdown_text"&&(a+=y.text)}return h}}}},u=await this.adapter.stream(this.id,s,r),p=this.createSentMessage(u.id,{markdown:a},u.threadId);return this._messageHistory&&await this._messageHistory.append(this.id,new Un(p)),p}let i={[Symbol.asyncIterator]:()=>{let a=t[Symbol.asyncIterator]();return{async next(){for(;;){let s=await a.next();if(s.done)return{value:void 0,done:!0};let u=s.value;if(typeof u=="string")return{value:u,done:!1};if(u.type==="markdown_text")return{value:u.text,done:!1}}}}}};return this.fallbackStream(i,r)}async startTyping(n){await this.adapter.startTyping(this.id,n)}async fallbackStream(n,t){var j;let r=(j=t==null?void 0:t.updateIntervalMs)!=null?j:this._streamingUpdateIntervalMs,i=this._fallbackStreamingPlaceholderText,o=i===null?null:await this.adapter.postMessage(this.id,i),a=this.id,s=new Ly,u="",p=!1,d=null,h=null;o&&(a=o.threadId||this.id,u=i!=null?i:"");let y=()=>{h=setTimeout(()=>{d=g()},r)},g=async()=>{var te;if(p||!o)return;let pe=s.render();if(pe!==u)try{await this.adapter.editMessage(a,o.id,{markdown:pe}),u=pe}catch(Te){(te=this._logger)==null||te.warn("fallbackStream edit failed",Te)}p||y()};o&&y();try{for await(let pe of n)if(s.push(pe),!o){let te=s.render();o=await this.adapter.postMessage(this.id,{markdown:te}),a=o.threadId||this.id,u=te,y()}}finally{p=!0,h&&(clearTimeout(h),h=null)}d&&await d;let P=s.getText(),Z=s.finish();o||(o=await this.adapter.postMessage(this.id,{markdown:P}),a=o.threadId||this.id,u=P),Z!==u&&await this.adapter.editMessage(a,o.id,{markdown:P});let Q=this.createSentMessage(o.id,{markdown:P},a);return this._messageHistory&&await this._messageHistory.append(this.id,new Un(Q)),Q}async refresh(){let n=await this.adapter.fetchMessages(this.id,{limit:50});n.messages.length>0?this._recentMessages=n.messages:this._messageHistory?this._recentMessages=await this._messageHistory.getMessages(this.id,50):this._recentMessages=[]}mentionUser(n){return`<@${n}>`}toJSON(){var n;return{_type:"chat:Thread",id:this.id,channelId:this.channelId,channelVisibility:this.channelVisibility,currentMessage:(n=this._currentMessage)==null?void 0:n.toJSON(),isDM:this.isDM,adapterName:this.adapter.name}}static fromJSON(n,t){let r=new Is({id:n.id,adapterName:n.adapterName,channelId:n.channelId,channelVisibility:n.channelVisibility,currentMessage:n.currentMessage?Un.fromJSON(n.currentMessage):void 0,isDM:n.isDM});return t&&(r._adapter=t),r}static[Qn](n){return n.toJSON()}static[Zn](n){return Is.fromJSON(n)}createSentMessage(n,t,r){let i=this.adapter,o=r||this.id,a=this,{plainText:s,formatted:u,attachments:p}=jy(t);return{id:n,threadId:o,text:s,formatted:u,raw:null,links:[],author:{userId:"self",userName:i.userName,fullName:i.userName,isBot:!0,isMe:!0},metadata:{dateSent:new Date,edited:!1},attachments:p,toJSON(){return new Un(this).toJSON()},async edit(h){let y=h;if(Nt(h)){let g=Mt(h);if(!g)throw new Error("Invalid JSX element: must be a Card element");y=g}return await i.editMessage(o,n,y),a.createSentMessage(n,y)},async delete(){await i.deleteMessage(o,n)},async addReaction(h){await i.addReaction(o,n,h)},async removeReaction(h){await i.removeReaction(o,n,h)}}}createSentMessageFromMessage(n){let t=this.adapter,r=this.id,i=n.id,o=this;return{id:n.id,threadId:n.threadId,text:n.text,formatted:n.formatted,raw:n.raw,author:n.author,metadata:n.metadata,attachments:n.attachments,links:n.links,isMention:n.isMention,toJSON(){return n.toJSON()},async edit(a){let s=a;if(Nt(a)){let u=Mt(a);if(!u)throw new Error("Invalid JSX element: must be a Card element");s=u}return await t.editMessage(r,i,s),o.createSentMessage(i,s,r)},async delete(){await t.deleteMessage(r,i)},async addReaction(a){await t.addReaction(r,i,a)},async removeReaction(a){await t.removeReaction(r,i,a)}}}};function jy(e){if(typeof e=="string")return{plainText:e,formatted:dn([pn([un(e)])]),attachments:[]};if("raw"in e)return{plainText:e.raw,formatted:dn([pn([un(e.raw)])]),attachments:e.attachments||[]};if("markdown"in e){let n=bs(e.markdown);return{plainText:Pr(n),formatted:n,attachments:e.attachments||[]}}if("ast"in e)return{plainText:Pr(e.ast),formatted:e.ast,attachments:e.attachments||[]};if("card"in e){let n=e.fallbackText||Mr(e.card);return{plainText:n,formatted:dn([pn([un(n)])]),attachments:[]}}if("type"in e&&e.type==="card"){let n=Mr(e);return{plainText:n,formatted:dn([pn([un(n)])]),attachments:[]}}throw new Error("Invalid PostableMessage format")}var BR=300*1e3,zR=1440*60*1e3;var yp=new Map;function er(e){let n=yp.get(e);return n||(n=Object.freeze({name:e,toString:()=>`{{emoji:${e}}}`,toJSON:()=>`{{emoji:${e}}}`}),yp.set(e,n)),n}var By={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}"}},zy=class{constructor(e){Ee(this,"emojiMap");Ee(this,"slackToNormalized");Ee(this,"gchatToNormalized");this.emojiMap={...By,...e},this.slackToNormalized=new Map,this.gchatToNormalized=new Map,this.buildReverseMaps()}buildReverseMaps(){for(let[e,n]of Object.entries(this.emojiMap)){let t=Array.isArray(n.slack)?n.slack:[n.slack];for(let i of t)this.slackToNormalized.set(i.toLowerCase(),e);let r=Array.isArray(n.gchat)?n.gchat:[n.gchat];for(let i of r)this.gchatToNormalized.set(i,e)}}fromSlack(e){var r;let n=e.replace(/^:|:$/g,"").toLowerCase(),t=(r=this.slackToNormalized.get(n))!=null?r:e;return er(t)}fromGChat(e){var t;let n=(t=this.gchatToNormalized.get(e))!=null?t:e;return er(n)}fromTeams(e){var r;let t=(r={like:"thumbs_up",heart:"heart",laugh:"laugh",surprised:"surprised",sad:"sad",angry:"angry"}[e])!=null?r:e;return er(t)}toSlack(e){let n=typeof e=="string"?e:e.name,t=this.emojiMap[n];return t?Array.isArray(t.slack)?t.slack[0]:t.slack:n}toGChat(e){let n=typeof e=="string"?e:e.name,t=this.emojiMap[n];return t?Array.isArray(t.gchat)?t.gchat[0]:t.gchat:n}toDiscord(e){return this.toGChat(e)}matches(e,n){let t=typeof n=="string"?n:n.name,r=this.emojiMap[t];if(!r)return e===t;let i=Array.isArray(r.slack)?r.slack:[r.slack],o=Array.isArray(r.gchat)?r.gchat:[r.gchat],a=e.replace(/^:|:$/g,"").toLowerCase();return i.some(s=>s.toLowerCase()===a)||o.includes(e)}extend(e){Object.assign(this.emojiMap,e),this.buildReverseMaps()}},Vy=new zy;function Wy(e){let n=["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"],t={custom:r=>er(r)};for(let r of n)t[r]=er(r);if(e){for(let r of Object.keys(e))t[r]=er(r);Vy.extend(e)}return t}var VR=Wy(),Cs=na,Ps=ra,Ms=ws;var Ns=ia,Ls=Ju,Ds=ta;var Fs=oa,Us=sa,$s=aa;function Hy(e){return"type"in e&&e.type==="card"}function Tp(e){var n;if(typeof e=="string")return{text:e};if(Nt(e)){let t=Mt(e);if(t)return{card:t}}if(Hy(e))return{card:e};if("markdown"in e&&typeof e.markdown=="string"){let t={markdown:e.markdown};return(n=e.files)!=null&&n.length&&(t.files=e.files),t}throw new Error("Invalid message content \u2014 expected string, { markdown }, or CardElement")}var Lr=class{constructor(n,t){this._signals=[];this._resolveSignal=null;var r;this.event=n.event,this.action=(r=n.action)!=null?r:null,this.message=n.message,this.reaction=n.reaction,this.conversation=n.conversation,this.subscriber=n.subscriber,this.history=n.history,this.platform=n.platform,this.platformContext=n.platformContext,this._replyUrl=n.replyUrl,this._conversationId=n.conversationId,this._integrationIdentifier=n.integrationIdentifier,this._secretKey=t,this.metadata={set:(i,o)=>{this._signals.push({type:"metadata",key:i,value:o})}}}async reply(n){let t={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,reply:Tp(n)};this._signals.length&&(t.signals=this._signals,this._signals=[]),this._resolveSignal&&(t.resolve=this._resolveSignal,this._resolveSignal=null),await this._post(t)}async update(n){let t={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,update:Tp(n)};await this._post(t)}resolve(n){this._resolveSignal={summary:n}}trigger(n,t){this._signals.push({type:"trigger",workflowId:n,...t})}async flush(){if(!this._signals.length&&!this._resolveSignal)return;let n={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier};this._signals.length&&(n.signals=this._signals,this._signals=[]),this._resolveSignal&&(n.resolve=this._resolveSignal,this._resolveSignal=null),await this._post(n)}async _post(n){let t=await fetch(this._replyUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this._secretKey}`},body:JSON.stringify(n)});if(!t.ok){let r=await t.text().catch(()=>"");throw new Error(`Agent reply failed (${t.status}): ${r}`)}}};function qs(e,n){if(!e)throw new Error("agent() requires a non-empty agentId");if(!(n!=null&&n.onMessage))throw new Error(`agent('${e}') requires an onMessage handler`);return{id:e,handlers:n}}var pa=(i=>(i.ON_MESSAGE="onMessage",i.ON_ACTION="onAction",i.ON_RESOLVE="onResolve",i.ON_REACTION="onReaction",i))(pa||{});var da=class{constructor(n){this.handler=n.handler,this.client=n.client?n.client:new Hn,this.workflows=n.workflows||[],this.agents=n.agents||[],this.http=Si(this.client.secretKey,this.client.apiUrl),this.frameworkName=n.frameworkName,this.hmacEnabled=this.client.strictAuthentication,this.client.addAgents(this.agents)}createHandler(){return async(...n)=>{await this.client.addWorkflows(this.workflows);let t=await this.handler(...n),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let n=`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.10.1-alpha.0","novu-framework-server":this.frameworkName,"user-agent":n}}createResponse(n,t){return{status:n,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(n){return{status:n.statusCode,body:JSON.stringify({message:n.message,data:n.data,code:n.code}),headers:this.getStaticHeaders()}}async handleAction({actions:n}){let t=await n.url(),r=await n.method(),i=t.searchParams.get("action")||"health-check",o=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",s=t.searchParams.get("agentId")||"",u=t.searchParams.get("event")||"",p=await n.headers("novu-signature")||"",d={};try{r==="POST"&&(d=await n.body())}catch{}try{i!=="health-check"&&await this.validateHmac(d,p);let h=this.getPostActionMap(d,o,a,i,s,u,n.waitUntil),y=this.getGetActionMap(o,a);if(r==="POST")return await this.handlePostAction(i,h);if(r==="GET")return await this.handleGetAction(i,y);if(r==="OPTIONS")return this.createResponse(200,{})}catch(h){return this.handleError(h)}return this.createError(new si(r))}getPostActionMap(n,t,r,i,o,a,s){return{trigger:this.triggerAction({workflowId:t,...n}),execute:async()=>{let u=await this.client.executeWorkflow({...n,workflowId:t,stepId:r,action:i});return this.createResponse(200,u)},preview:async()=>{let u=await this.client.executeWorkflow({...n,workflowId:t,stepId:r,action:i});return this.createResponse(200,u)},"agent-event":async()=>{let u=this.client.getAgent(o);if(!u)return this.createResponse(404,{error:`Agent '${o}' not registered`});let p=new Lr(n,this.client.secretKey),d=this.runAgentHandler(u,a,p).catch(h=>{console.error(`[agent:${o}] Handler error:`,h)});return s&&s(d),this.createResponse(200,{status:"ack"})}}}triggerAction(n){return async()=>{let t={name:n.workflowId,to:n.to,payload:(n==null?void 0:n.payload)||{},transactionId:n.transactionId,overrides:n.overrides||{},...n.actor&&{actor:n.actor},...n.bridgeUrl&&{bridgeUrl:n.bridgeUrl},...n.controls&&{controls:n.controls},...n.context&&{context:n.context}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(n,t){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(n,t);return this.createResponse(200,r)}}}async handlePostAction(n,t){if(Object.values(fr).includes(n)){let r=t[n];return r()}else throw new zn(n,fr)}async handleGetAction(n,t){if(Object.values(Jr).includes(n)){let r=t[n];return r()}else throw new zn(n,Jr)}async runAgentHandler(n,t,r){let i={onMessage:n.handlers.onMessage,onReaction:n.handlers.onReaction,onAction:n.handlers.onAction,onResolve:n.handlers.onResolve};if(!Object.prototype.hasOwnProperty.call(i,t))throw new zn(t,pa);let o=i[t];o&&await o(r),await r.flush()}handleError(n){if(On(n))return n.statusCode>=500&&console.error(n),this.createError(n);if(Bl(n))return this.createError(n);{let t=new Bn(n);return console.error(t),this.createError(t)}}async validateHmac(n,t){if(!this.hmacEnabled)return;if(!t)throw new hi;if(!this.client.secretKey)throw new gi;let[r,i]=t.split(",");if(!r||!i)throw new fi;let[o,a]=r.split("="),[s,u]=i.split("=");if(Number(o)<Date.now()-1500)throw new mi;if(!(await Xl(this.client.secretKey,`${a}.${JSON.stringify(n)}`)===u))throw new di}};var ue={output:{type:"object",properties:{},required:[],additionalProperties:!0}};var Jy={type:"object",properties:{webhookUrl:{type:"string",format:"uri"},text:{type:"string"},blocks:{type:"array",items:{type:"object",properties:{type:{enum:["image","context","actions","divider","section","input","file","header","video","rich_text"]}},required:["type"],additionalProperties:!0}}},additionalProperties:!0},kp={output:Jy};var vp={"chat-webhook":ue,discord:ue,getstream:ue,"grafana-on-call":ue,mattermost:ue,msteams:ue,"rocket-chat":ue,ryver:ue,slack:kp,"whatsapp-business":ue,zulip:ue};var Gy={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},Ep={output:Gy};var $n={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},Ky={type:"object",properties:{contentType:{type:"string"},filename:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},Xy={type:"object",properties:{filename:{type:"string"},contentType:{type:"string"},contentId:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},Qy={type:"object",properties:{from:$n,sender:$n,to:{type:"array",items:$n},cc:{type:"array",items:$n},bcc:{type:"array",items:$n},replyTo:$n,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:$n,templateErrorDeliver:{type:"boolean"},attachments:{type:"array",items:Ky},inlineAttachments:{type:"array",items:Xy},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},Ap={output:Qy};var Vt={type:"object",properties:{address:{type:"string"},name:{type:"string"}},additionalProperties:!0},ha={type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0},Zy={type:"object",properties:{from:{anyOf:[{type:"string"},Vt]},sender:{anyOf:[{type:"string"},Vt]},to:{anyOf:[{type:"string"},Vt,{type:"array",items:Vt}]},cc:{anyOf:[{type:"string"},Vt,{type:"array",items:Vt}]},bcc:{anyOf:[{type:"string"},Vt,{type:"array",items:Vt}]},replyTo:{anyOf:[{type:"string"},Vt,{type:"array",items:Vt}]},inReplyTo:{anyOf:[{type:"string"},Vt]},references:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},subject:{type:"string"},text:{anyOf:[{type:"string"},ha]},html:{anyOf:[{type:"string"},ha]},watchHtml:{anyOf:[{type:"string"},ha]},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"},ha]}}}]},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},Op={output:Zy};var eb={type:"object",properties:{},required:[],additionalProperties:!1},_p={output:eb};var tb={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},Rp={output:tb};var Ip={braze:ue,clickatell:ue,nodemailer:Op,emailjs:ue,"email-webhook":ue,"infobip-email":ue,mailersend:ue,mailgun:Ep,mailjet:Ap,mailtrap:ue,mandrill:ue,netcore:ue,"novu-email":_p,outlook365:ue,plunk:ue,postmark:ue,resend:ue,sendgrid:Rp,sendinblue:ue,ses:ue,sparkpost:ue};var nb={type:"object",properties:{},required:[],additionalProperties:!1},Cp={output:nb};var Pp={novu:Cp};var Mp={anyOf:[{type:"string"},{type:"object",additionalProperties:!0,properties:{name:{type:"string"},volume:{type:"number"},critical:{type:"number"}},required:["name","volume","critical"]}]},rb={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:
|
|
151
|
+
`),s}function $y(e){return"adapterName"in e&&!("adapter"in e)}var gp="thread-state:";function qy(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}var jR=class Is{constructor(n){Ee(this,"id");Ee(this,"channelId");Ee(this,"isDM");Ee(this,"channelVisibility");Ee(this,"_adapter");Ee(this,"_adapterName");Ee(this,"_stateAdapterInstance");Ee(this,"_recentMessages",[]);Ee(this,"_isSubscribedContext");Ee(this,"_currentMessage");Ee(this,"_streamingUpdateIntervalMs");Ee(this,"_fallbackStreamingPlaceholderText");Ee(this,"_channel");Ee(this,"_messageHistory");Ee(this,"_logger");var t,r,i,o;this.id=n.id,this.channelId=n.channelId,this.isDM=(t=n.isDM)!=null?t:!1,this.channelVisibility=(r=n.channelVisibility)!=null?r:"unknown",this._isSubscribedContext=(i=n.isSubscribedContext)!=null?i:!1,this._currentMessage=n.currentMessage,this._logger=n.logger,this._streamingUpdateIntervalMs=(o=n.streamingUpdateIntervalMs)!=null?o:500,this._fallbackStreamingPlaceholderText=n.fallbackStreamingPlaceholderText!==void 0?n.fallbackStreamingPlaceholderText:"...",$y(n)?this._adapterName=n.adapterName:(this._adapter=n.adapter,this._stateAdapterInstance=n.stateAdapter,this._messageHistory=n.messageHistory),n.initialMessage&&(this._recentMessages=[n.initialMessage])}get adapter(){if(this._adapter)return this._adapter;if(!this._adapterName)throw new Error("Thread has no adapter configured");let t=ca().getAdapter(this._adapterName);if(!t)throw new Error(`Adapter "${this._adapterName}" not found in Chat singleton`);return this._adapter=t,t}get _stateAdapter(){if(this._stateAdapterInstance)return this._stateAdapterInstance;let n=ca();return this._stateAdapterInstance=n.getState(),this._stateAdapterInstance}get recentMessages(){return this._recentMessages}set recentMessages(n){this._recentMessages=n}get state(){return this._stateAdapter.get(`${gp}${this.id}`)}async setState(n,t){let r=`${gp}${this.id}`;if(t!=null&&t.replace)await this._stateAdapter.set(r,n,ua);else{let o={...await this._stateAdapter.get(r),...n};await this._stateAdapter.set(r,o,ua)}}get channel(){if(!this._channel){let n=My(this.adapter,this.id);this._channel=new Py({id:n,adapter:this.adapter,stateAdapter:this._stateAdapter,isDM:this.isDM,channelVisibility:this.channelVisibility,messageHistory:this._messageHistory})}return this._channel}get messages(){let n=this.adapter,t=this.id,r=this._messageHistory;return{async*[Symbol.asyncIterator](){let i,o=!1;for(;;){let a=await n.fetchMessages(t,{cursor:i,direction:"backward"}),s=[...a.messages].reverse();for(let u of s)o=!0,yield u;if(!a.nextCursor||a.messages.length===0)break;i=a.nextCursor}if(!o&&r){let a=await r.getMessages(t);for(let s=a.length-1;s>=0;s--)yield a[s]}}}}get allMessages(){let n=this.adapter,t=this.id,r=this._messageHistory;return{async*[Symbol.asyncIterator](){let i,o=!1;for(;;){let a=await n.fetchMessages(t,{limit:100,cursor:i,direction:"forward"});for(let s of a.messages)o=!0,yield s;if(!a.nextCursor||a.messages.length===0)break;i=a.nextCursor}if(!o&&r){let a=await r.getMessages(t);for(let s of a)yield s}}}}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(n){if(wp(n))return await this.handlePostableObject(n),n;if(qy(n))return this.handleStream(n);let t=n;if(Nt(n)){let o=Mt(n);if(!o)throw new Error("Invalid JSX element: must be a Card element");t=o}let r=await this.adapter.postMessage(this.id,t),i=this.createSentMessage(r.id,t,r.threadId);return this._messageHistory&&await this._messageHistory.append(this.id,new Un(i)),i}async handlePostableObject(n){await Sp(n,this.adapter,this.id,(t,r)=>this.adapter.postMessage(t,r),this._logger)}async postEphemeral(n,t,r){let{fallbackToDM:i}=r,o=typeof n=="string"?n:n.userId,a;if(Nt(t)){let s=Mt(t);if(!s)throw new Error("Invalid JSX element: must be a Card element");a=s}else a=t;if(this.adapter.postEphemeral)return this.adapter.postEphemeral(this.id,o,a);if(!i)return null;if(this.adapter.openDM){let s=await this.adapter.openDM(o),u=await this.adapter.postMessage(s,a);return{id:u.id,threadId:s,usedFallback:!0,raw:u.raw}}return null}async schedule(n,t){let r;if(Nt(n)){let i=Mt(n);if(!i)throw new Error("Invalid JSX element: must be a Card element");r=i}else r=n;if(!this.adapter.scheduleMessage)throw new xp("Scheduled messages are not supported by this adapter","scheduling");return this.adapter.scheduleMessage(this.id,r,t)}async handleStream(n){var o;let t=bp(n),r={};if(this._currentMessage){r.recipientUserId=this._currentMessage.author.userId;let a=this._currentMessage.raw;r.recipientTeamId=(o=a==null?void 0:a.team_id)!=null?o:a==null?void 0:a.team}if(this.adapter.stream){let a="",s={[Symbol.asyncIterator]:()=>{let d=t[Symbol.asyncIterator]();return{async next(){let h=await d.next();if(!h.done){let y=h.value;typeof y=="string"?a+=y:y.type==="markdown_text"&&(a+=y.text)}return h}}}},u=await this.adapter.stream(this.id,s,r),p=this.createSentMessage(u.id,{markdown:a},u.threadId);return this._messageHistory&&await this._messageHistory.append(this.id,new Un(p)),p}let i={[Symbol.asyncIterator]:()=>{let a=t[Symbol.asyncIterator]();return{async next(){for(;;){let s=await a.next();if(s.done)return{value:void 0,done:!0};let u=s.value;if(typeof u=="string")return{value:u,done:!1};if(u.type==="markdown_text")return{value:u.text,done:!1}}}}}};return this.fallbackStream(i,r)}async startTyping(n){await this.adapter.startTyping(this.id,n)}async fallbackStream(n,t){var j;let r=(j=t==null?void 0:t.updateIntervalMs)!=null?j:this._streamingUpdateIntervalMs,i=this._fallbackStreamingPlaceholderText,o=i===null?null:await this.adapter.postMessage(this.id,i),a=this.id,s=new Ly,u="",p=!1,d=null,h=null;o&&(a=o.threadId||this.id,u=i!=null?i:"");let y=()=>{h=setTimeout(()=>{d=g()},r)},g=async()=>{var te;if(p||!o)return;let pe=s.render();if(pe!==u)try{await this.adapter.editMessage(a,o.id,{markdown:pe}),u=pe}catch(Te){(te=this._logger)==null||te.warn("fallbackStream edit failed",Te)}p||y()};o&&y();try{for await(let pe of n)if(s.push(pe),!o){let te=s.render();o=await this.adapter.postMessage(this.id,{markdown:te}),a=o.threadId||this.id,u=te,y()}}finally{p=!0,h&&(clearTimeout(h),h=null)}d&&await d;let P=s.getText(),Z=s.finish();o||(o=await this.adapter.postMessage(this.id,{markdown:P}),a=o.threadId||this.id,u=P),Z!==u&&await this.adapter.editMessage(a,o.id,{markdown:P});let Q=this.createSentMessage(o.id,{markdown:P},a);return this._messageHistory&&await this._messageHistory.append(this.id,new Un(Q)),Q}async refresh(){let n=await this.adapter.fetchMessages(this.id,{limit:50});n.messages.length>0?this._recentMessages=n.messages:this._messageHistory?this._recentMessages=await this._messageHistory.getMessages(this.id,50):this._recentMessages=[]}mentionUser(n){return`<@${n}>`}toJSON(){var n;return{_type:"chat:Thread",id:this.id,channelId:this.channelId,channelVisibility:this.channelVisibility,currentMessage:(n=this._currentMessage)==null?void 0:n.toJSON(),isDM:this.isDM,adapterName:this.adapter.name}}static fromJSON(n,t){let r=new Is({id:n.id,adapterName:n.adapterName,channelId:n.channelId,channelVisibility:n.channelVisibility,currentMessage:n.currentMessage?Un.fromJSON(n.currentMessage):void 0,isDM:n.isDM});return t&&(r._adapter=t),r}static[Qn](n){return n.toJSON()}static[Zn](n){return Is.fromJSON(n)}createSentMessage(n,t,r){let i=this.adapter,o=r||this.id,a=this,{plainText:s,formatted:u,attachments:p}=jy(t);return{id:n,threadId:o,text:s,formatted:u,raw:null,links:[],author:{userId:"self",userName:i.userName,fullName:i.userName,isBot:!0,isMe:!0},metadata:{dateSent:new Date,edited:!1},attachments:p,toJSON(){return new Un(this).toJSON()},async edit(h){let y=h;if(Nt(h)){let g=Mt(h);if(!g)throw new Error("Invalid JSX element: must be a Card element");y=g}return await i.editMessage(o,n,y),a.createSentMessage(n,y)},async delete(){await i.deleteMessage(o,n)},async addReaction(h){await i.addReaction(o,n,h)},async removeReaction(h){await i.removeReaction(o,n,h)}}}createSentMessageFromMessage(n){let t=this.adapter,r=this.id,i=n.id,o=this;return{id:n.id,threadId:n.threadId,text:n.text,formatted:n.formatted,raw:n.raw,author:n.author,metadata:n.metadata,attachments:n.attachments,links:n.links,isMention:n.isMention,toJSON(){return n.toJSON()},async edit(a){let s=a;if(Nt(a)){let u=Mt(a);if(!u)throw new Error("Invalid JSX element: must be a Card element");s=u}return await t.editMessage(r,i,s),o.createSentMessage(i,s,r)},async delete(){await t.deleteMessage(r,i)},async addReaction(a){await t.addReaction(r,i,a)},async removeReaction(a){await t.removeReaction(r,i,a)}}}};function jy(e){if(typeof e=="string")return{plainText:e,formatted:dn([pn([un(e)])]),attachments:[]};if("raw"in e)return{plainText:e.raw,formatted:dn([pn([un(e.raw)])]),attachments:e.attachments||[]};if("markdown"in e){let n=bs(e.markdown);return{plainText:Pr(n),formatted:n,attachments:e.attachments||[]}}if("ast"in e)return{plainText:Pr(e.ast),formatted:e.ast,attachments:e.attachments||[]};if("card"in e){let n=e.fallbackText||Mr(e.card);return{plainText:n,formatted:dn([pn([un(n)])]),attachments:[]}}if("type"in e&&e.type==="card"){let n=Mr(e);return{plainText:n,formatted:dn([pn([un(n)])]),attachments:[]}}throw new Error("Invalid PostableMessage format")}var BR=300*1e3,zR=1440*60*1e3;var yp=new Map;function er(e){let n=yp.get(e);return n||(n=Object.freeze({name:e,toString:()=>`{{emoji:${e}}}`,toJSON:()=>`{{emoji:${e}}}`}),yp.set(e,n)),n}var By={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}"}},zy=class{constructor(e){Ee(this,"emojiMap");Ee(this,"slackToNormalized");Ee(this,"gchatToNormalized");this.emojiMap={...By,...e},this.slackToNormalized=new Map,this.gchatToNormalized=new Map,this.buildReverseMaps()}buildReverseMaps(){for(let[e,n]of Object.entries(this.emojiMap)){let t=Array.isArray(n.slack)?n.slack:[n.slack];for(let i of t)this.slackToNormalized.set(i.toLowerCase(),e);let r=Array.isArray(n.gchat)?n.gchat:[n.gchat];for(let i of r)this.gchatToNormalized.set(i,e)}}fromSlack(e){var r;let n=e.replace(/^:|:$/g,"").toLowerCase(),t=(r=this.slackToNormalized.get(n))!=null?r:e;return er(t)}fromGChat(e){var t;let n=(t=this.gchatToNormalized.get(e))!=null?t:e;return er(n)}fromTeams(e){var r;let t=(r={like:"thumbs_up",heart:"heart",laugh:"laugh",surprised:"surprised",sad:"sad",angry:"angry"}[e])!=null?r:e;return er(t)}toSlack(e){let n=typeof e=="string"?e:e.name,t=this.emojiMap[n];return t?Array.isArray(t.slack)?t.slack[0]:t.slack:n}toGChat(e){let n=typeof e=="string"?e:e.name,t=this.emojiMap[n];return t?Array.isArray(t.gchat)?t.gchat[0]:t.gchat:n}toDiscord(e){return this.toGChat(e)}matches(e,n){let t=typeof n=="string"?n:n.name,r=this.emojiMap[t];if(!r)return e===t;let i=Array.isArray(r.slack)?r.slack:[r.slack],o=Array.isArray(r.gchat)?r.gchat:[r.gchat],a=e.replace(/^:|:$/g,"").toLowerCase();return i.some(s=>s.toLowerCase()===a)||o.includes(e)}extend(e){Object.assign(this.emojiMap,e),this.buildReverseMaps()}},Vy=new zy;function Wy(e){let n=["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"],t={custom:r=>er(r)};for(let r of n)t[r]=er(r);if(e){for(let r of Object.keys(e))t[r]=er(r);Vy.extend(e)}return t}var VR=Wy(),Cs=na,Ps=ra,Ms=ws;var Ns=ia,Ls=Ju,Ds=ta;var Fs=oa,Us=sa,$s=aa;function Hy(e){return"type"in e&&e.type==="card"}function Tp(e){var n;if(typeof e=="string")return{text:e};if(Nt(e)){let t=Mt(e);if(t)return{card:t}}if(Hy(e))return{card:e};if("markdown"in e&&typeof e.markdown=="string"){let t={markdown:e.markdown};return(n=e.files)!=null&&n.length&&(t.files=e.files),t}throw new Error("Invalid message content \u2014 expected string, { markdown }, or CardElement")}var Lr=class{constructor(n,t){this._signals=[];this._resolveSignal=null;var r;this.event=n.event,this.action=(r=n.action)!=null?r:null,this.message=n.message,this.reaction=n.reaction,this.conversation=n.conversation,this.subscriber=n.subscriber,this.history=n.history,this.platform=n.platform,this.platformContext=n.platformContext,this._replyUrl=n.replyUrl,this._conversationId=n.conversationId,this._integrationIdentifier=n.integrationIdentifier,this._secretKey=t,this.metadata={set:(i,o)=>{this._signals.push({type:"metadata",key:i,value:o})}}}async reply(n){let t={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,reply:Tp(n)};this._signals.length&&(t.signals=this._signals,this._signals=[]),this._resolveSignal&&(t.resolve=this._resolveSignal,this._resolveSignal=null),await this._post(t)}async update(n){let t={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier,update:Tp(n)};await this._post(t)}resolve(n){this._resolveSignal={summary:n}}trigger(n,t){this._signals.push({type:"trigger",workflowId:n,...t})}async flush(){if(!this._signals.length&&!this._resolveSignal)return;let n={conversationId:this._conversationId,integrationIdentifier:this._integrationIdentifier};this._signals.length&&(n.signals=this._signals,this._signals=[]),this._resolveSignal&&(n.resolve=this._resolveSignal,this._resolveSignal=null),await this._post(n)}async _post(n){let t=await fetch(this._replyUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${this._secretKey}`},body:JSON.stringify(n)});if(!t.ok){let r=await t.text().catch(()=>"");throw new Error(`Agent reply failed (${t.status}): ${r}`)}}};function qs(e,n){if(!e)throw new Error("agent() requires a non-empty agentId");if(!(n!=null&&n.onMessage))throw new Error(`agent('${e}') requires an onMessage handler`);return{id:e,handlers:n}}var pa=(i=>(i.ON_MESSAGE="onMessage",i.ON_ACTION="onAction",i.ON_RESOLVE="onResolve",i.ON_REACTION="onReaction",i))(pa||{});var da=class{constructor(n){this.handler=n.handler,this.client=n.client?n.client:new Hn,this.workflows=n.workflows||[],this.agents=n.agents||[],this.http=Si(this.client.secretKey,this.client.apiUrl),this.frameworkName=n.frameworkName,this.hmacEnabled=this.client.strictAuthentication,this.client.addAgents(this.agents)}createHandler(){return async(...n)=>{await this.client.addWorkflows(this.workflows);let t=await this.handler(...n),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let n=`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.10.1-alpha.1","novu-framework-server":this.frameworkName,"user-agent":n}}createResponse(n,t){return{status:n,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(n){return{status:n.statusCode,body:JSON.stringify({message:n.message,data:n.data,code:n.code}),headers:this.getStaticHeaders()}}async handleAction({actions:n}){let t=await n.url(),r=await n.method(),i=t.searchParams.get("action")||"health-check",o=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",s=t.searchParams.get("agentId")||"",u=t.searchParams.get("event")||"",p=await n.headers("novu-signature")||"",d={};try{r==="POST"&&(d=await n.body())}catch{}try{i!=="health-check"&&await this.validateHmac(d,p);let h=this.getPostActionMap(d,o,a,i,s,u,n.waitUntil),y=this.getGetActionMap(o,a);if(r==="POST")return await this.handlePostAction(i,h);if(r==="GET")return await this.handleGetAction(i,y);if(r==="OPTIONS")return this.createResponse(200,{})}catch(h){return this.handleError(h)}return this.createError(new si(r))}getPostActionMap(n,t,r,i,o,a,s){return{trigger:this.triggerAction({workflowId:t,...n}),execute:async()=>{let u=await this.client.executeWorkflow({...n,workflowId:t,stepId:r,action:i});return this.createResponse(200,u)},preview:async()=>{let u=await this.client.executeWorkflow({...n,workflowId:t,stepId:r,action:i});return this.createResponse(200,u)},"agent-event":async()=>{let u=this.client.getAgent(o);if(!u)return this.createResponse(404,{error:`Agent '${o}' not registered`});let p=new Lr(n,this.client.secretKey),d=this.runAgentHandler(u,a,p).catch(h=>{console.error(`[agent:${o}] Handler error:`,h)});return s&&s(d),this.createResponse(200,{status:"ack"})}}}triggerAction(n){return async()=>{let t={name:n.workflowId,to:n.to,payload:(n==null?void 0:n.payload)||{},transactionId:n.transactionId,overrides:n.overrides||{},...n.actor&&{actor:n.actor},...n.bridgeUrl&&{bridgeUrl:n.bridgeUrl},...n.controls&&{controls:n.controls},...n.context&&{context:n.context}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(n,t){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(n,t);return this.createResponse(200,r)}}}async handlePostAction(n,t){if(Object.values(fr).includes(n)){let r=t[n];return r()}else throw new zn(n,fr)}async handleGetAction(n,t){if(Object.values(Jr).includes(n)){let r=t[n];return r()}else throw new zn(n,Jr)}async runAgentHandler(n,t,r){let i={onMessage:n.handlers.onMessage,onReaction:n.handlers.onReaction,onAction:n.handlers.onAction,onResolve:n.handlers.onResolve};if(!Object.prototype.hasOwnProperty.call(i,t))throw new zn(t,pa);let o=i[t];o&&await o(r),await r.flush()}handleError(n){if(On(n))return n.statusCode>=500&&console.error(n),this.createError(n);if(Bl(n))return this.createError(n);{let t=new Bn(n);return console.error(t),this.createError(t)}}async validateHmac(n,t){if(!this.hmacEnabled)return;if(!t)throw new hi;if(!this.client.secretKey)throw new gi;let[r,i]=t.split(",");if(!r||!i)throw new fi;let[o,a]=r.split("="),[s,u]=i.split("=");if(Number(o)<Date.now()-1500)throw new mi;if(!(await Xl(this.client.secretKey,`${a}.${JSON.stringify(n)}`)===u))throw new di}};var ue={output:{type:"object",properties:{},required:[],additionalProperties:!0}};var Jy={type:"object",properties:{webhookUrl:{type:"string",format:"uri"},text:{type:"string"},blocks:{type:"array",items:{type:"object",properties:{type:{enum:["image","context","actions","divider","section","input","file","header","video","rich_text"]}},required:["type"],additionalProperties:!0}}},additionalProperties:!0},kp={output:Jy};var vp={"chat-webhook":ue,discord:ue,getstream:ue,"grafana-on-call":ue,mattermost:ue,msteams:ue,"rocket-chat":ue,ryver:ue,slack:kp,"whatsapp-business":ue,zulip:ue};var Gy={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},Ep={output:Gy};var $n={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},Ky={type:"object",properties:{contentType:{type:"string"},filename:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},Xy={type:"object",properties:{filename:{type:"string"},contentType:{type:"string"},contentId:{type:"string"},base64Content:{type:"string"}},required:["ContentType","Filename","Base64Content"],additionalProperties:!0},Qy={type:"object",properties:{from:$n,sender:$n,to:{type:"array",items:$n},cc:{type:"array",items:$n},bcc:{type:"array",items:$n},replyTo:$n,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:$n,templateErrorDeliver:{type:"boolean"},attachments:{type:"array",items:Ky},inlineAttachments:{type:"array",items:Xy},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},Ap={output:Qy};var Vt={type:"object",properties:{address:{type:"string"},name:{type:"string"}},additionalProperties:!0},ha={type:"object",properties:{content:{type:"string"},path:{type:"string"}},additionalProperties:!0},Zy={type:"object",properties:{from:{anyOf:[{type:"string"},Vt]},sender:{anyOf:[{type:"string"},Vt]},to:{anyOf:[{type:"string"},Vt,{type:"array",items:Vt}]},cc:{anyOf:[{type:"string"},Vt,{type:"array",items:Vt}]},bcc:{anyOf:[{type:"string"},Vt,{type:"array",items:Vt}]},replyTo:{anyOf:[{type:"string"},Vt,{type:"array",items:Vt}]},inReplyTo:{anyOf:[{type:"string"},Vt]},references:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},subject:{type:"string"},text:{anyOf:[{type:"string"},ha]},html:{anyOf:[{type:"string"},ha]},watchHtml:{anyOf:[{type:"string"},ha]},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"},ha]}}}]},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},Op={output:Zy};var eb={type:"object",properties:{},required:[],additionalProperties:!1},_p={output:eb};var tb={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},Rp={output:tb};var Ip={braze:ue,clickatell:ue,nodemailer:Op,emailjs:ue,"email-webhook":ue,"infobip-email":ue,mailersend:ue,mailgun:Ep,mailjet:Ap,mailtrap:ue,mandrill:ue,netcore:ue,"novu-email":_p,outlook365:ue,plunk:ue,postmark:ue,resend:ue,sendgrid:Rp,sendinblue:ue,ses:ue,sparkpost:ue};var nb={type:"object",properties:{},required:[],additionalProperties:!1},Cp={output:nb};var Pp={novu:Cp};var Mp={anyOf:[{type:"string"},{type:"object",additionalProperties:!0,properties:{name:{type:"string"},volume:{type:"number"},critical:{type:"number"}},required:["name","volume","critical"]}]},rb={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:
|
|
152
152
|
|
|
153
153
|
10 - The push notification is sent to the device immediately. (Default)
|
|
154
154
|
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.
|