@novu/framework 2.1.0 → 2.1.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/{handler-8vDLpUDh.d.ts → handler-_mH7Q42O.d.ts} +2686 -2668
- package/dist/index.d.ts +2 -2
- package/dist/index.js +21 -19
- package/dist/servers/express.d.ts +1 -1
- package/dist/servers/express.js +1 -1
- package/dist/servers/h3.d.ts +1 -1
- package/dist/servers/h3.js +1 -1
- package/dist/servers/lambda.d.ts +1 -1
- package/dist/servers/lambda.js +1 -1
- package/dist/servers/next.d.ts +1 -1
- package/dist/servers/next.js +1 -1
- package/dist/servers/nuxt.d.ts +1 -1
- package/dist/servers/nuxt.js +1 -1
- package/dist/servers/remix.d.ts +1 -1
- package/dist/servers/remix.js +1 -1
- package/dist/servers/sveltekit.d.ts +1 -1
- package/dist/servers/sveltekit.js +1 -1
- package/package.json +6 -4
package/dist/servers/h3.js
CHANGED
|
@@ -21,7 +21,7 @@ var Ie__default = /*#__PURE__*/_interopDefault(Ie);
|
|
|
21
21
|
var Me__default = /*#__PURE__*/_interopDefault(Me);
|
|
22
22
|
var Ve__default = /*#__PURE__*/_interopDefault(Ve);
|
|
23
23
|
|
|
24
|
-
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),V=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(V||{});var u=(n=>(n.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",n.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",n.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",n.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",n.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",n.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",n.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",n.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",n.STEP_NOT_FOUND_ERROR="StepNotFoundError",n.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",n.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",n.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",n.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",n.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",n.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",n.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",n.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",n.INVALID_ACTION_ERROR="InvalidActionError",n.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",n.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",n.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",n.SIGNATURE_INVALID_ERROR="SignatureInvalidError",n.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",n.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",n.BRIDGE_ERROR="BridgeError",n.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",n.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",n))(u||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var Te="2.1.0";var y=Te,F="2024-06-26";var E=class extends Error{data},L=class extends E{statusCode=404},R=class extends E{statusCode=400},m=class extends E{statusCode=401},f=class extends E{statusCode=500},C=class extends E{statusCode=409};var b=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},P=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:o=>N__default.default.blue(o),warning:o=>N__default.default.yellow(o),error:o=>N__default.default.red(o),success:o=>N__default.default.green(o),underline:o=>N__default.default.underline(o),bold:o=>N__default.default.bold(o)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var ue=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var xe={allowedTags:Ie__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},me=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=Ie__default.default(o,xe);return t?t[0]+r:r},q=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=me(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?me(s):typeof s=="object"?q(s):s):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ue(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ue(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Me__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=fe(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(o,e)=>{if(ce.canHandle(o))return ce.validate(e,o);if(de.canHandle(o))return de.validate(e,o);throw new Error("Invalid schema")},ve=o=>{if(ce.canHandle(o))return ce.transformToJsonSchema(o);if(de.canHandle(o))return de.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Le(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=y;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Le()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:y,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,s,i,a,d){let c=await Ne(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(s,i,c.errors);case"step":this.throwInvalidStep(a,s,i,c.errors);case"provider":this.throwInvalidProvider(a,d,s,i,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,s);case"result":throw new j(r,e,s);case"controls":throw new $(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new P(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let a=this.getStep(e.workflowId,r),d=await this.createStepControls(a,e),c=e.action==="preview";if(!c&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),_=this.executeStep.bind(this),T=await(c?O:_)(e,{...a,providers:a.providers.map(S=>{let M=i?.providers?.[S.type];if(!M)throw new Z(S.type);return {...S,resolve:M}}),resolve:s});return Object.values(Re).includes(a.type)&&(T={...T,outputs:q(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
24
|
+
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),V=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(V||{});var u=(n=>(n.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",n.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",n.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",n.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",n.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",n.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",n.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",n.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",n.STEP_NOT_FOUND_ERROR="StepNotFoundError",n.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",n.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",n.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",n.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",n.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",n.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",n.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",n.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",n.INVALID_ACTION_ERROR="InvalidActionError",n.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",n.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",n.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",n.SIGNATURE_INVALID_ERROR="SignatureInvalidError",n.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",n.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",n.BRIDGE_ERROR="BridgeError",n.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",n.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",n))(u||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var Te="2.1.1";var y=Te,F="2024-06-26";var E=class extends Error{data},L=class extends E{statusCode=404},R=class extends E{statusCode=400},m=class extends E{statusCode=401},f=class extends E{statusCode=500},C=class extends E{statusCode=409};var b=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},P=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:o=>N__default.default.blue(o),warning:o=>N__default.default.yellow(o),error:o=>N__default.default.red(o),success:o=>N__default.default.green(o),underline:o=>N__default.default.underline(o),bold:o=>N__default.default.bold(o)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var ue=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var xe={allowedTags:Ie__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},me=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=Ie__default.default(o,xe);return t?t[0]+r:r},q=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=me(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?me(s):typeof s=="object"?q(s):s):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ue(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ue(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Me__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=fe(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(o,e)=>{if(ce.canHandle(o))return ce.validate(e,o);if(de.canHandle(o))return de.validate(e,o);throw new Error("Invalid schema")},ve=o=>{if(ce.canHandle(o))return ce.transformToJsonSchema(o);if(de.canHandle(o))return de.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Le(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=y;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Le()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:y,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,s,i,a,d){let c=await Ne(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(s,i,c.errors);case"step":this.throwInvalidStep(a,s,i,c.errors);case"provider":this.throwInvalidProvider(a,d,s,i,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,s);case"result":throw new j(r,e,s);case"controls":throw new $(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new P(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let a=this.getStep(e.workflowId,r),d=await this.createStepControls(a,e),c=e.action==="preview";if(!c&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),_=this.executeStep.bind(this),T=await(c?O:_)(e,{...a,providers:a.providers.map(S=>{let M=i?.providers?.[S.type];if(!M)throw new Z(S.type);return {...S,resolve:M}}),resolve:s});return Object.values(Re).includes(a.type)&&(T={...T,outputs:q(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
25
25
|
${l.bold(l.underline(s))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},c,O=new Promise(h=>{c=h;}),_=h=>{c(),d=h;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new P(e.workflowId,{message:"Event `payload` is required"});let h=await this.createExecutionPayload(e,i),A={...e,payload:h};await Promise.race([O,i.execute({payload:h,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(A,_),sms:this.executeStepFactory(A,_),inApp:this.executeStepFactory(A,_),digest:this.executeStepFactory(A,_),delay:this.executeStepFactory(A,_),push:this.executeStepFactory(A,_),chat:this.executeStepFactory(A,_),custom:this.executeStepFactory(A,_)}})]);}catch(h){w=h;}let T=process.hrtime(a),S=T[0],M=T[1],Oe=S*1e3+M/1e6,Se=w?p.ERROR:p.SUCCESS,De=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Se} ${De} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Oe,w),w)throw w;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:Oe}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let s=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":i,d=r?l.error:l.success,c=`${s} ${a} workflowId: '${e.workflowId}`;console.log(`
|
|
26
26
|
${l.bold(d(c))}'`),console.log(` \u251C ${p.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${p.ACTION} action: '${e.action}'`),console.log(` \u2514 ${p.DURATION} duration: '${t.toFixed(2)}ms'
|
|
27
27
|
`);}async executeProviders(e,t,r){return t.providers.reduce(async(s,i)=>{let a=await s,d=this.previewProvider.bind(this),c=this.executeProvider.bind(this),_=await(e.action==="preview"?d:c)(e,t,i,r);return {...a,[i.type]:_}},Promise.resolve({}))}previewProvider(e,t,r,s){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,s){let i=le__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let a=await this.createStepControls(t,e),d=await r.resolve({controls:a,outputs:s}),c=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...c,_passthrough:d._passthrough}}else return i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(a){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new Q(`Failed to execute provider: '${r.type}'.
|
package/dist/servers/lambda.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as aws_lambda from 'aws-lambda';
|
|
2
2
|
import { APIGatewayProxyEventV2, APIGatewayProxyResult } from 'aws-lambda';
|
|
3
|
-
import {
|
|
3
|
+
import { w as SupportedFrameworkName, c as ServeHandlerOptions, ag as Either } from '../handler-_mH7Q42O.js';
|
|
4
4
|
import '@novu/shared';
|
|
5
5
|
import 'json-schema-to-ts';
|
|
6
6
|
import 'zod';
|
package/dist/servers/lambda.js
CHANGED
|
@@ -20,7 +20,7 @@ var me__default = /*#__PURE__*/_interopDefault(me);
|
|
|
20
20
|
var ke__default = /*#__PURE__*/_interopDefault(ke);
|
|
21
21
|
var Ve__default = /*#__PURE__*/_interopDefault(Ve);
|
|
22
22
|
|
|
23
|
-
var S=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(S||{}),M=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(M||{});var _=(c=>(c.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",c.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",c.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",c.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",c.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",c.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",c.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",c.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",c.STEP_NOT_FOUND_ERROR="StepNotFoundError",c.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",c.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",c.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",c.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",c.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",c.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",c.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",c.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",c.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",c.SIGNATURE_INVALID_ERROR="SignatureInvalidError",c.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",c.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",c.BRIDGE_ERROR="BridgeError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",c))(_||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var he="2.1.0";var P=he,F="2024-06-26";var E=class extends Error{data},C=class extends E{statusCode=404},R=class extends E{statusCode=400},I=class extends E{statusCode=401},f=class extends E{statusCode=500},b=class extends E{statusCode=409};var L=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},D=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:s=>N__default.default.blue(s),warning:s=>N__default.default.yellow(s),error:s=>N__default.default.red(s),success:s=>N__default.default.green(s),underline:s=>N__default.default.underline(s),bold:s=>N__default.default.bold(s)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var _e=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),J=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(s,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,o)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`},body:JSON.stringify(o)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`}})).json()}};var De={allowedTags:me__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=s=>{if(!s)return s;let e=/^<!DOCTYPE .*?>/,t=s.match(e),r=me__default.default(s,De);return t?t[0]+r:r},q=s=>Object.keys(s).reduce((e,t)=>{let r=s[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(o=>typeof o=="string"?Ie(o):typeof o=="object"?q(o):o):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${_e(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${_e(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends b{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},m=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends m{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends I{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends I{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends I{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends I{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends I{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends m{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends m{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=s=>typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new ke__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let o=fe(e);return r(o)?{success:!0,data:o}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(o=>({path:`/${o.path.join("/")}`,message:o.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(s,e)=>{if(ce.canHandle(s))return ce.validate(e,s);if(de.canHandle(s))return de.validate(e,s);throw new Error("Invalid schema")},ve=s=>{if(ce.canHandle(s))return ce.transformToJsonSchema(s);if(de.canHandle(s))return de.transformToJsonSchema(s);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Fe(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=P;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Fe()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:P,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,o,i,a,n){let d=await Ne(t,e);if(d.success)return d.data;switch(r){case"event":this.throwInvalidEvent(o,i,d.errors);case"step":this.throwInvalidStep(a,o,i,d.errors);case"provider":this.throwInvalidProvider(a,n,o,i,d.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,o,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(o,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,o){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,o);case"result":throw new j(r,e,o);case"controls":throw new $(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new D(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let a=this.getStep(e.workflowId,r),n=await this.createStepControls(a,e),d=e.action==="preview";if(!d&&await this.shouldSkip(i?.skip,n))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),u=this.executeStep.bind(this),h=await(d?O:u)(e,{...a,providers:a.providers.map(y=>{let V=i?.providers?.[y.type];if(!V)throw new Z(y.type);return {...y,resolve:V}}),resolve:o});return Object.values(Re).includes(a.type)&&(h={...h,outputs:q(h.outputs)}),r===e.stepId&&t({...h,options:{skip:!1}}),h.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
23
|
+
var S=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(S||{}),M=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(M||{});var _=(c=>(c.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",c.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",c.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",c.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",c.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",c.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",c.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",c.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",c.STEP_NOT_FOUND_ERROR="StepNotFoundError",c.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",c.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",c.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",c.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",c.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",c.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",c.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",c.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",c.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",c.SIGNATURE_INVALID_ERROR="SignatureInvalidError",c.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",c.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",c.BRIDGE_ERROR="BridgeError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",c))(_||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var he="2.1.1";var P=he,F="2024-06-26";var E=class extends Error{data},C=class extends E{statusCode=404},R=class extends E{statusCode=400},I=class extends E{statusCode=401},f=class extends E{statusCode=500},b=class extends E{statusCode=409};var L=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},D=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:s=>N__default.default.blue(s),warning:s=>N__default.default.yellow(s),error:s=>N__default.default.red(s),success:s=>N__default.default.green(s),underline:s=>N__default.default.underline(s),bold:s=>N__default.default.bold(s)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var _e=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),J=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(s,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,o)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`},body:JSON.stringify(o)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`}})).json()}};var De={allowedTags:me__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=s=>{if(!s)return s;let e=/^<!DOCTYPE .*?>/,t=s.match(e),r=me__default.default(s,De);return t?t[0]+r:r},q=s=>Object.keys(s).reduce((e,t)=>{let r=s[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(o=>typeof o=="string"?Ie(o):typeof o=="object"?q(o):o):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${_e(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${_e(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends b{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},m=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends m{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends I{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends I{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends I{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends I{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends I{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends m{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends m{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=s=>typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new ke__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let o=fe(e);return r(o)?{success:!0,data:o}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(o=>({path:`/${o.path.join("/")}`,message:o.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(s,e)=>{if(ce.canHandle(s))return ce.validate(e,s);if(de.canHandle(s))return de.validate(e,s);throw new Error("Invalid schema")},ve=s=>{if(ce.canHandle(s))return ce.transformToJsonSchema(s);if(de.canHandle(s))return de.transformToJsonSchema(s);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Fe(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=P;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Fe()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:P,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,o,i,a,n){let d=await Ne(t,e);if(d.success)return d.data;switch(r){case"event":this.throwInvalidEvent(o,i,d.errors);case"step":this.throwInvalidStep(a,o,i,d.errors);case"provider":this.throwInvalidProvider(a,n,o,i,d.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,o,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(o,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,o){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,o);case"result":throw new j(r,e,o);case"controls":throw new $(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new D(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let a=this.getStep(e.workflowId,r),n=await this.createStepControls(a,e),d=e.action==="preview";if(!d&&await this.shouldSkip(i?.skip,n))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),u=this.executeStep.bind(this),h=await(d?O:u)(e,{...a,providers:a.providers.map(y=>{let V=i?.providers?.[y.type];if(!V)throw new Z(y.type);return {...y,resolve:V}}),resolve:o});return Object.values(Re).includes(a.type)&&(h={...h,outputs:q(h.outputs)}),r===e.stepId&&t({...h,options:{skip:!1}}),h.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
24
24
|
${l.bold(l.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),n={outputs:{},providers:{},options:{skip:!1}},d,O=new Promise(T=>{d=T;}),u=T=>{d(),n=T;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new D(e.workflowId,{message:"Event `payload` is required"});let T=await this.createExecutionPayload(e,i),A={...e,payload:T};await Promise.race([O,i.execute({payload:T,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(A,u),sms:this.executeStepFactory(A,u),inApp:this.executeStepFactory(A,u),digest:this.executeStepFactory(A,u),delay:this.executeStepFactory(A,u),push:this.executeStepFactory(A,u),chat:this.executeStepFactory(A,u),custom:this.executeStepFactory(A,u)}})]);}catch(T){w=T;}let h=process.hrtime(a),y=h[0],V=h[1],Oe=y*1e3+V/1e6,ge=w?p.ERROR:p.SUCCESS,ye=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${ge} ${ye} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Oe,w),w)throw w;return {outputs:n.outputs,providers:n.providers,options:n.options,metadata:{status:"success",error:!1,duration:Oe}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let o=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":i,n=r?l.error:l.success,d=`${o} ${a} workflowId: '${e.workflowId}`;console.log(`
|
|
25
25
|
${l.bold(n(d))}'`),console.log(` \u251C ${p.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${p.ACTION} action: '${e.action}'`),console.log(` \u2514 ${p.DURATION} duration: '${t.toFixed(2)}ms'
|
|
26
26
|
`);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let a=await o,n=this.previewProvider.bind(this),d=this.executeProvider.bind(this),u=await(e.action==="preview"?n:d)(e,t,i,r);return {...a,[i.type]:u}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=le__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let a=await this.createStepControls(t,e),n=await r.resolve({controls:a,outputs:o}),d=await this.validate(n,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...d,_passthrough:n._passthrough}}else return i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(a){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new Q(`Failed to execute provider: '${r.type}'.
|
package/dist/servers/next.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextApiResponse } from 'next';
|
|
2
2
|
import { NextRequest } from 'next/server';
|
|
3
|
-
import {
|
|
3
|
+
import { w as SupportedFrameworkName, c as ServeHandlerOptions } from '../handler-_mH7Q42O.js';
|
|
4
4
|
import '@novu/shared';
|
|
5
5
|
import 'json-schema-to-ts';
|
|
6
6
|
import 'zod';
|
package/dist/servers/next.js
CHANGED
|
@@ -20,7 +20,7 @@ var fe__default = /*#__PURE__*/_interopDefault(fe);
|
|
|
20
20
|
var Ve__default = /*#__PURE__*/_interopDefault(Ve);
|
|
21
21
|
var Ye__default = /*#__PURE__*/_interopDefault(Ye);
|
|
22
22
|
|
|
23
|
-
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),Y=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(Y||{});var h=(l=>(l.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",l.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",l.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",l.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",l.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",l.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",l.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",l.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",l.STEP_NOT_FOUND_ERROR="StepNotFoundError",l.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",l.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",l.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",l.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",l.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",l.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",l.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",l.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",l.INVALID_ACTION_ERROR="InvalidActionError",l.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",l.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",l.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",l.SIGNATURE_INVALID_ERROR="SignatureInvalidError",l.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",l.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",l.BRIDGE_ERROR="BridgeError",l.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",l.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",l))(h||{});var F=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(F||{});var _e=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(_e||{});var Te="2.1.0";var x=Te,L="2024-06-26";var A=class extends Error{data},b=class extends A{statusCode=404},E=class extends A{statusCode=400},N=class extends A{statusCode=401},g=class extends A{statusCode=500},C=class extends A{statusCode=409};var W=class extends E{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},U=class extends E{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},$=class extends E{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},G=class extends E{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},j=class extends E{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},K=class extends E{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},q=class extends E{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends E{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends A{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var Ae=()=>typeof Response<"u"?Response:crossFetch.Response;var p={info:o=>S__default.default.blue(o),warning:o=>S__default.default.yellow(o),error:o=>S__default.default.red(o),success:o=>S__default.default.green(o),underline:o=>S__default.default.underline(o),bold:o=>S__default.default.bold(o)},_={SUCCESS:p.success("\u2714"),ERROR:p.error("\u2717"),WARNING:p.warning("\u26A0"),INFO:p.info("\u2139"),ARROW:p.bold("\u2192"),MOCK:p.info("\u25CB"),HYDRATED:p.bold(p.info("\u2192")),STEP:p.info("\u03C3"),ACTION:p.info("\u03B1"),DURATION:p.info("\u0394"),PROVIDER:p.info("\u2699"),OUTPUT:p.info("\u21E2"),INPUT:p.info("\u21E0"),WORKFLOW:p.info("\u03C9"),STATE:p.info("\u03C3"),EXECUTE:p.info("\u03B5"),PREVIEW:p.info("\u03C1")};var Oe=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var me=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),n=await i.json();if(i.ok)return n;throw shared.checkIsResponseError(n)?new X(n.statusCode,n.error,n.message):new y("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var Ue={allowedTags:fe__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=fe__default.default(o,Ue);return t?t[0]+r:r},z=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?Ie(s):typeof s=="object"?z(s):s):typeof r=="object"&&r!==null?e[t]=z(r):e[t]=r,e},{});var Z=class extends A{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Oe(F)}`},k=class extends E{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Oe(t)}`);}};var y=class extends g{code="BridgeError";message="Something went wrong. Please try again later."};var M=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},v=class extends b{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},P=class extends g{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Q=class extends v{code="ProviderNotFoundError";constructor(e){super("provider",e);}},H=class extends P{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var ee=class extends N{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},te=class extends N{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},re=class extends N{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},oe=class extends N{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},se=class extends N{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var ie=class extends v{code="StepNotFoundError";constructor(e){super("step",e);}};var V=class extends v{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ne=class extends M{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var Ne=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Ve__default.default({useDefaults:!0,removeAdditional:"failing"}),Ye__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=Ne(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(n=>({path:n.instancePath,message:n.message}))}}transformToJsonSchema(e){return e}};var ce=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var de=new ce,le=new ae,ve=async(o,e)=>{if(de.canHandle(o))return de.validate(e,o);if(le.canHandle(o))return le.validate(e,o);throw new Error("Invalid schema")},ge=o=>{if(de.canHandle(o))return de.transformToJsonSchema(o);if(le.canHandle(o))return le.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function be(){return ["development",void 0].includes(process.env.NODE_ENV)}var ue=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=x;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!be()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ne(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:x,frameworkVersion:L,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new V(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new ie(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ge(e))}async validate(e,t,r,s,i,n,d){let a=await ve(t,e);if(a.success)return a.data;switch(r){case"event":this.throwInvalidEvent(s,i,a.errors);case"step":this.throwInvalidStep(n,s,i,a.errors);case"provider":this.throwInvalidProvider(n,d,s,i,a.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new j(r,e,s);case"result":throw new K(r,e,s);case"controls":throw new G(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new $(t,r);case"payload":throw new U(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let n=this.getStep(e.workflowId,r),d=await this.createStepControls(n,e),a=e.action==="preview";if(!a&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),c=this.executeStep.bind(this),R=await(a?O:c)(e,{...n,providers:n.providers.map(I=>{let T=i?.providers?.[I.type];if(!T)throw new Q(I.type);return {...I,resolve:T}}),resolve:s});return Object.values(_e).includes(n.type)&&(R={...R,outputs:z(R.outputs)}),r===e.stepId&&t({...R,options:{skip:!1}}),R.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
23
|
+
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),Y=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(Y||{});var h=(l=>(l.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",l.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",l.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",l.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",l.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",l.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",l.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",l.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",l.STEP_NOT_FOUND_ERROR="StepNotFoundError",l.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",l.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",l.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",l.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",l.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",l.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",l.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",l.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",l.INVALID_ACTION_ERROR="InvalidActionError",l.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",l.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",l.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",l.SIGNATURE_INVALID_ERROR="SignatureInvalidError",l.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",l.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",l.BRIDGE_ERROR="BridgeError",l.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",l.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",l))(h||{});var F=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(F||{});var _e=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(_e||{});var Te="2.1.1";var x=Te,L="2024-06-26";var A=class extends Error{data},b=class extends A{statusCode=404},E=class extends A{statusCode=400},N=class extends A{statusCode=401},g=class extends A{statusCode=500},C=class extends A{statusCode=409};var W=class extends E{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},U=class extends E{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},$=class extends E{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},G=class extends E{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},j=class extends E{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},K=class extends E{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},q=class extends E{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends E{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends A{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var Ae=()=>typeof Response<"u"?Response:crossFetch.Response;var p={info:o=>S__default.default.blue(o),warning:o=>S__default.default.yellow(o),error:o=>S__default.default.red(o),success:o=>S__default.default.green(o),underline:o=>S__default.default.underline(o),bold:o=>S__default.default.bold(o)},_={SUCCESS:p.success("\u2714"),ERROR:p.error("\u2717"),WARNING:p.warning("\u26A0"),INFO:p.info("\u2139"),ARROW:p.bold("\u2192"),MOCK:p.info("\u25CB"),HYDRATED:p.bold(p.info("\u2192")),STEP:p.info("\u03C3"),ACTION:p.info("\u03B1"),DURATION:p.info("\u0394"),PROVIDER:p.info("\u2699"),OUTPUT:p.info("\u21E2"),INPUT:p.info("\u21E0"),WORKFLOW:p.info("\u03C9"),STATE:p.info("\u03C3"),EXECUTE:p.info("\u03B5"),PREVIEW:p.info("\u03C1")};var Oe=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var me=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),n=await i.json();if(i.ok)return n;throw shared.checkIsResponseError(n)?new X(n.statusCode,n.error,n.message):new y("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var Ue={allowedTags:fe__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=fe__default.default(o,Ue);return t?t[0]+r:r},z=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?Ie(s):typeof s=="object"?z(s):s):typeof r=="object"&&r!==null?e[t]=z(r):e[t]=r,e},{});var Z=class extends A{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Oe(F)}`},k=class extends E{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Oe(t)}`);}};var y=class extends g{code="BridgeError";message="Something went wrong. Please try again later."};var M=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},v=class extends b{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},P=class extends g{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Q=class extends v{code="ProviderNotFoundError";constructor(e){super("provider",e);}},H=class extends P{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var ee=class extends N{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},te=class extends N{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},re=class extends N{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},oe=class extends N{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},se=class extends N{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var ie=class extends v{code="StepNotFoundError";constructor(e){super("step",e);}};var V=class extends v{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ne=class extends M{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var Ne=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Ve__default.default({useDefaults:!0,removeAdditional:"failing"}),Ye__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=Ne(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(n=>({path:n.instancePath,message:n.message}))}}transformToJsonSchema(e){return e}};var ce=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var de=new ce,le=new ae,ve=async(o,e)=>{if(de.canHandle(o))return de.validate(e,o);if(le.canHandle(o))return le.validate(e,o);throw new Error("Invalid schema")},ge=o=>{if(de.canHandle(o))return de.transformToJsonSchema(o);if(le.canHandle(o))return le.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function be(){return ["development",void 0].includes(process.env.NODE_ENV)}var ue=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=x;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!be()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ne(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:x,frameworkVersion:L,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new V(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new ie(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ge(e))}async validate(e,t,r,s,i,n,d){let a=await ve(t,e);if(a.success)return a.data;switch(r){case"event":this.throwInvalidEvent(s,i,a.errors);case"step":this.throwInvalidStep(n,s,i,a.errors);case"provider":this.throwInvalidProvider(n,d,s,i,a.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new j(r,e,s);case"result":throw new K(r,e,s);case"controls":throw new G(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new $(t,r);case"payload":throw new U(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let n=this.getStep(e.workflowId,r),d=await this.createStepControls(n,e),a=e.action==="preview";if(!a&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),c=this.executeStep.bind(this),R=await(a?O:c)(e,{...n,providers:n.providers.map(I=>{let T=i?.providers?.[I.type];if(!T)throw new Q(I.type);return {...I,resolve:T}}),resolve:s});return Object.values(_e).includes(n.type)&&(R={...R,outputs:z(R.outputs)}),r===e.stepId&&t({...R,options:{skip:!1}}),R.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
24
24
|
${p.bold(p.underline(s))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),n=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},a,O=new Promise(f=>{a=f;}),c=f=>{a(),d=f;},u;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new U(e.workflowId,{message:"Event `payload` is required"});let f=await this.createExecutionPayload(e,i),w={...e,payload:f};await Promise.race([O,i.execute({payload:f,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(w,c),sms:this.executeStepFactory(w,c),inApp:this.executeStepFactory(w,c),digest:this.executeStepFactory(w,c),delay:this.executeStepFactory(w,c),push:this.executeStepFactory(w,c),chat:this.executeStepFactory(w,c),custom:this.executeStepFactory(w,c)}})]);}catch(f){u=f;}let R=process.hrtime(n),I=R[0],T=R[1],m=I*1e3+T/1e6,Se=u?_.ERROR:_.SUCCESS,ye=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Se} ${ye} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,m,u),u)throw u;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:m}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let s=r?_.ERROR:_.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",n=r?"Failed to execute":i,d=r?p.error:p.success,a=`${s} ${n} workflowId: '${e.workflowId}`;console.log(`
|
|
25
25
|
${p.bold(d(a))}'`),console.log(` \u251C ${_.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${_.ACTION} action: '${e.action}'`),console.log(` \u2514 ${_.DURATION} duration: '${t.toFixed(2)}ms'
|
|
26
26
|
`);}async executeProviders(e,t,r){return t.providers.reduce(async(s,i)=>{let n=await s,d=this.previewProvider.bind(this),a=this.executeProvider.bind(this),c=await(e.action==="preview"?d:a)(e,t,i,r);return {...n,[i.type]:c}},Promise.resolve({}))}previewProvider(e,t,r,s){return console.log(` ${_.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,s){let i=pe__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let n=await this.createStepControls(t,e),d=await r.resolve({controls:n,outputs:s}),a=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...a,_passthrough:d._passthrough}}else return i.stopAndPersist({symbol:_.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(n){throw i.stopAndPersist({symbol:_.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new H(`Failed to execute provider: '${r.type}'.
|
package/dist/servers/nuxt.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as h3 from 'h3';
|
|
2
2
|
import { H3Event } from 'h3';
|
|
3
|
-
import {
|
|
3
|
+
import { w as SupportedFrameworkName, c as ServeHandlerOptions } from '../handler-_mH7Q42O.js';
|
|
4
4
|
import '@novu/shared';
|
|
5
5
|
import 'json-schema-to-ts';
|
|
6
6
|
import 'zod';
|
package/dist/servers/nuxt.js
CHANGED
|
@@ -21,7 +21,7 @@ var Ie__default = /*#__PURE__*/_interopDefault(Ie);
|
|
|
21
21
|
var Me__default = /*#__PURE__*/_interopDefault(Me);
|
|
22
22
|
var Ve__default = /*#__PURE__*/_interopDefault(Ve);
|
|
23
23
|
|
|
24
|
-
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),V=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(V||{});var u=(n=>(n.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",n.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",n.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",n.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",n.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",n.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",n.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",n.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",n.STEP_NOT_FOUND_ERROR="StepNotFoundError",n.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",n.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",n.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",n.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",n.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",n.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",n.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",n.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",n.INVALID_ACTION_ERROR="InvalidActionError",n.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",n.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",n.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",n.SIGNATURE_INVALID_ERROR="SignatureInvalidError",n.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",n.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",n.BRIDGE_ERROR="BridgeError",n.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",n.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",n))(u||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var Te="2.1.0";var y=Te,F="2024-06-26";var O=class extends Error{data},L=class extends O{statusCode=404},R=class extends O{statusCode=400},m=class extends O{statusCode=401},f=class extends O{statusCode=500},C=class extends O{statusCode=409};var b=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},P=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends O{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:o=>N__default.default.blue(o),warning:o=>N__default.default.yellow(o),error:o=>N__default.default.red(o),success:o=>N__default.default.green(o),underline:o=>N__default.default.underline(o),bold:o=>N__default.default.bold(o)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var ue=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var xe={allowedTags:Ie__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},me=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=Ie__default.default(o,xe);return t?t[0]+r:r},q=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=me(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?me(s):typeof s=="object"?q(s):s):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ue(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ue(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Me__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=fe(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(o,e)=>{if(ce.canHandle(o))return ce.validate(e,o);if(de.canHandle(o))return de.validate(e,o);throw new Error("Invalid schema")},ve=o=>{if(ce.canHandle(o))return ce.transformToJsonSchema(o);if(de.canHandle(o))return de.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Le(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=y;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Le()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:y,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,s,i,a,d){let c=await Ne(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(s,i,c.errors);case"step":this.throwInvalidStep(a,s,i,c.errors);case"provider":this.throwInvalidProvider(a,d,s,i,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,s);case"result":throw new j(r,e,s);case"controls":throw new $(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new P(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let a=this.getStep(e.workflowId,r),d=await this.createStepControls(a,e),c=e.action==="preview";if(!c&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let E=this.previewStep.bind(this),_=this.executeStep.bind(this),T=await(c?E:_)(e,{...a,providers:a.providers.map(S=>{let M=i?.providers?.[S.type];if(!M)throw new Z(S.type);return {...S,resolve:M}}),resolve:s});return Object.values(Re).includes(a.type)&&(T={...T,outputs:q(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
24
|
+
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),V=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(V||{});var u=(n=>(n.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",n.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",n.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",n.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",n.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",n.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",n.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",n.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",n.STEP_NOT_FOUND_ERROR="StepNotFoundError",n.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",n.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",n.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",n.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",n.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",n.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",n.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",n.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",n.INVALID_ACTION_ERROR="InvalidActionError",n.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",n.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",n.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",n.SIGNATURE_INVALID_ERROR="SignatureInvalidError",n.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",n.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",n.BRIDGE_ERROR="BridgeError",n.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",n.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",n))(u||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var Te="2.1.1";var y=Te,F="2024-06-26";var O=class extends Error{data},L=class extends O{statusCode=404},R=class extends O{statusCode=400},m=class extends O{statusCode=401},f=class extends O{statusCode=500},C=class extends O{statusCode=409};var b=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},P=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends O{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:o=>N__default.default.blue(o),warning:o=>N__default.default.yellow(o),error:o=>N__default.default.red(o),success:o=>N__default.default.green(o),underline:o=>N__default.default.underline(o),bold:o=>N__default.default.bold(o)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var ue=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Ae=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var xe={allowedTags:Ie__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},me=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=Ie__default.default(o,xe);return t?t[0]+r:r},q=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=me(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?me(s):typeof s=="object"?q(s):s):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ue(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ue(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var fe=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Me__default.default({useDefaults:!0,removeAdditional:"failing"}),Ve__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=fe(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,Ne=async(o,e)=>{if(ce.canHandle(o))return ce.validate(e,o);if(de.canHandle(o))return de.validate(e,o);throw new Error("Invalid schema")},ve=o=>{if(ce.canHandle(o))return ce.transformToJsonSchema(o);if(de.canHandle(o))return de.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Le(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=y;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Le()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:y,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ve(e))}async validate(e,t,r,s,i,a,d){let c=await Ne(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(s,i,c.errors);case"step":this.throwInvalidStep(a,s,i,c.errors);case"provider":this.throwInvalidProvider(a,d,s,i,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,s);case"result":throw new j(r,e,s);case"controls":throw new $(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new P(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let a=this.getStep(e.workflowId,r),d=await this.createStepControls(a,e),c=e.action==="preview";if(!c&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let E=this.previewStep.bind(this),_=this.executeStep.bind(this),T=await(c?E:_)(e,{...a,providers:a.providers.map(S=>{let M=i?.providers?.[S.type];if(!M)throw new Z(S.type);return {...S,resolve:M}}),resolve:s});return Object.values(Re).includes(a.type)&&(T={...T,outputs:q(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
25
25
|
${l.bold(l.underline(s))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},c,E=new Promise(h=>{c=h;}),_=h=>{c(),d=h;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new P(e.workflowId,{message:"Event `payload` is required"});let h=await this.createExecutionPayload(e,i),A={...e,payload:h};await Promise.race([E,i.execute({payload:h,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(A,_),sms:this.executeStepFactory(A,_),inApp:this.executeStepFactory(A,_),digest:this.executeStepFactory(A,_),delay:this.executeStepFactory(A,_),push:this.executeStepFactory(A,_),chat:this.executeStepFactory(A,_),custom:this.executeStepFactory(A,_)}})]);}catch(h){w=h;}let T=process.hrtime(a),S=T[0],M=T[1],Ee=S*1e3+M/1e6,Se=w?p.ERROR:p.SUCCESS,De=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Se} ${De} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Ee,w),w)throw w;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:Ee}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let s=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":i,d=r?l.error:l.success,c=`${s} ${a} workflowId: '${e.workflowId}`;console.log(`
|
|
26
26
|
${l.bold(d(c))}'`),console.log(` \u251C ${p.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${p.ACTION} action: '${e.action}'`),console.log(` \u2514 ${p.DURATION} duration: '${t.toFixed(2)}ms'
|
|
27
27
|
`);}async executeProviders(e,t,r){return t.providers.reduce(async(s,i)=>{let a=await s,d=this.previewProvider.bind(this),c=this.executeProvider.bind(this),_=await(e.action==="preview"?d:c)(e,t,i,r);return {...a,[i.type]:_}},Promise.resolve({}))}previewProvider(e,t,r,s){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,s){let i=le__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let a=await this.createStepControls(t,e),d=await r.resolve({controls:a,outputs:s}),c=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...c,_passthrough:d._passthrough}}else return i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(a){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new Q(`Failed to execute provider: '${r.type}'.
|
package/dist/servers/remix.d.ts
CHANGED
package/dist/servers/remix.js
CHANGED
|
@@ -20,7 +20,7 @@ var we__default = /*#__PURE__*/_interopDefault(we);
|
|
|
20
20
|
var Ve__default = /*#__PURE__*/_interopDefault(Ve);
|
|
21
21
|
var Ye__default = /*#__PURE__*/_interopDefault(Ye);
|
|
22
22
|
|
|
23
|
-
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),V=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(V||{});var u=(n=>(n.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",n.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",n.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",n.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",n.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",n.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",n.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",n.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",n.STEP_NOT_FOUND_ERROR="StepNotFoundError",n.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",n.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",n.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",n.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",n.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",n.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",n.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",n.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",n.INVALID_ACTION_ERROR="InvalidActionError",n.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",n.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",n.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",n.SIGNATURE_INVALID_ERROR="SignatureInvalidError",n.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",n.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",n.BRIDGE_ERROR="BridgeError",n.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",n.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",n))(u||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var _e=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(_e||{});var Te="2.1.0";var y=Te,F="2024-06-26";var O=class extends Error{data},L=class extends O{statusCode=404},_=class extends O{statusCode=400},m=class extends O{statusCode=401},f=class extends O{statusCode=500},C=class extends O{statusCode=409};var b=class extends _{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},P=class extends _{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends _{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends _{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends _{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends _{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends _{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends _{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends O{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var Ae=()=>typeof Response<"u"?Response:crossFetch.Response;var l={info:o=>N__default.default.blue(o),warning:o=>N__default.default.yellow(o),error:o=>N__default.default.red(o),success:o=>N__default.default.green(o),underline:o=>N__default.default.underline(o),bold:o=>N__default.default.bold(o)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var ue=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var me=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var Ue={allowedTags:we__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=we__default.default(o,Ue);return t?t[0]+r:r},q=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?Ie(s):typeof s=="object"?q(s):s):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ue(Y)}`},x=class extends _{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ue(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var Ne=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Ve__default.default({useDefaults:!0,removeAdditional:"failing"}),Ye__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=Ne(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,ve=async(o,e)=>{if(ce.canHandle(o))return ce.validate(e,o);if(de.canHandle(o))return de.validate(e,o);throw new Error("Invalid schema")},ge=o=>{if(ce.canHandle(o))return ce.transformToJsonSchema(o);if(de.canHandle(o))return de.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Ce(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=y;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Ce()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:y,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ge(e))}async validate(e,t,r,s,i,a,d){let c=await ve(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(s,i,c.errors);case"step":this.throwInvalidStep(a,s,i,c.errors);case"provider":this.throwInvalidProvider(a,d,s,i,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,s);case"result":throw new j(r,e,s);case"controls":throw new $(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new P(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let a=this.getStep(e.workflowId,r),d=await this.createStepControls(a,e),c=e.action==="preview";if(!c&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let E=this.previewStep.bind(this),R=this.executeStep.bind(this),T=await(c?E:R)(e,{...a,providers:a.providers.map(S=>{let M=i?.providers?.[S.type];if(!M)throw new Z(S.type);return {...S,resolve:M}}),resolve:s});return Object.values(_e).includes(a.type)&&(T={...T,outputs:q(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
23
|
+
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),V=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(V||{});var u=(n=>(n.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",n.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",n.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",n.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",n.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",n.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",n.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",n.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",n.STEP_NOT_FOUND_ERROR="StepNotFoundError",n.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",n.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",n.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",n.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",n.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",n.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",n.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",n.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",n.INVALID_ACTION_ERROR="InvalidActionError",n.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",n.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",n.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",n.SIGNATURE_INVALID_ERROR="SignatureInvalidError",n.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",n.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",n.BRIDGE_ERROR="BridgeError",n.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",n.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",n))(u||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var _e=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(_e||{});var Te="2.1.1";var y=Te,F="2024-06-26";var O=class extends Error{data},L=class extends O{statusCode=404},_=class extends O{statusCode=400},m=class extends O{statusCode=401},f=class extends O{statusCode=500},C=class extends O{statusCode=409};var b=class extends _{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},P=class extends _{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends _{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends _{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends _{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends _{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends _{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends _{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends O{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var Ae=()=>typeof Response<"u"?Response:crossFetch.Response;var l={info:o=>N__default.default.blue(o),warning:o=>N__default.default.yellow(o),error:o=>N__default.default.red(o),success:o=>N__default.default.green(o),underline:o=>N__default.default.underline(o),bold:o=>N__default.default.bold(o)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var ue=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),J=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var me=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var Ue={allowedTags:we__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=we__default.default(o,Ue);return t?t[0]+r:r},q=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?Ie(s):typeof s=="object"?q(s):s):typeof r=="object"&&r!==null?e[t]=q(r):e[t]=r,e},{});var z=class extends O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ue(Y)}`},x=class extends _{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ue(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends C{constructor(e,t){super(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends L{constructor(e,t){super(`${J(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${J(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var Ne=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Ve__default.default({useDefaults:!0,removeAdditional:"failing"}),Ye__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=Ne(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,ve=async(o,e)=>{if(ce.canHandle(o))return ce.validate(e,o);if(de.canHandle(o))return de.validate(e,o);throw new Error("Invalid schema")},ge=o=>{if(ce.canHandle(o))return ce.transformToJsonSchema(o);if(de.canHandle(o))return de.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Ce(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=y;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Ce()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:y,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ge(e))}async validate(e,t,r,s,i,a,d){let c=await ve(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(s,i,c.errors);case"step":this.throwInvalidStep(a,s,i,c.errors);case"provider":this.throwInvalidProvider(a,d,s,i,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,s);case"result":throw new j(r,e,s);case"controls":throw new $(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new P(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let a=this.getStep(e.workflowId,r),d=await this.createStepControls(a,e),c=e.action==="preview";if(!c&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let E=this.previewStep.bind(this),R=this.executeStep.bind(this),T=await(c?E:R)(e,{...a,providers:a.providers.map(S=>{let M=i?.providers?.[S.type];if(!M)throw new Z(S.type);return {...S,resolve:M}}),resolve:s});return Object.values(_e).includes(a.type)&&(T={...T,outputs:q(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
24
24
|
${l.bold(l.underline(s))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},c,E=new Promise(h=>{c=h;}),R=h=>{c(),d=h;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new P(e.workflowId,{message:"Event `payload` is required"});let h=await this.createExecutionPayload(e,i),A={...e,payload:h};await Promise.race([E,i.execute({payload:h,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(A,R),sms:this.executeStepFactory(A,R),inApp:this.executeStepFactory(A,R),digest:this.executeStepFactory(A,R),delay:this.executeStepFactory(A,R),push:this.executeStepFactory(A,R),chat:this.executeStepFactory(A,R),custom:this.executeStepFactory(A,R)}})]);}catch(h){w=h;}let T=process.hrtime(a),S=T[0],M=T[1],Ee=S*1e3+M/1e6,Se=w?p.ERROR:p.SUCCESS,De=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Se} ${De} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Ee,w),w)throw w;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:Ee}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let s=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":i,d=r?l.error:l.success,c=`${s} ${a} workflowId: '${e.workflowId}`;console.log(`
|
|
25
25
|
${l.bold(d(c))}'`),console.log(` \u251C ${p.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${p.ACTION} action: '${e.action}'`),console.log(` \u2514 ${p.DURATION} duration: '${t.toFixed(2)}ms'
|
|
26
26
|
`);}async executeProviders(e,t,r){return t.providers.reduce(async(s,i)=>{let a=await s,d=this.previewProvider.bind(this),c=this.executeProvider.bind(this),R=await(e.action==="preview"?d:c)(e,t,i,r);return {...a,[i.type]:R}},Promise.resolve({}))}previewProvider(e,t,r,s){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,s){let i=le__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let a=await this.createStepControls(t,e),d=await r.resolve({controls:a,outputs:s}),c=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...c,_passthrough:d._passthrough}}else return i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(a){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new Q(`Failed to execute provider: '${r.type}'.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RequestEvent } from '@sveltejs/kit';
|
|
2
|
-
import {
|
|
2
|
+
import { w as SupportedFrameworkName, c as ServeHandlerOptions } from '../handler-_mH7Q42O.js';
|
|
3
3
|
import '@novu/shared';
|
|
4
4
|
import 'json-schema-to-ts';
|
|
5
5
|
import 'zod';
|
|
@@ -20,7 +20,7 @@ var we__default = /*#__PURE__*/_interopDefault(we);
|
|
|
20
20
|
var Ve__default = /*#__PURE__*/_interopDefault(Ve);
|
|
21
21
|
var Ye__default = /*#__PURE__*/_interopDefault(Ye);
|
|
22
22
|
|
|
23
|
-
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),V=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(V||{});var O=(d=>(d.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",d.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",d.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",d.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",d.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",d.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",d.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",d.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",d.STEP_NOT_FOUND_ERROR="StepNotFoundError",d.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",d.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",d.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",d.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",d.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",d.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",d.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",d.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",d.INVALID_ACTION_ERROR="InvalidActionError",d.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",d.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",d.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",d.SIGNATURE_INVALID_ERROR="SignatureInvalidError",d.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",d.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",d.BRIDGE_ERROR="BridgeError",d.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",d.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",d))(O||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var Te="2.1.0";var P=Te,F="2024-06-26";var E=class extends Error{data},b=class extends E{statusCode=404},R=class extends E{statusCode=400},m=class extends E{statusCode=401},f=class extends E{statusCode=500},L=class extends E{statusCode=409};var C=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},y=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var Ae=()=>typeof Response<"u"?Response:crossFetch.Response;var l={info:o=>N__default.default.blue(o),warning:o=>N__default.default.yellow(o),error:o=>N__default.default.red(o),success:o=>N__default.default.green(o),underline:o=>N__default.default.underline(o),bold:o=>N__default.default.bold(o)},u={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var _e=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),q=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var me=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var Ue={allowedTags:we__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=we__default.default(o,Ue);return t?t[0]+r:r},J=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?Ie(s):typeof s=="object"?J(s):s):typeof r=="object"&&r!==null?e[t]=J(r):e[t]=r,e},{});var z=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${_e(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${_e(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends L{constructor(e,t){super(`${q(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends b{constructor(e,t){super(`${q(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${q(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var Ne=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Ve__default.default({useDefaults:!0,removeAdditional:"failing"}),Ye__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=Ne(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,ve=async(o,e)=>{if(ce.canHandle(o))return ce.validate(e,o);if(de.canHandle(o))return de.validate(e,o);throw new Error("Invalid schema")},ge=o=>{if(ce.canHandle(o))return ce.transformToJsonSchema(o);if(de.canHandle(o))return de.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Le(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=P;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Le()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:P,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ge(e))}async validate(e,t,r,s,i,a,n){let c=await ve(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(s,i,c.errors);case"step":this.throwInvalidStep(a,s,i,c.errors);case"provider":this.throwInvalidProvider(a,n,s,i,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,s);case"result":throw new j(r,e,s);case"controls":throw new $(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new y(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let a=this.getStep(e.workflowId,r),n=await this.createStepControls(a,e),c=e.action==="preview";if(!c&&await this.shouldSkip(i?.skip,n))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let _=this.previewStep.bind(this),p=this.executeStep.bind(this),T=await(c?_:p)(e,{...a,providers:a.providers.map(S=>{let M=i?.providers?.[S.type];if(!M)throw new Z(S.type);return {...S,resolve:M}}),resolve:s});return Object.values(Re).includes(a.type)&&(T={...T,outputs:J(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
23
|
+
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),V=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(V||{});var O=(d=>(d.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",d.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",d.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",d.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",d.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",d.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",d.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",d.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",d.STEP_NOT_FOUND_ERROR="StepNotFoundError",d.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",d.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",d.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",d.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",d.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",d.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",d.STEP_CONTROL_COMPILATION_FAILED_ERROR="StepControlCompilationFailedError",d.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",d.INVALID_ACTION_ERROR="InvalidActionError",d.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",d.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",d.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",d.SIGNATURE_INVALID_ERROR="SignatureInvalidError",d.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",d.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",d.BRIDGE_ERROR="BridgeError",d.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",d.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",d))(O||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var Re=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(Re||{});var Te="2.1.1";var P=Te,F="2024-06-26";var E=class extends Error{data},b=class extends E{statusCode=404},R=class extends E{statusCode=400},m=class extends E{statusCode=401},f=class extends E{statusCode=500},L=class extends E{statusCode=409};var C=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},y=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},G=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},j=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},K=class extends R{code="StepControlCompilationFailedError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has invalid controls syntax in step with id: \`${t}\`. Please correct step control syntax.`),this.data=r;}},B=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=s;}};var X=class extends E{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var Ae=()=>typeof Response<"u"?Response:crossFetch.Response;var l={info:o=>N__default.default.blue(o),warning:o=>N__default.default.yellow(o),error:o=>N__default.default.red(o),success:o=>N__default.default.green(o),underline:o=>N__default.default.underline(o),bold:o=>N__default.default.bold(o)},u={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var _e=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),q=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var me=(o,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(r,s)=>{let i=await fetch(`${t}/v1${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`},body:JSON.stringify(s)}),a=await i.json();if(i.ok)return a;throw shared.checkIsResponseError(a)?new X(a.statusCode,a.error,a.message):new v("Error processing API request to Novu Cloud from Bridge application.")},delete:async r=>(await fetch(`${t}/v1${r}`,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var Ue={allowedTags:we__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},Ie=o=>{if(!o)return o;let e=/^<!DOCTYPE .*?>/,t=o.match(e),r=we__default.default(o,Ue);return t?t[0]+r:r},J=o=>Object.keys(o).reduce((e,t)=>{let r=o[t];return typeof r=="string"?e[t]=Ie(r):Array.isArray(r)?e[t]=r.map(s=>typeof s=="string"?Ie(s):typeof s=="object"?J(s):s):typeof r=="object"&&r!==null?e[t]=J(r):e[t]=r,e},{});var z=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${_e(Y)}`},x=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${_e(t)}`);}};var v=class extends f{code="BridgeError";message="Something went wrong. Please try again later."};var U=class extends L{constructor(e,t){super(`${q(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=class extends b{constructor(e,t){super(`${q(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends f{constructor(e,t){super(`Failed to execute ${q(e)} with id: \`${t}\`. Please try again later.`);}};var Z=class extends I{code="ProviderNotFoundError";constructor(e){super("provider",e);}},Q=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var H=class extends m{code="SignatureMismatchError";constructor(){super("Signature does not match the expected signature. Please ensure the signature provided in the `novu-signature` header is correct and try again.");}},ee=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},te=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},re=class extends m{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},oe=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var se=class extends I{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends I{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ie=class extends U{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var Ne=o=>typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o));var ae=class{ajv;compiledSchemas;constructor(){this.ajv=new Ve__default.default({useDefaults:!0,removeAdditional:"failing"}),Ye__default.default(this.ajv),this.compiledSchemas=new Map;}canHandle(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.allOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r));let s=Ne(e);return r(s)?{success:!0,data:s}:{success:!1,errors:r.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var ne=class{canHandle(e){return e.safeParseAsync!==void 0}async validate(e,t){let r=t.safeParse(e);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var ce=new ne,de=new ae,ve=async(o,e)=>{if(ce.canHandle(o))return ce.validate(e,o);if(de.canHandle(o))return de.validate(e,o);throw new Error("Invalid schema")},ge=o=>{if(ce.canHandle(o))return ce.transformToJsonSchema(o);if(de.canHandle(o))return de.transformToJsonSchema(o);throw new Error("Invalid schema")};jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Le(){return ["development",void 0].includes(process.env.NODE_ENV)}var pe=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=P;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Le()};return t.secretKey=e?.secretKey||process.env.NOVU_SECRET_KEY||process.env.NOVU_API_KEY,e?.strictAuthentication!==void 0?t.strictAuthentication=e.strictAuthentication:process.env.NOVU_STRICT_AUTHENTICATION_ENABLED!==void 0&&(t.strictAuthentication=process.env.NOVU_STRICT_AUTHENTICATION_ENABLED==="true"),t}addWorkflows(e){for(let t of e){if(this.discoveredWorkflows.some(r=>r.workflowId===t.definition.workflowId))throw new ie(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,s)=>r+s.steps.length,0);return {status:"ok",sdkVersion:P,frameworkVersion:F,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new k(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new se(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(ge(e))}async validate(e,t,r,s,i,a,n){let c=await ve(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(s,i,c.errors);case"step":this.throwInvalidStep(a,s,i,c.errors);case"provider":this.throwInvalidProvider(a,n,s,i,c.errors);default:throw new Error(`Invalid component: '${r}'`)}}throwInvalidProvider(e,t,r,s,i){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(r){case"output":throw new B(s,e,t,i);default:throw new Error(`Invalid payload type: '${r}'`)}}throwInvalidStep(e,t,r,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new G(r,e,s);case"result":throw new j(r,e,s);case"controls":throw new $(r,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new y(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let a=this.getStep(e.workflowId,r),n=await this.createStepControls(a,e),c=e.action==="preview";if(!c&&await this.shouldSkip(i?.skip,n))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let _=this.previewStep.bind(this),p=this.executeStep.bind(this),T=await(c?_:p)(e,{...a,providers:a.providers.map(S=>{let M=i?.providers?.[S.type];if(!M)throw new Z(S.type);return {...S,resolve:M}}),resolve:s});return Object.values(Re).includes(a.type)&&(T={...T,outputs:J(T.outputs)}),r===e.stepId&&t({...T,options:{skip:!1}}),T.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
24
24
|
${l.bold(l.underline(s))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),n={outputs:{},providers:{},options:{skip:!1}},c,_=new Promise(h=>{c=h;}),p=h=>{c(),n=h;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new y(e.workflowId,{message:"Event `payload` is required"});let h=await this.createExecutionPayload(e,i),A={...e,payload:h};await Promise.race([_,i.execute({payload:h,environment:{},input:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(A,p),sms:this.executeStepFactory(A,p),inApp:this.executeStepFactory(A,p),digest:this.executeStepFactory(A,p),delay:this.executeStepFactory(A,p),push:this.executeStepFactory(A,p),chat:this.executeStepFactory(A,p),custom:this.executeStepFactory(A,p)}})]);}catch(h){w=h;}let T=process.hrtime(a),S=T[0],M=T[1],Ee=S*1e3+M/1e6,Se=w?u.ERROR:u.SUCCESS,De=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Se} ${De} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,Ee,w),w)throw w;return {outputs:n.outputs,providers:n.providers,options:n.options,metadata:{status:"success",error:!1,duration:Ee}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let s=r?u.ERROR:u.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",a=r?"Failed to execute":i,n=r?l.error:l.success,c=`${s} ${a} workflowId: '${e.workflowId}`;console.log(`
|
|
25
25
|
${l.bold(n(c))}'`),console.log(` \u251C ${u.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${u.ACTION} action: '${e.action}'`),console.log(` \u2514 ${u.DURATION} duration: '${t.toFixed(2)}ms'
|
|
26
26
|
`);}async executeProviders(e,t,r){return t.providers.reduce(async(s,i)=>{let a=await s,n=this.previewProvider.bind(this),c=this.executeProvider.bind(this),p=await(e.action==="preview"?n:c)(e,t,i,r);return {...a,[i.type]:p}},Promise.resolve({}))}previewProvider(e,t,r,s){return console.log(` ${u.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,s){let i=le__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let a=await this.createStepControls(t,e),n=await r.resolve({controls:a,outputs:s}),c=await this.validate(n,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...c,_passthrough:n._passthrough}}else return i.stopAndPersist({symbol:u.HYDRATED,text:`Hydrated provider: \`${r.type}\``}),{}}catch(a){throw i.stopAndPersist({symbol:u.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new Q(`Failed to execute provider: '${r.type}'.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@novu/framework",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.1",
|
|
4
4
|
"description": "The Code-First Notifications Workflow SDK.",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -29,8 +29,7 @@
|
|
|
29
29
|
"$comment:bump:prerelease": "This is a workaround to support `npm version prerelease` with lerna",
|
|
30
30
|
"bump:prerelease": "npm version prerelease --preid=alpha & PID=$!; (sleep 1 && kill -9 $PID) & wait $PID",
|
|
31
31
|
"release:alpha": "pnpm bump:prerelease || pnpm build && npm publish",
|
|
32
|
-
"devtool": "tsx ./scripts/devtool.ts"
|
|
33
|
-
"release:preview": "pnpx pkg-pr-new publish"
|
|
32
|
+
"devtool": "tsx ./scripts/devtool.ts"
|
|
34
33
|
},
|
|
35
34
|
"keywords": [
|
|
36
35
|
"novu",
|
|
@@ -153,7 +152,7 @@
|
|
|
153
152
|
"zod-to-json-schema": "^3.23.0"
|
|
154
153
|
},
|
|
155
154
|
"dependencies": {
|
|
156
|
-
"@novu/shared": "^2.1.
|
|
155
|
+
"@novu/shared": "^2.1.1",
|
|
157
156
|
"ajv": "^8.12.0",
|
|
158
157
|
"ajv-formats": "^2.1.1",
|
|
159
158
|
"better-ajv-errors": "^1.2.0",
|
|
@@ -164,5 +163,8 @@
|
|
|
164
163
|
"liquidjs": "^10.13.1",
|
|
165
164
|
"ora": "^5.4.1",
|
|
166
165
|
"sanitize-html": "^2.13.0"
|
|
166
|
+
},
|
|
167
|
+
"nx": {
|
|
168
|
+
"tags": ["package:public"]
|
|
167
169
|
}
|
|
168
170
|
}
|