@novu/framework 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{handler-8vDLpUDh.d.ts → handler-TDgxEYp-.d.ts} +2689 -2665
- package/dist/index.d.ts +2 -2
- package/dist/index.js +22 -20
- package/dist/servers/express.d.ts +1 -1
- package/dist/servers/express.js +6 -6
- package/dist/servers/h3.d.ts +1 -1
- package/dist/servers/h3.js +4 -4
- package/dist/servers/lambda.d.ts +1 -1
- package/dist/servers/lambda.js +5 -5
- package/dist/servers/nest.d.ts +115 -0
- package/dist/servers/nest.js +34 -0
- package/dist/servers/next.d.ts +1 -1
- package/dist/servers/next.js +3 -3
- package/dist/servers/nuxt.d.ts +1 -1
- package/dist/servers/nuxt.js +2 -2
- package/dist/servers/remix.d.ts +1 -1
- package/dist/servers/remix.js +2 -2
- package/dist/servers/sveltekit.d.ts +1 -1
- package/dist/servers/sveltekit.js +2 -2
- package/package.json +16 -4
package/dist/servers/express.js
CHANGED
|
@@ -7,7 +7,7 @@ var le = require('ora');
|
|
|
7
7
|
require('cross-fetch');
|
|
8
8
|
var N = require('chalk');
|
|
9
9
|
var shared = require('@novu/shared');
|
|
10
|
-
var
|
|
10
|
+
var Ie = require('sanitize-html');
|
|
11
11
|
var ke = require('ajv');
|
|
12
12
|
var Ve = require('ajv-formats');
|
|
13
13
|
var zodToJsonSchema = require('zod-to-json-schema');
|
|
@@ -16,15 +16,15 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
16
16
|
|
|
17
17
|
var le__default = /*#__PURE__*/_interopDefault(le);
|
|
18
18
|
var N__default = /*#__PURE__*/_interopDefault(N);
|
|
19
|
-
var
|
|
19
|
+
var Ie__default = /*#__PURE__*/_interopDefault(Ie);
|
|
20
20
|
var ke__default = /*#__PURE__*/_interopDefault(ke);
|
|
21
21
|
var Ve__default = /*#__PURE__*/_interopDefault(Ve);
|
|
22
22
|
|
|
23
|
-
var y=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(y||{}),M=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(M||{});var R=(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))(R||{});var Y=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(Y||{});var ue=(i=>(i.EMAIL="email",i.SMS="sms",i.PUSH="push",i.CHAT="chat",i.IN_APP="in_app",i))(ue||{});var Te="2.1.0";var D=Te,F="2024-06-26";var O=class extends Error{data},L=class extends O{statusCode=404},u=class extends O{statusCode=400},I=class extends O{statusCode=401},f=class extends O{statusCode=500},C=class extends O{statusCode=409};var b=class extends u{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 u{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 u{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends u{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 u{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 u{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 u{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 u{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 O{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 Re=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 Pe={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,Pe);return t?t[0]+r:r},z=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"?z(o):o):typeof r=="object"&&r!==null?e[t]=z(r):e[t]=r,e},{});var q=class extends O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Re(Y)}`},x=class extends u{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Re(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.`);}},m=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 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=D;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:D,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,d){let n=await Ne(t,e);if(n.success)return n.data;switch(r){case"event":this.throwInvalidEvent(o,i,n.errors);case"step":this.throwInvalidStep(a,o,i,n.errors);case"provider":this.throwInvalidProvider(a,d,o,i,n.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 P(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),d=await this.createStepControls(a,e),n=e.action==="preview";if(!n&&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(n?E:_)(e,{...a,providers:a.providers.map(S=>{let V=i?.providers?.[S.type];if(!V)throw new Z(S.type);return {...S,resolve:V}}),resolve:o});return Object.values(ue).includes(a.type)&&(T={...T,outputs:z(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 o=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
24
|
-
${l.bold(l.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},n,
|
|
23
|
+
var y=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(y||{}),M=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(M||{});var R=(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))(R||{});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.2.0";var D=Te,F="2024-06-26";var E=class extends Error{data},L=class extends E{statusCode=404},_=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 _{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;}},j=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;}},G=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,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 Re=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 Pe={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=s=>{if(!s)return s;let e=/^<!DOCTYPE .*?>/,t=s.match(e),r=Ie__default.default(s,Pe);return t?t[0]+r:r},z=s=>Object.keys(s).reduce((e,t)=>{let r=s[t];return typeof r=="string"?e[t]=me(r):Array.isArray(r)?e[t]=r.map(o=>typeof o=="string"?me(o):typeof o=="object"?z(o):o):typeof r=="object"&&r!==null?e[t]=z(r):e[t]=r,e},{});var q=class extends E{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${Re(Y)}`},x=class extends _{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Re(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=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=D;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:D,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,d){let n=await Ne(t,e);if(n.success)return n.data;switch(r){case"event":this.throwInvalidEvent(o,i,n.errors);case"step":this.throwInvalidStep(a,o,i,n.errors);case"provider":this.throwInvalidProvider(a,d,o,i,n.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 j(r,e,o);case"result":throw new G(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 P(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),d=await this.createStepControls(a,e),n=e.action==="preview";if(!n&&await this.shouldSkip(i?.skip,d))return r===e.stepId&&t({options:{skip:!0},outputs:{},providers:{}}),{};let O=this.previewStep.bind(this),u=this.executeStep.bind(this),T=await(n?O:u)(e,{...a,providers:a.providers.map(S=>{let V=i?.providers?.[S.type];if(!V)throw new Z(S.type);return {...S,resolve:V}}),resolve:o});return Object.values(_e).includes(a.type)&&i?.disableOutputSanitization!==!0&&(T={...T,outputs:z(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 o=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
24
|
+
${l.bold(l.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),a=process.hrtime(),d={outputs:{},providers:{},options:{skip:!1}},n,O=new Promise(h=>{n=h;}),u=h=>{n(),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,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(h){w=h;}let T=process.hrtime(a),S=T[0],V=T[1],Oe=S*1e3+V/1e6,ge=w?p.ERROR:p.SUCCESS,Se=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${ge} ${Se} 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 o=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,n=`${o} ${a} workflowId: '${e.workflowId}`;console.log(`
|
|
25
25
|
${l.bold(d(n))}'`),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
|
-
`);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let a=await o,d=this.previewProvider.bind(this),n=this.executeProvider.bind(this),
|
|
27
|
-
${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),n=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:n}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new b(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(o)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new k(e);return r}};var
|
|
26
|
+
`);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let a=await o,d=this.previewProvider.bind(this),n=this.executeProvider.bind(this),u=await(e.action==="preview"?d:n)(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),d=await r.resolve({controls:a,outputs:o}),n=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),{...n,_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}'.
|
|
27
|
+
${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),n=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:n}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new b(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(o)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new k(e);return r}};var ue=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new pe,this.client.addWorkflows(e.workflows),this.http=Ae(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":F,"novu-framework-sdk":D,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),o=t.searchParams.get("action")||"health-check",i=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",n={};try{r==="POST"&&(n=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(n,d);let O=this.getPostActionMap(n,i,a,o),u=this.getGetActionMap(i,a);if(r==="POST")return await this.handlePostAction(o,O);if(r==="GET")return await this.handleGetAction(o,u);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new q(r))}getPostActionMap(e,t,r,o){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,t){return {discover:async()=>{let r=await this.client.discover();return this.createResponse(200,r)},"health-check":async()=>{let r=await this.client.healthCheck();return this.createResponse(200,r)},code:async()=>{let r=await this.client.getCode(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(y).includes(e)){let r=t[e];return r()}else throw new x(e,y)}async handleGetAction(e,t){if(Object.values(M).includes(e)){let r=t[e];return r()}else throw new x(e,M)}isBridgeError(e){return Object.values(R).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new v))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new ee;if(!this.client.secretKey)throw new oe;let[r,o]=t.split(",");if(!r||!o)throw new te;let[i,a]=r.split("="),[d,n]=o.split("=");if(Number(i)<Date.now()-1500)throw new re;if(!(this.hashHmac(this.client.secretKey,`${a}.${JSON.stringify(e)}`)===n))throw new H}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var be="express",qr=s=>new ue({frameworkName:be,...s,handler:(t,r)=>({body:()=>t.body,headers:o=>{let i=t.headers[o];return Array.isArray(i)?i[0]:i},method:()=>t.method||"GET",url:()=>{let o=t.headers.host||"",i=o?.includes("://")?"":`${t.protocol||"https"}://`;return new URL(t.originalUrl||t.url||"",`${i}${o||""}`)},queryString:o=>{let i=t.query[o];return Array.isArray(i)?i[0]:i},transformResponse:({body:o,headers:i,status:a})=>(Object.entries(i).forEach(([d,n])=>{r.setHeader(d,n);}),r.status(a).send(o))})}).createHandler();
|
|
28
28
|
|
|
29
29
|
exports.frameworkName = be;
|
|
30
30
|
exports.serve = qr;
|
package/dist/servers/h3.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { H3Event, EventHandlerRequest } from 'h3';
|
|
2
|
-
import {
|
|
2
|
+
import { w as SupportedFrameworkName, c as ServeHandlerOptions } from '../handler-TDgxEYp-.js';
|
|
3
3
|
import '@novu/shared';
|
|
4
4
|
import 'json-schema-to-ts';
|
|
5
5
|
import 'zod';
|
package/dist/servers/h3.js
CHANGED
|
@@ -21,11 +21,11 @@ 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(`
|
|
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;}),
|
|
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 R=(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))(R||{});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.2.0";var y=Te,F="2024-06-26";var E=class extends Error{data},C=class extends E{statusCode=404},_=class extends E{statusCode=400},m=class extends E{statusCode=401},f=class extends E{statusCode=500},L=class extends E{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;}},j=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;}},G=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 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 Re=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 ${Re(Y)}`},x=class extends _{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Re(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(`${J(e)} with id: \`${t}\` already exists. Please use a different id.`);}},I=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 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 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(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 j(r,e,s);case"result":throw new G(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),u=this.executeStep.bind(this),T=await(c?O:u)(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)&&i?.disableOutputSanitization!==!0&&(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
|
+
${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;}),u=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,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(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
|
-
`);}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),
|
|
28
|
-
${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),c=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:c}}catch(s){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),s}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let s=e.state.find(i=>i.stepId===t.stepId);if(s){let i=await this.validate(s.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new b(e.workflowId,t.stepId)}catch(s){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),s}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),s=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(s)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let s=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:s,providers:await this.executeProviders(e,t,s)}}}catch(s){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),s}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new k(e);return r}};var
|
|
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),u=await(e.action==="preview"?d:c)(e,t,i,r);return {...a,[i.type]:u}},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}'.
|
|
28
|
+
${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),c=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:c}}catch(s){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),s}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let s=e.state.find(i=>i.stepId===t.stepId);if(s){let i=await this.validate(s.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new b(e.workflowId,t.stepId)}catch(s){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),s}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),s=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(s)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),a=await t.resolve(i),d=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let s=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:s,providers:await this.executeProviders(e,t,s)}}}catch(s){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),s}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new k(e);return r}};var ue=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new pe,this.client.addWorkflows(e.workflows),this.http=Ae(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":F,"novu-framework-sdk":y,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),s=t.searchParams.get("action")||"health-check",i=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",c={};try{r==="POST"&&(c=await e.body());}catch{}try{s!=="health-check"&&this.validateHmac(c,d);let O=this.getPostActionMap(c,i,a,s),u=this.getGetActionMap(i,a);if(r==="POST")return await this.handlePostAction(s,O);if(r==="GET")return await this.handleGetAction(s,u);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new z(r))}getPostActionMap(e,t,r,s){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:s});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,t){return {discover:async()=>{let r=await this.client.discover();return this.createResponse(200,r)},"health-check":async()=>{let r=await this.client.healthCheck();return this.createResponse(200,r)},code:async()=>{let r=await this.client.getCode(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(D).includes(e)){let r=t[e];return r()}else throw new x(e,D)}async handleGetAction(e,t){if(Object.values(V).includes(e)){let r=t[e];return r()}else throw new x(e,V)}isBridgeError(e){return Object.values(R).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new v))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new ee;if(!this.client.secretKey)throw new oe;let[r,s]=t.split(",");if(!r||!s)throw new te;let[i,a]=r.split("="),[d,c]=s.split("=");if(Number(i)<Date.now()-1500)throw new re;if(!(this.hashHmac(this.client.secretKey,`${a}.${JSON.stringify(e)}`)===c))throw new H}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var Ke="h3",to=o=>new ue({frameworkName:Ke,...o,handler:t=>({body:()=>h3.readBody(t),headers:r=>h3.getHeader(t,r),method:()=>t.method,url:()=>new URL(String(t.path),`${process.env.NODE_ENV==="development"?"http":"https"}://${String(h3.getHeader(t,"host"))}`),queryString:r=>String(h3.getQuery(t)[r]),transformResponse:r=>{let{res:s}=t.node;return s.statusCode=r.status,h3.setHeaders(t,r.headers),h3.send(t,r.body)}})}).createHandler();
|
|
29
29
|
|
|
30
30
|
exports.frameworkName = Ke;
|
|
31
31
|
exports.serve = to;
|
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-TDgxEYp-.js';
|
|
4
4
|
import '@novu/shared';
|
|
5
5
|
import 'json-schema-to-ts';
|
|
6
6
|
import 'zod';
|
package/dist/servers/lambda.js
CHANGED
|
@@ -7,7 +7,7 @@ var le = require('ora');
|
|
|
7
7
|
require('cross-fetch');
|
|
8
8
|
var N = require('chalk');
|
|
9
9
|
var shared = require('@novu/shared');
|
|
10
|
-
var
|
|
10
|
+
var Ie = require('sanitize-html');
|
|
11
11
|
var ke = require('ajv');
|
|
12
12
|
var Ve = require('ajv-formats');
|
|
13
13
|
var zodToJsonSchema = require('zod-to-json-schema');
|
|
@@ -16,15 +16,15 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
16
16
|
|
|
17
17
|
var le__default = /*#__PURE__*/_interopDefault(le);
|
|
18
18
|
var N__default = /*#__PURE__*/_interopDefault(N);
|
|
19
|
-
var
|
|
19
|
+
var Ie__default = /*#__PURE__*/_interopDefault(Ie);
|
|
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(`
|
|
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(
|
|
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 R=(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))(R||{});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.2.0";var P=Te,F="2024-06-26";var E=class extends Error{data},C=class extends E{statusCode=404},_=class extends E{statusCode=400},m=class extends E{statusCode=401},f=class extends E{statusCode=500},b=class extends E{statusCode=409};var L=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};}},D=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,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 Re=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:Ie__default.default.defaults.allowedTags.concat(["style","img","html","head","body","link","meta","title"]),allowedAttributes:!1,allowVulnerableTags:!0,parseStyleAttributes:!1,parser:{lowerCaseAttributeNames:!0}},me=s=>{if(!s)return s;let e=/^<!DOCTYPE .*?>/,t=s.match(e),r=Ie__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]=me(r):Array.isArray(r)?e[t]=r.map(o=>typeof o=="string"?me(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 ${Re(Y)}`},x=class extends _{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${Re(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.`);}},I=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 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=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),T=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(_e).includes(a.type)&&i?.disableOutputSanitization!==!0&&(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 o=`${e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action"} workflowId:`;console.log(`
|
|
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(h=>{d=h;}),u=h=>{d(),n=h;},w;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new D(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,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(h){w=h;}let T=process.hrtime(a),y=T[0],V=T[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}'.
|
|
27
|
-
${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),n=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),d=await this.executeProviders(e,t,n);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:n,providers:d}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new L(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(o)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),n=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:n,providers:await this.executeProviders(e,t,n)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new k(e);return r}};var ue=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new pe,this.client.addWorkflows(e.workflows),this.http=Ae(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":F,"novu-framework-sdk":P,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),o=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",n=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",d={};try{r==="POST"&&(d=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(d,n);let O=this.getPostActionMap(d,i,a,o),u=this.getGetActionMap(i,a);if(r==="POST")return await this.handlePostAction(o,O);if(r==="GET")return await this.handleGetAction(o,u);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new z(r))}getPostActionMap(e,t,r,o){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,t){return {discover:async()=>{let r=await this.client.discover();return this.createResponse(200,r)},"health-check":async()=>{let r=await this.client.healthCheck();return this.createResponse(200,r)},code:async()=>{let r=await this.client.getCode(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(S).includes(e)){let r=t[e];return r()}else throw new x(e,S)}async handleGetAction(e,t){if(Object.values(M).includes(e)){let r=t[e];return r()}else throw new x(e,M)}isBridgeError(e){return Object.values(
|
|
27
|
+
${a.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=le__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),n=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),d=await this.executeProviders(e,t,n);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:n,providers:d}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=le__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new L(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){try{let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{payload:t.payload||t.data,subscriber:t.subscriber,...t.payload||t.data});return JSON.parse(o)}catch(r){throw new K(t.workflowId,t.stepId,r)}}async createStepControls(e,t){let r=t.controls||t.inputs;return await this.validate(r,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let r=le__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),a=await t.resolve(i),n=await this.validate(a,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:n,providers:await this.executeProviders(e,t,n)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new k(e);return r}};var ue=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new pe,this.client.addWorkflows(e.workflows),this.http=Ae(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),r=await this.handleAction({actions:t});return t.transformResponse(r)}}getStaticHeaders(){let e=`novu-framework:v${this.client.version}`;return {"content-type":"application/json","access-control-allow-origin":"*","access-control-allow-methods":"GET, POST","access-control-allow-headers":"*","access-control-max-age":"604800","novu-framework-version":F,"novu-framework-sdk":P,"novu-framework-server":this.frameworkName,"user-agent":e}}createResponse(e,t){return {status:e,body:JSON.stringify(t),headers:{...this.getStaticHeaders()}}}createError(e){return {status:e.statusCode,body:JSON.stringify({message:e.message,data:e.data,code:e.code}),headers:this.getStaticHeaders()}}async handleAction({actions:e}){let t=await e.url(),r=await e.method(),o=t.searchParams.get("action")||"health-check",i=t.searchParams.get("workflowId")||"",a=t.searchParams.get("stepId")||"",n=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",d={};try{r==="POST"&&(d=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(d,n);let O=this.getPostActionMap(d,i,a,o),u=this.getGetActionMap(i,a);if(r==="POST")return await this.handlePostAction(o,O);if(r==="GET")return await this.handleGetAction(o,u);if(r==="OPTIONS")return this.createResponse(200,{})}catch(O){return this.handleError(O)}return this.createError(new z(r))}getPostActionMap(e,t,r,o){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)},preview:async()=>{let i=await this.client.executeWorkflow({...e,workflowId:t,stepId:r,action:o});return this.createResponse(200,i)}}}triggerAction(e){return async()=>{let t={name:e.workflowId,to:e.to,payload:e?.payload||{},transactionId:e.transactionId,overrides:e.overrides||{},...e.actor&&{actor:e.actor},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},r=await this.http.post("/events/trigger",t);return this.createResponse(200,r)}}getGetActionMap(e,t){return {discover:async()=>{let r=await this.client.discover();return this.createResponse(200,r)},"health-check":async()=>{let r=await this.client.healthCheck();return this.createResponse(200,r)},code:async()=>{let r=await this.client.getCode(e,t);return this.createResponse(200,r)}}}async handlePostAction(e,t){if(Object.values(S).includes(e)){let r=t[e];return r()}else throw new x(e,S)}async handleGetAction(e,t){if(Object.values(M).includes(e)){let r=t[e];return r()}else throw new x(e,M)}isBridgeError(e){return Object.values(R).includes(e?.code)}isPlatformError(e){return e?.statusCode>=400&&e?.statusCode<500}handleError(e){return this.isBridgeError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):this.isPlatformError(e)?this.createError(e):(console.error(e),this.createError(new v))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new ee;if(!this.client.secretKey)throw new oe;let[r,o]=t.split(",");if(!r||!o)throw new te;let[i,a]=r.split("="),[n,d]=o.split("=");if(Number(i)<Date.now()-1500)throw new re;if(!(this.hashHmac(this.client.secretKey,`${a}.${JSON.stringify(e)}`)===d))throw new H}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var Le="lambda",qr=s=>new ue({frameworkName:Le,...s,handler:t=>{let r=(o=>o.version==="2.0")(t);return {url:()=>{let o=r?t.requestContext.http.path:t.path,i=t.headers["x-forwarded-proto"]||"https",a=new URL(o,`${i}://${t.headers.host||t.headers.Host||""}`);for(let n in t.queryStringParameters)n&&a.searchParams.set(n,t.queryStringParameters[n]);return a},body:()=>{let o="{}";return t.body&&(o=t.isBase64Encoded?Buffer.from(t.body,"base64").toString():t.body),JSON.parse(o)},headers:o=>t.headers[o],queryString:o=>t.queryStringParameters?.[o],transformResponse:({body:o,status:i,headers:a})=>Promise.resolve({body:o,statusCode:i,headers:a}),method:()=>r?t.requestContext.http.method:t.httpMethod}}}).createHandler();
|
|
28
28
|
|
|
29
29
|
exports.frameworkName = Le;
|
|
30
30
|
exports.serve = qr;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { Request, Response } from 'express';
|
|
2
|
+
import { c as ServeHandlerOptions, C as Client, b as Workflow, ag as Either, au as INovuRequestHandlerOptions, w as SupportedFrameworkName, N as NovuRequestHandler } from '../handler-TDgxEYp-.js';
|
|
3
|
+
import { VercelRequest, VercelResponse } from '@vercel/node';
|
|
4
|
+
import * as _nestjs_common from '@nestjs/common';
|
|
5
|
+
import { Provider, FactoryProvider } from '@nestjs/common';
|
|
6
|
+
import '@novu/shared';
|
|
7
|
+
import 'json-schema-to-ts';
|
|
8
|
+
import 'zod';
|
|
9
|
+
|
|
10
|
+
type NovuModuleOptions = ServeHandlerOptions & {
|
|
11
|
+
apiPath: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
declare const NovuBaseModule: _nestjs_common.ConfigurableModuleCls<NovuModuleOptions, "register", "createNovuModuleOptions", (definition: NovuModuleOptions) => {
|
|
15
|
+
isGlobal: boolean;
|
|
16
|
+
client?: Client;
|
|
17
|
+
workflows: Array<Workflow>;
|
|
18
|
+
apiPath: string;
|
|
19
|
+
}>;
|
|
20
|
+
declare const NOVU_OPTIONS: string | symbol;
|
|
21
|
+
declare const OPTIONS_TYPE: ServeHandlerOptions & {
|
|
22
|
+
apiPath: string;
|
|
23
|
+
} & Partial<(definition: NovuModuleOptions) => {
|
|
24
|
+
isGlobal: boolean;
|
|
25
|
+
client?: Client;
|
|
26
|
+
workflows: Array<Workflow>;
|
|
27
|
+
apiPath: string;
|
|
28
|
+
}>;
|
|
29
|
+
declare const ASYNC_OPTIONS_TYPE: _nestjs_common.ConfigurableModuleAsyncOptions<NovuModuleOptions, "createNovuModuleOptions"> & Partial<(definition: NovuModuleOptions) => {
|
|
30
|
+
isGlobal: boolean;
|
|
31
|
+
client?: Client;
|
|
32
|
+
workflows: Array<Workflow>;
|
|
33
|
+
apiPath: string;
|
|
34
|
+
}>;
|
|
35
|
+
|
|
36
|
+
declare const REGISTER_API_PATH = "REGISTER_API_PATH";
|
|
37
|
+
|
|
38
|
+
declare class NovuHandler {
|
|
39
|
+
handler(incomingRequest: Either<VercelRequest, Request>, response: Either<Response, VercelResponse>): ReturnType<INovuRequestHandlerOptions['handler']>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
declare const frameworkName: SupportedFrameworkName;
|
|
43
|
+
declare class NovuClient {
|
|
44
|
+
private options;
|
|
45
|
+
private novuHandler;
|
|
46
|
+
novuRequestHandler: NovuRequestHandler;
|
|
47
|
+
constructor(options: ServeHandlerOptions, novuHandler: NovuHandler);
|
|
48
|
+
handleRequest(req: Request, res: Response): Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
declare class NovuController {
|
|
52
|
+
private novuService;
|
|
53
|
+
constructor(novuService: NovuClient);
|
|
54
|
+
handleGet(req: Request, res: Response): Promise<void>;
|
|
55
|
+
handlePost(req: Request, res: Response): Promise<void>;
|
|
56
|
+
handleOptions(req: Request, res: Response): Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* In NestJS, serve and register any declared workflows with Novu, making
|
|
61
|
+
* them available to be triggered by events.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```ts
|
|
65
|
+
* import { NovuModule } from "@novu/framework/nest";
|
|
66
|
+
* import { myWorkflow } from "./src/novu/workflows"; // Your workflows
|
|
67
|
+
*
|
|
68
|
+
* @Module({
|
|
69
|
+
* imports: [
|
|
70
|
+
* // Expose the middleware on our recommended path at `/api/novu`.
|
|
71
|
+
* NovuModule.register({
|
|
72
|
+
* apiPath: '/api/novu',
|
|
73
|
+
* workflows: [myWorkflow]
|
|
74
|
+
* })
|
|
75
|
+
* ]
|
|
76
|
+
* })
|
|
77
|
+
* export class AppModule {}
|
|
78
|
+
*
|
|
79
|
+
* const app = await NestFactory.create(AppModule);
|
|
80
|
+
*
|
|
81
|
+
* // Important: ensure you add JSON middleware to process incoming JSON POST payloads.
|
|
82
|
+
* app.use(express.json());
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
declare class NovuModule extends NovuBaseModule {
|
|
86
|
+
/**
|
|
87
|
+
* Register the Novu module
|
|
88
|
+
*
|
|
89
|
+
* @param options - The options to register the Novu module
|
|
90
|
+
* @param customProviders - Custom providers to register. These will be merged with the default providers.
|
|
91
|
+
* @returns The Novu module
|
|
92
|
+
*/
|
|
93
|
+
static register(options: typeof OPTIONS_TYPE, customProviders?: Provider[]): _nestjs_common.DynamicModule;
|
|
94
|
+
/**
|
|
95
|
+
* Register the Novu module asynchronously
|
|
96
|
+
*
|
|
97
|
+
* @param options - The options to register the Novu module
|
|
98
|
+
* @param customProviders - Custom providers to register. These will be merged with the default providers.
|
|
99
|
+
* @returns The Novu module
|
|
100
|
+
*/
|
|
101
|
+
static registerAsync(options: typeof ASYNC_OPTIONS_TYPE, customProviders?: Provider[]): _nestjs_common.DynamicModule;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Workaround to dynamically set the path for the controller.
|
|
106
|
+
*
|
|
107
|
+
* A custom provider is necessary to ensure that the controller path is set during
|
|
108
|
+
* application initialization, because NestJS does not support declaration of
|
|
109
|
+
* paths after the application has been initialized.
|
|
110
|
+
*
|
|
111
|
+
* @see https://github.com/nestjs/nest/issues/1438#issuecomment-863446608
|
|
112
|
+
*/
|
|
113
|
+
declare const registerApiPath: FactoryProvider;
|
|
114
|
+
|
|
115
|
+
export { NOVU_OPTIONS, NovuClient, NovuController, NovuHandler, NovuModule, type NovuModuleOptions, REGISTER_API_PATH, frameworkName, registerApiPath };
|