@novu/framework 2.0.0-canary.1 → 2.0.0-canary.3

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/index.js CHANGED
@@ -5,8 +5,9 @@ var liquidjs = require('liquidjs');
5
5
  var Te = require('ora');
6
6
  require('cross-fetch');
7
7
  var P = require('chalk');
8
- var Ze = require('ajv');
9
- var He = require('ajv-formats');
8
+ var shared = require('@novu/shared');
9
+ var He = require('ajv');
10
+ var et = require('ajv-formats');
10
11
  var zodToJsonSchema = require('zod-to-json-schema');
11
12
  var crypto = require('crypto');
12
13
 
@@ -14,14 +15,14 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
15
 
15
16
  var Te__default = /*#__PURE__*/_interopDefault(Te);
16
17
  var P__default = /*#__PURE__*/_interopDefault(P);
17
- var Ze__default = /*#__PURE__*/_interopDefault(Ze);
18
18
  var He__default = /*#__PURE__*/_interopDefault(He);
19
+ var et__default = /*#__PURE__*/_interopDefault(et);
19
20
 
20
- var V=(i=>(i.TRIGGER="trigger",i.EXECUTE="execute",i.PREVIEW="preview",i))(V||{}),F=(i=>(i.DISCOVER="discover",i.HEALTH_CHECK="health-check",i.CODE="code",i))(F||{});var Je=(t=>(t.SYNC="/v1/bridge/sync",t.DIFF="/v1/bridge/diff",t))(Je||{}),ve=5,Oe=1500;var w=(h=>(h.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",h.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",h.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",h.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",h.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",h.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",h.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",h.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",h.STEP_NOT_FOUND_ERROR="StepNotFoundError",h.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",h.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",h.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",h.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",h.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",h.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",h.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",h.INVALID_ACTION_ERROR="InvalidActionError",h.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",h.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",h.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",h.SIGNATURE_INVALID_ERROR="SignatureInvalidError",h.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",h.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",h.PLATFORM_ERROR="PlatformError",h.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",h.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",h))(w||{});var xe=(m=>(m.NOVU_SIGNATURE="novu-signature",m.NOVU_ANONYMOUS="novu-anonymous",m.NOVU_SIGNATURE_DEPRECATED="x-novu-signature",m.NOVU_ANONYMOUS_DEPRECATED="x-novu-anonymous",m.NOVU_FRAMEWORK_SDK="novu-framework-sdk",m.NOVU_FRAMEWORK_API="novu-framework-api",m.NOVU_FRAMEWORK_VERSION="novu-framework-version",m.USER_AGENT="user-agent",m.CONTENT_TYPE="content-type",m.ACCESS_CONTROL_ALLOW_ORIGIN="access-control-allow-origin",m.ACCESS_CONTROL_ALLOW_METHODS="access-control-allow-methods",m.ACCESS_CONTROL_ALLOW_HEADERS="access-control-allow-headers",m.ACCESS_CONTROL_MAX_AGE="access-control-max-age",m))(xe||{});var L=(i=>(i.POST="POST",i.GET="GET",i.OPTIONS="OPTIONS",i))(L||{});var Pe=(s=>(s.WORKFLOW_ID="workflowId",s.STEP_ID="stepId",s.ACTION="action",s.SOURCE="source",s))(Pe||{});var q=(o=>(o[o.CONTINUE=100]="CONTINUE",o[o.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",o[o.PROCESSING=102]="PROCESSING",o[o.EARLYHINTS=103]="EARLYHINTS",o[o.OK=200]="OK",o[o.CREATED=201]="CREATED",o[o.ACCEPTED=202]="ACCEPTED",o[o.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",o[o.NO_CONTENT=204]="NO_CONTENT",o[o.RESET_CONTENT=205]="RESET_CONTENT",o[o.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",o[o.AMBIGUOUS=300]="AMBIGUOUS",o[o.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",o[o.FOUND=302]="FOUND",o[o.SEE_OTHER=303]="SEE_OTHER",o[o.NOT_MODIFIED=304]="NOT_MODIFIED",o[o.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",o[o.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",o[o.BAD_REQUEST=400]="BAD_REQUEST",o[o.UNAUTHORIZED=401]="UNAUTHORIZED",o[o.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",o[o.FORBIDDEN=403]="FORBIDDEN",o[o.NOT_FOUND=404]="NOT_FOUND",o[o.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",o[o.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",o[o.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",o[o.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",o[o.CONFLICT=409]="CONFLICT",o[o.GONE=410]="GONE",o[o.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",o[o.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",o[o.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",o[o.URI_TOO_LONG=414]="URI_TOO_LONG",o[o.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",o[o.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",o[o.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",o[o.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",o[o.MISDIRECTED=421]="MISDIRECTED",o[o.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",o[o.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",o[o.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",o[o.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",o[o.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",o[o.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",o[o.BAD_GATEWAY=502]="BAD_GATEWAY",o[o.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",o[o.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",o[o.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",o))(q||{}),Vt=[500];var W=(i=>(i.WORKFLOW="workflow",i.PROVIDER="provider",i.STEP="step",i))(W||{});var B=(a=>(a.EMAIL="email",a.SMS="sms",a.PUSH="push",a.CHAT="chat",a.IN_APP="in_app",a))(B||{}),Qe=(i=>(i.DIGEST="digest",i.DELAY="delay",i.CUSTOM="custom",i))(Qe||{});var k=class extends Error{data},G=class extends k{statusCode=404},b=class extends k{statusCode=400},R=class extends k{statusCode=401},O=class extends k{statusCode=500},K=class extends k{statusCode=409};var X=class extends b{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};}},M=class extends b{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},z=class extends b{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},J=class extends b{code="ExecutionStateControlInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=i;}},Q=class extends b{code="ExecutionStateOutputInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=i;}},Z=class extends b{code="ExecutionStateResultInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=i;}},H=class extends b{code="ExecutionProviderOutputInvalidError";constructor(e,t,i,s){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${i}\` has invalid output. Please provide the correct provider output.`),this.data=s;}},ee=class extends b{code="WorkflowPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct payload.`),this.data=t;}},te=class extends Error{statusCode;message;code;constructor(e,t,i){super(i),this.statusCode=e,this.code=t;}};var Ie=async()=>{if(process.env.NOVU_BRIDGE_ORIGIN)return `${process.env.NOVU_BRIDGE_ORIGIN}/api/novu`;if(process.env.NEXT_PUBLIC_VERCEL_ENV==="preview"&&process.env.NEXT_PUBLIC_VERCEL_URL)return `https://${process.env.NEXT_PUBLIC_VERCEL_URL}/api/novu`;try{if(process.env.NODE_ENV==="development"){let e=await(await fetch("http://localhost:2022/.well-known/novu")).json();return `${e.tunnelOrigin}${e.route}`}}catch(n){console.error(n);}return ""};var d={info:n=>P__default.default.blue(n),warning:n=>P__default.default.yellow(n),error:n=>P__default.default.red(n),success:n=>P__default.default.green(n),underline:n=>P__default.default.underline(n),bold:n=>P__default.default.bold(n)},f={SUCCESS:d.success("\u2714"),ERROR:d.error("\u2717"),WARNING:d.warning("\u26A0"),INFO:d.info("\u2139"),ARROW:d.bold("\u2192"),MOCK:d.info("\u25CB"),HYDRATED:d.bold(d.info("\u2192")),STEP:d.info("\u03C3"),ACTION:d.info("\u03B1"),DURATION:d.info("\u0394"),PROVIDER:d.info("\u2699"),OUTPUT:d.info("\u21E2"),INPUT:d.info("\u21E0"),WORKFLOW:d.info("\u03C9"),STATE:d.info("\u03C3"),EXECUTE:d.info("\u03B5"),PREVIEW:d.info("\u03C1")};var ke=n=>Object.values(n).map(e=>`\`${e}\``).join(", "),ie=n=>n.replaceAll(/(\w)(\w*)/g,(e,t,i)=>t.toUpperCase()+i.toLowerCase()).replaceAll(/[\s-]+/g,"");var oe=(n,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(i,s)=>{let a=await fetch(t+"/v1"+i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${n}`},body:JSON.stringify(s)}),l=await a.json();if(a.ok)return l;throw new te(l.statusCode,l.error,l.message)},delete:async i=>(await fetch(t+"/v1"+i,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${n}`}})).json()}};var ne=class extends k{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ke(L)}`},C=class extends b{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ke(t)}`);}},se=class extends b{code="MissingSecretKeyError";constructor(){super("Missing secret key. Set the `NOVU_SECRET_KEY` environment variable or pass `secretKey` to the client options.");}};var re=class extends O{code="PlatformError";message="Something went wrong. Please try again later."};var I=class extends K{constructor(e,t){super(`${ie(e)} with id: \`${t}\` already exists. Please use a different id.`);}},S=class extends G{constructor(e,t){super(`${ie(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},D=class extends O{constructor(e,t){super(`Failed to execute ${ie(e)} with id: \`${t}\`. Please try again later.`);}};var ae=class extends S{code="ProviderNotFoundError";constructor(e){super("provider",e);}},le=class extends D{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var ce=class extends R{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.");}},pe=class extends R{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},de=class extends R{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},he=class extends R{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},ue=class extends R{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var me=class extends S{code="StepNotFoundError";constructor(e){super("step",e);}},fe=class extends I{code="StepAlreadyExistsError";constructor(e){super("step",e);}};var j=class extends S{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ye=class extends I{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var ge=class{ajv;compiledSchemas;constructor(){this.ajv=new Ze__default.default({useDefaults:!0,removeAdditional:"all"}),He__default.default(this.ajv),this.compiledSchemas=new Map;}isSchema(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.oneOf}async validate(e,t){let i=this.compiledSchemas.get(t);return i||(i=this.ajv.compile(t),this.compiledSchemas.set(t,i)),i(e)?{success:!0,data:e}:{success:!1,errors:i.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var _e=class{isSchema(e){return e.safeParseAsync!==void 0}async validate(e,t){let i=t.safeParse(e);return i.success?{success:!0,data:i.data}:{success:!1,errors:i.error.errors.map(s=>({path:`/${s.path.join("/")}`,message:s.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var De=[new _e,new ge],be=async(n,e)=>{for(let t of De)if(t.isSchema(n))return t.validate(e,n);throw new Error("Invalid schema")},y=n=>{for(let e of De)if(e.isSchema(n))return e.transformToJsonSchema(n);throw new Error("Invalid schema")};var Ne={name:"@novu/framework",version:"2.0.0-canary.1",description:"The Code-First Notifications Workflow SDK.",main:"./dist/index.js",types:"./dist/index.d.ts",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},private:!1,repository:{type:"git",url:"git+https://github.com/novuhq/novu.git"},files:["dist","README.md"],scripts:{preinstall:"npx only-allow pnpm",test:"vitest","test:watch":"vitest --watch",lint:"eslint src --ext .ts","lint:fix":"eslint src --ext .ts --fix",format:"prettier --check --ignore-path .gitignore .","format:fix":"prettier --write --ignore-path .gitignore .",build:"tsup","build:watch":"tsup --watch","$comment:bump:prerelease":"This is a workaround to support `npm version prerelease` with lerna","bump:prerelease":"npm version prerelease --preid=alpha & PID=$!; (sleep 1 && kill -9 $PID) & wait $PID","release:alpha":"pnpm bump:prerelease || pnpm build && npm publish"},keywords:["novu","code-first","workflows","durable","sdk","notifications","email","sms","push","webhooks","next","nuxt","h3","express"],author:"Novu Team <engineering@novu.co>",license:"ISC",exports:{".":{require:"./dist/index.js",import:"./dist/index.js",types:"./dist/index.d.ts"},"./express":{require:"./dist/express.js",import:"./dist/express.js",types:"./dist/express.d.ts"},"./next":{require:"./dist/next.js",import:"./dist/next.js",types:"./dist/next.d.ts"},"./nuxt":{require:"./dist/nuxt.js",import:"./dist/nuxt.js",types:"./dist/nuxt.d.ts"},"./h3":{require:"./dist/h3.js",import:"./dist/h3.js",types:"./dist/h3.d.ts"},"./sveltekit":{require:"./dist/sveltekit.js",import:"./dist/sveltekit.js",types:"./dist/sveltekit.d.ts"},"./remix":{require:"./dist/remix.js",import:"./dist/remix.js",types:"./dist/remix.d.ts"}},peerDependencies:{"@sveltejs/kit":">=1.27.3","@vercel/node":">=2.15.9",express:">=4.19.2",h3:">=1.8.1",next:">=12.0.0",zod:">=3.0.0","zod-to-json-schema":">=3.0.0"},peerDependenciesMeta:{"@sveltejs/kit":{optional:!0},"@vercel/node":{optional:!0},express:{optional:!0},fastify:{optional:!0},h3:{optional:!0},next:{optional:!0},zod:{optional:!0},"zod-to-json-schema":{optional:!0}},devDependencies:{"@sveltejs/kit":"^1.27.3","@types/express":"^4.17.13","@types/json-schema":"^7.0.15","@types/node":"^20.11.20","@vercel/node":"^2.15.9",express:"^4.19.2",h3:"^1.11.1",next:"^13.5.4",prettier:"^3.2.5","ts-node":"^10.9.2",tsup:"^8.0.2",typescript:"^5.3.3",vitest:"^1.2.1",zod:"^3.23.0","zod-to-json-schema":"^3.23.0"},dependencies:{"@novu/shared":"workspace:*",ajv:"^8.12.0","ajv-formats":"^2.1.1","better-ajv-errors":"^1.2.0",chalk:"^4.1.2","cross-fetch":"^4.0.0","json-schema-faker":"^0.5.6","json-schema-to-ts":"^3.0.0",liquidjs:"^10.13.1",ora:"^5.4.1"}};var $=Ne.version,we="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function ot(){return process.env.NODE_ENV==="development"}var U=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=$;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!ot()};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(i=>i.workflowId===t.definition.workflowId))throw new ye(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((i,s)=>i+s.steps.length,0);return {status:"ok",sdkVersion:$,frameworkVersion:we,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(i=>i.workflowId===e);if(t)return t;throw new j(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(a=>a.stepId===t);if(s)return s;throw new me(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(y(e))}async validate(e,t,i,s,a,l,c){let p=await be(t,e);if(p.success)return p.data;switch(i){case"event":this.throwInvalidEvent(s,a,p.errors);case"step":this.throwInvalidStep(l,s,a,p.errors);case"provider":this.throwInvalidProvider(l,c,s,a,p.errors);default:throw new Error(`Invalid component: '${i}'`)}}throwInvalidProvider(e,t,i,s,a){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(i){case"output":throw new H(s,e,t,a);default:throw new Error(`Invalid payload type: '${i}'`)}}throwInvalidStep(e,t,i,s){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new Q(i,e,s);case"result":throw new Z(i,e,s);case"controls":throw new J(i,e,s);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,i){switch(e){case"controls":throw new z(t,i);case"payload":throw new M(t,i);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(i,s,a)=>{let l=this.getStep(e.workflowId,i),c=nt(e),p=await this.createStepControls(l,c),u=e.action==="preview";if(!u&&await this.shouldSkip(a?.skip,p))return t({options:{skip:!0}}),{};let g=this.previewStep.bind(this),x=this.executeStep.bind(this),m=await(u?g:x)(e,{...l,providers:l.providers.map(v=>{let N=a?.providers?.[v.type];if(!N)throw new ae(v.type);return {...v,resolve:N}}),resolve:s});return i===e.stepId&&t(m),m.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
21
- ${d.bold(d.underline(s))} '${e.workflowId}'`);let a=this.getWorkflow(e.workflowId),l=process.hrtime(),c={outputs:{},providers:{},options:{}},p,u=new Promise(A=>{p=A;}),g=A=>{p(),c=A;},x;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new M(e.workflowId,{message:"Event `payload` is required"});let A=await this.createExecutionPayload(e,a);await Promise.race([u,a.execute({payload:A,environment:{},inputs:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,g),sms:this.executeStepFactory(e,g),inApp:this.executeStepFactory(e,g),digest:this.executeStepFactory(e,g),delay:this.executeStepFactory(e,g),push:this.executeStepFactory(e,g),chat:this.executeStepFactory(e,g),custom:this.executeStepFactory(e,g)}})]);}catch(A){x=A;}let Y=process.hrtime(l),m=Y[0],v=Y[1],N=m*1e3+v/1e6,Xe=x?f.ERROR:f.SUCCESS,ze=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Xe} ${ze} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,N,x),x)throw x;return {outputs:c.outputs,providers:c.providers,options:c.options,metadata:{status:"success",error:!1,duration:N}}}async createExecutionPayload(e,t){let i=e.payload||e.data;if(e.action==="preview"){let a=this.mock(t.payload.schema);i=Object.assign(a,i);}return await this.validate(i,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,i){let s=i?f.ERROR:f.SUCCESS,a=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",l=i?"Failed to execute":a,c=i?d.error:d.success,p=`${s} ${l} workflowId: '${e.workflowId}`;console.log(`
21
+ var C=(i=>(i.TRIGGER="trigger",i.EXECUTE="execute",i.PREVIEW="preview",i))(C||{}),L=(i=>(i.DISCOVER="discover",i.HEALTH_CHECK="health-check",i.CODE="code",i))(L||{});var Je=(t=>(t.SYNC="/v1/bridge/sync",t.DIFF="/v1/bridge/diff",t))(Je||{}),ve=5,Oe=1500;var w=(h=>(h.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",h.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",h.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",h.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",h.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",h.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",h.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",h.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",h.STEP_NOT_FOUND_ERROR="StepNotFoundError",h.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",h.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",h.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",h.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",h.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",h.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",h.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",h.INVALID_ACTION_ERROR="InvalidActionError",h.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",h.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",h.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",h.SIGNATURE_INVALID_ERROR="SignatureInvalidError",h.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",h.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",h.BRIDGE_ERROR="BridgeError",h.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",h.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",h))(w||{});var xe=(m=>(m.NOVU_SIGNATURE="novu-signature",m.NOVU_ANONYMOUS="novu-anonymous",m.NOVU_SIGNATURE_DEPRECATED="x-novu-signature",m.NOVU_ANONYMOUS_DEPRECATED="x-novu-anonymous",m.NOVU_FRAMEWORK_SDK="novu-framework-sdk",m.NOVU_FRAMEWORK_API="novu-framework-api",m.NOVU_FRAMEWORK_VERSION="novu-framework-version",m.USER_AGENT="user-agent",m.CONTENT_TYPE="content-type",m.ACCESS_CONTROL_ALLOW_ORIGIN="access-control-allow-origin",m.ACCESS_CONTROL_ALLOW_METHODS="access-control-allow-methods",m.ACCESS_CONTROL_ALLOW_HEADERS="access-control-allow-headers",m.ACCESS_CONTROL_MAX_AGE="access-control-max-age",m))(xe||{});var q=(i=>(i.POST="POST",i.GET="GET",i.OPTIONS="OPTIONS",i))(q||{});var Pe=(n=>(n.WORKFLOW_ID="workflowId",n.STEP_ID="stepId",n.ACTION="action",n.SOURCE="source",n))(Pe||{});var W=(o=>(o[o.CONTINUE=100]="CONTINUE",o[o.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",o[o.PROCESSING=102]="PROCESSING",o[o.EARLYHINTS=103]="EARLYHINTS",o[o.OK=200]="OK",o[o.CREATED=201]="CREATED",o[o.ACCEPTED=202]="ACCEPTED",o[o.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",o[o.NO_CONTENT=204]="NO_CONTENT",o[o.RESET_CONTENT=205]="RESET_CONTENT",o[o.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",o[o.AMBIGUOUS=300]="AMBIGUOUS",o[o.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",o[o.FOUND=302]="FOUND",o[o.SEE_OTHER=303]="SEE_OTHER",o[o.NOT_MODIFIED=304]="NOT_MODIFIED",o[o.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",o[o.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",o[o.BAD_REQUEST=400]="BAD_REQUEST",o[o.UNAUTHORIZED=401]="UNAUTHORIZED",o[o.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",o[o.FORBIDDEN=403]="FORBIDDEN",o[o.NOT_FOUND=404]="NOT_FOUND",o[o.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",o[o.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",o[o.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",o[o.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",o[o.CONFLICT=409]="CONFLICT",o[o.GONE=410]="GONE",o[o.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",o[o.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",o[o.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",o[o.URI_TOO_LONG=414]="URI_TOO_LONG",o[o.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",o[o.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",o[o.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",o[o.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",o[o.MISDIRECTED=421]="MISDIRECTED",o[o.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",o[o.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",o[o.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",o[o.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",o[o.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",o[o.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",o[o.BAD_GATEWAY=502]="BAD_GATEWAY",o[o.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",o[o.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",o[o.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",o))(W||{}),Ft=[500];var B=(i=>(i.WORKFLOW="workflow",i.PROVIDER="provider",i.STEP="step",i))(B||{});var G=(a=>(a.EMAIL="email",a.SMS="sms",a.PUSH="push",a.CHAT="chat",a.IN_APP="in_app",a))(G||{}),Qe=(i=>(i.DIGEST="digest",i.DELAY="delay",i.CUSTOM="custom",i))(Qe||{});var T=class extends Error{data},K=class extends T{statusCode=404},b=class extends T{statusCode=400},R=class extends T{statusCode=401},O=class extends T{statusCode=500},X=class extends T{statusCode=409};var z=class extends b{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};}},j=class extends b{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},J=class extends b{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},Q=class extends b{code="ExecutionStateControlInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=i;}},Z=class extends b{code="ExecutionStateOutputInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=i;}},H=class extends b{code="ExecutionStateResultInvalidError";constructor(e,t,i){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=i;}},ee=class extends b{code="ExecutionProviderOutputInvalidError";constructor(e,t,i,n){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${i}\` has invalid output. Please provide the correct provider output.`),this.data=n;}},te=class extends b{code="WorkflowPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct payload.`),this.data=t;}},ie=class extends T{statusCode;data;code;constructor(e,t,i){super(),this.data={message:i},this.statusCode=e,this.code=t;}};var Ie=async()=>{if(process.env.NOVU_BRIDGE_ORIGIN)return `${process.env.NOVU_BRIDGE_ORIGIN}/api/novu`;if(process.env.NEXT_PUBLIC_VERCEL_ENV==="preview"&&process.env.NEXT_PUBLIC_VERCEL_URL)return `https://${process.env.NEXT_PUBLIC_VERCEL_URL}/api/novu`;try{if(process.env.NODE_ENV==="development"){let e=await(await fetch("http://localhost:2022/.well-known/novu")).json();return `${e.tunnelOrigin}${e.route}`}}catch(s){console.error(s);}return ""};var d={info:s=>P__default.default.blue(s),warning:s=>P__default.default.yellow(s),error:s=>P__default.default.red(s),success:s=>P__default.default.green(s),underline:s=>P__default.default.underline(s),bold:s=>P__default.default.bold(s)},f={SUCCESS:d.success("\u2714"),ERROR:d.error("\u2717"),WARNING:d.warning("\u26A0"),INFO:d.info("\u2139"),ARROW:d.bold("\u2192"),MOCK:d.info("\u25CB"),HYDRATED:d.bold(d.info("\u2192")),STEP:d.info("\u03C3"),ACTION:d.info("\u03B1"),DURATION:d.info("\u0394"),PROVIDER:d.info("\u2699"),OUTPUT:d.info("\u21E2"),INPUT:d.info("\u21E0"),WORKFLOW:d.info("\u03C9"),STATE:d.info("\u03C3"),EXECUTE:d.info("\u03B5"),PREVIEW:d.info("\u03C1")};var ke=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),oe=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,i)=>t.toUpperCase()+i.toLowerCase()).replaceAll(/[\s-]+/g,"");var ne=(s,e="https://api.novu.co")=>{let t=process.env.NOVU_API_URL||e;return {post:async(i,n)=>{let a=await fetch(t+"/v1"+i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`},body:JSON.stringify(n)}),l=await a.json();if(a.ok)return l;throw shared.checkIsResponseError(l)?new ie(l.statusCode,l.error,l.message):new I("Error processing API request to Novu Cloud from Bridge application.")},delete:async i=>(await fetch(t+"/v1"+i,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`}})).json()}};var se=class extends T{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${ke(q)}`},$=class extends b{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${ke(t)}`);}},re=class extends b{code="MissingSecretKeyError";constructor(){super("Missing secret key. Set the `NOVU_SECRET_KEY` environment variable or pass `secretKey` to the client options.");}};var I=class extends O{code="BridgeError";message="Something went wrong. Please try again later."};var D=class extends X{constructor(e,t){super(`${oe(e)} with id: \`${t}\` already exists. Please use a different id.`);}},S=class extends K{constructor(e,t){super(`${oe(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},N=class extends O{constructor(e,t){super(`Failed to execute ${oe(e)} with id: \`${t}\`. Please try again later.`);}};var ae=class extends S{code="ProviderNotFoundError";constructor(e){super("provider",e);}},le=class extends N{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var ce=class extends R{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.");}},pe=class extends R{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},de=class extends R{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},he=class extends R{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},ue=class extends R{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var me=class extends S{code="StepNotFoundError";constructor(e){super("step",e);}},fe=class extends D{code="StepAlreadyExistsError";constructor(e){super("step",e);}};var U=class extends S{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},ye=class extends D{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var ge=class{ajv;compiledSchemas;constructor(){this.ajv=new He__default.default({useDefaults:!0,removeAdditional:"all"}),et__default.default(this.ajv),this.compiledSchemas=new Map;}isSchema(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.oneOf}async validate(e,t){let i=this.compiledSchemas.get(t);return i||(i=this.ajv.compile(t),this.compiledSchemas.set(t,i)),i(e)?{success:!0,data:e}:{success:!1,errors:i.errors.map(a=>({path:a.instancePath,message:a.message}))}}transformToJsonSchema(e){return e}};var _e=class{isSchema(e){return e.safeParseAsync!==void 0}async validate(e,t){let i=t.safeParse(e);return i.success?{success:!0,data:i.data}:{success:!1,errors:i.error.errors.map(n=>({path:`/${n.path.join("/")}`,message:n.message}))}}transformToJsonSchema(e){try{return zodToJsonSchema.zodToJsonSchema(e)}catch(t){throw t?.message?.includes("Cannot find module")&&console.error("Tried to use a zod schema in @novu/framework without `zod-to-json-schema` installed. Please install it by running `npm install zod-to-json-schema`."),t}}};var De=[new _e,new ge],be=async(s,e)=>{for(let t of De)if(t.isSchema(s))return t.validate(e,s);throw new Error("Invalid schema")},y=s=>{for(let e of De)if(e.isSchema(s))return e.transformToJsonSchema(s);throw new Error("Invalid schema")};var Ne={name:"@novu/framework",version:"2.0.0-canary.3",description:"The Code-First Notifications Workflow SDK.",main:"./dist/index.js",types:"./dist/index.d.ts",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},private:!1,repository:{type:"git",url:"git+https://github.com/novuhq/novu.git"},files:["dist","README.md"],scripts:{preinstall:"npx only-allow pnpm",test:"vitest","test:watch":"vitest --watch",lint:"eslint src --ext .ts","lint:fix":"eslint src --ext .ts --fix",format:"prettier --check --ignore-path .gitignore .","format:fix":"prettier --write --ignore-path .gitignore .",build:"tsup","build:watch":"tsup --watch","$comment:bump:prerelease":"This is a workaround to support `npm version prerelease` with lerna","bump:prerelease":"npm version prerelease --preid=alpha & PID=$!; (sleep 1 && kill -9 $PID) & wait $PID","release:alpha":"pnpm bump:prerelease || pnpm build && npm publish"},keywords:["novu","code-first","workflows","durable","sdk","notifications","email","sms","push","webhooks","next","nuxt","h3","express"],author:"Novu Team <engineering@novu.co>",license:"ISC",exports:{".":{require:"./dist/index.js",import:"./dist/index.js",types:"./dist/index.d.ts"},"./express":{require:"./dist/express.js",import:"./dist/express.js",types:"./dist/express.d.ts"},"./next":{require:"./dist/next.js",import:"./dist/next.js",types:"./dist/next.d.ts"},"./nuxt":{require:"./dist/nuxt.js",import:"./dist/nuxt.js",types:"./dist/nuxt.d.ts"},"./h3":{require:"./dist/h3.js",import:"./dist/h3.js",types:"./dist/h3.d.ts"},"./sveltekit":{require:"./dist/sveltekit.js",import:"./dist/sveltekit.js",types:"./dist/sveltekit.d.ts"},"./remix":{require:"./dist/remix.js",import:"./dist/remix.js",types:"./dist/remix.d.ts"}},peerDependencies:{"@sveltejs/kit":">=1.27.3","@vercel/node":">=2.15.9",express:">=4.19.2",h3:">=1.8.1",next:">=12.0.0",zod:">=3.0.0","zod-to-json-schema":">=3.0.0"},peerDependenciesMeta:{"@sveltejs/kit":{optional:!0},"@vercel/node":{optional:!0},express:{optional:!0},fastify:{optional:!0},h3:{optional:!0},next:{optional:!0},zod:{optional:!0},"zod-to-json-schema":{optional:!0}},devDependencies:{"@sveltejs/kit":"^1.27.3","@types/express":"^4.17.13","@types/json-schema":"^7.0.15","@types/node":"^20.11.20","@vercel/node":"^2.15.9",express:"^4.19.2",h3:"^1.11.1",next:"^13.5.4",prettier:"^3.2.5","ts-node":"^10.9.2",tsup:"^8.0.2",typescript:"^5.3.3",vitest:"^1.2.1",zod:"^3.23.0","zod-to-json-schema":"^3.23.0"},dependencies:{"@novu/shared":"^2.0.0-canary.0",ajv:"^8.12.0","ajv-formats":"^2.1.1","better-ajv-errors":"^1.2.0",chalk:"^4.1.2","cross-fetch":"^4.0.0","json-schema-faker":"^0.5.6","json-schema-to-ts":"^3.0.0",liquidjs:"^10.13.1",ora:"^5.4.1"}};var Y=Ne.version,we="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function nt(){return process.env.NODE_ENV==="development"}var F=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:!nt()};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(i=>i.workflowId===t.definition.workflowId))throw new ye(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((i,n)=>i+n.steps.length,0);return {status:"ok",sdkVersion:Y,frameworkVersion:we,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(i=>i.workflowId===e);if(t)return t;throw new U(e)}getStep(e,t){let n=this.getWorkflow(e).steps.find(a=>a.stepId===t);if(n)return n;throw new me(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(y(e))}async validate(e,t,i,n,a,l,c){let p=await be(t,e);if(p.success)return p.data;switch(i){case"event":this.throwInvalidEvent(n,a,p.errors);case"step":this.throwInvalidStep(l,n,a,p.errors);case"provider":this.throwInvalidProvider(l,c,n,a,p.errors);default:throw new Error(`Invalid component: '${i}'`)}}throwInvalidProvider(e,t,i,n,a){if(!e)throw new Error("stepId is required");if(!t)throw new Error("providerId is required");switch(i){case"output":throw new ee(n,e,t,a);default:throw new Error(`Invalid payload type: '${i}'`)}}throwInvalidStep(e,t,i,n){if(!e)throw new Error("stepId is required");switch(t){case"output":throw new Z(i,e,n);case"result":throw new H(i,e,n);case"controls":throw new Q(i,e,n);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,i){switch(e){case"controls":throw new J(t,i);case"payload":throw new j(t,i);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(i,n,a)=>{let l=this.getStep(e.workflowId,i),c=st(e),p=await this.createStepControls(l,c),u=e.action==="preview";if(!u&&await this.shouldSkip(a?.skip,p))return t({options:{skip:!0}}),{};let g=this.previewStep.bind(this),k=this.executeStep.bind(this),m=await(u?g:k)(e,{...l,providers:l.providers.map(v=>{let M=a?.providers?.[v.type];if(!M)throw new ae(v.type);return {...v,resolve:M}}),resolve:n});return i===e.stepId&&t(m),m.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let n=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
22
+ ${d.bold(d.underline(n))} '${e.workflowId}'`);let a=this.getWorkflow(e.workflowId),l=process.hrtime(),c={outputs:{},providers:{},options:{}},p,u=new Promise(A=>{p=A;}),g=A=>{p(),c=A;},k;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new j(e.workflowId,{message:"Event `payload` is required"});let A=await this.createExecutionPayload(e,a);await Promise.race([u,a.execute({payload:A,environment:{},inputs:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,g),sms:this.executeStepFactory(e,g),inApp:this.executeStepFactory(e,g),digest:this.executeStepFactory(e,g),delay:this.executeStepFactory(e,g),push:this.executeStepFactory(e,g),chat:this.executeStepFactory(e,g),custom:this.executeStepFactory(e,g)}})]);}catch(A){k=A;}let V=process.hrtime(l),m=V[0],v=V[1],M=m*1e3+v/1e6,Xe=k?f.ERROR:f.SUCCESS,ze=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Xe} ${ze} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,M,k),k)throw k;return {outputs:c.outputs,providers:c.providers,options:c.options,metadata:{status:"success",error:!1,duration:M}}}async createExecutionPayload(e,t){let i=e.payload||e.data;if(e.action==="preview"){let a=this.mock(t.payload.schema);i=Object.assign(a,i);}return await this.validate(i,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,i){let n=i?f.ERROR:f.SUCCESS,a=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",l=i?"Failed to execute":a,c=i?d.error:d.success,p=`${n} ${l} workflowId: '${e.workflowId}`;console.log(`
22
23
  ${d.bold(c(p))}'`),console.log(` \u251C ${f.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${f.ACTION} action: '${e.action}'`),console.log(` \u2514 ${f.DURATION} duration: '${t.toFixed(2)}ms'
23
- `);}async executeProviders(e,t,i){return t.providers.reduce(async(s,a)=>{let l=await s,c=this.previewProvider.bind(this),p=this.executeProvider.bind(this),g=await(e.action==="preview"?c:p)(e,t,a,i);return {...l,[a.type]:g}},Promise.resolve({}))}previewProvider(e,t,i,s){return console.log(` ${f.MOCK} Mocked provider: \`${i.type}\``),this.mock(i.outputs.schema)}async executeProvider(e,t,i,s){let a=Te__default.default({indent:2}).start(`Executing provider: \`${i.type}\``);try{if(e.stepId===t.stepId){let l=await this.createStepControls(t,e),c=await i.resolve({controls:l,outputs:s}),p=await this.validate(c,i.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,i.type);return a.succeed(`Executed provider: \`${i.type}\``),p}else a.stopAndPersist({symbol:f.HYDRATED,text:`Hydrated provider: \`${i.type}\``});}catch(l){throw a.stopAndPersist({symbol:f.ERROR,text:`Failed to execute provider: \`${i.type}\``}),new le(`Failed to execute provider: '${i.type}'.
24
- ${l.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let i=Te__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let s=await this.createStepControls(t,e),a=await this.compileControls(s,e),l=await t.resolve(a),c=await this.validate(l,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),p=await this.executeProviders(e,t,c);return i.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:c,providers:p}}catch(s){throw i.stopAndPersist({prefixText:"",symbol:f.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),s}}else {let i=Te__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let s=e.state.find(a=>a.stepId===t.stepId);if(s){let a=await this.validate(s.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return i.stopAndPersist({symbol:f.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:a,providers:await this.executeProviders(e,t,a)}}else throw new X(e.workflowId,t.stepId)}catch(s){throw i.stopAndPersist({symbol:f.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),s}}}async compileControls(e,t){let i=this.templateEngine.parse(JSON.stringify(e)),s=await this.templateEngine.render(i,{...t.payload||t.data,subscriber:t.subscriber});return JSON.parse(s)}async createStepControls(e,t){let i=t.controls||t.inputs;return await this.validate(i,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let i=Te__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let s=await this.createStepControls(t,e),a=await this.compileControls(s,e),l=await t.resolve(a),c=await this.validate(l,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return i.stopAndPersist({symbol:f.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:c,providers:await this.executeProviders(e,t,c)}}else {let s=this.mock(t.results.schema);return i.stopAndPersist({symbol:f.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:s,providers:await this.executeProviders(e,t,s)}}}catch(s){throw i.stopAndPersist({symbol:f.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 i;if(e)t?i=this.getStepCode(e,t):i=this.getWorkflowCode(e);else throw new j(e);return i}};function nt(n){return JSON.parse(JSON.stringify(n))}var st=(r=>(r.EVERY_SECOND="* * * * * *",r.EVERY_5_SECONDS="*/5 * * * * *",r.EVERY_10_SECONDS="*/10 * * * * *",r.EVERY_30_SECONDS="*/30 * * * * *",r.EVERY_MINUTE="*/1 * * * *",r.EVERY_5_MINUTES="0 */5 * * * *",r.EVERY_10_MINUTES="0 */10 * * * *",r.EVERY_30_MINUTES="0 */30 * * * *",r.EVERY_HOUR="0 0-23/1 * * *",r.EVERY_2_HOURS="0 0-23/2 * * *",r.EVERY_3_HOURS="0 0-23/3 * * *",r.EVERY_4_HOURS="0 0-23/4 * * *",r.EVERY_5_HOURS="0 0-23/5 * * *",r.EVERY_6_HOURS="0 0-23/6 * * *",r.EVERY_7_HOURS="0 0-23/7 * * *",r.EVERY_8_HOURS="0 0-23/8 * * *",r.EVERY_9_HOURS="0 0-23/9 * * *",r.EVERY_10_HOURS="0 0-23/10 * * *",r.EVERY_11_HOURS="0 0-23/11 * * *",r.EVERY_12_HOURS="0 0-23/12 * * *",r.EVERY_DAY_AT_1AM="0 01 * * *",r.EVERY_DAY_AT_2AM="0 02 * * *",r.EVERY_DAY_AT_3AM="0 03 * * *",r.EVERY_DAY_AT_4AM="0 04 * * *",r.EVERY_DAY_AT_5AM="0 05 * * *",r.EVERY_DAY_AT_6AM="0 06 * * *",r.EVERY_DAY_AT_7AM="0 07 * * *",r.EVERY_DAY_AT_8AM="0 08 * * *",r.EVERY_DAY_AT_9AM="0 09 * * *",r.EVERY_DAY_AT_10AM="0 10 * * *",r.EVERY_DAY_AT_11AM="0 11 * * *",r.EVERY_DAY_AT_NOON="0 12 * * *",r.EVERY_DAY_AT_1PM="0 13 * * *",r.EVERY_DAY_AT_2PM="0 14 * * *",r.EVERY_DAY_AT_3PM="0 15 * * *",r.EVERY_DAY_AT_4PM="0 16 * * *",r.EVERY_DAY_AT_5PM="0 17 * * *",r.EVERY_DAY_AT_6PM="0 18 * * *",r.EVERY_DAY_AT_7PM="0 19 * * *",r.EVERY_DAY_AT_8PM="0 20 * * *",r.EVERY_DAY_AT_9PM="0 21 * * *",r.EVERY_DAY_AT_10PM="0 22 * * *",r.EVERY_DAY_AT_11PM="0 23 * * *",r.EVERY_DAY_AT_MIDNIGHT="0 0 * * *",r.EVERY_WEEK="0 0 * * 0",r.EVERY_WEEKDAY="0 0 * * 1-5",r.EVERY_WEEKEND="0 0 * * 6,0",r.EVERY_1ST_DAY_OF_MONTH_AT_MIDNIGHT="0 0 1 * *",r.EVERY_1ST_DAY_OF_MONTH_AT_NOON="0 12 1 * *",r.EVERY_2ND_HOUR="0 */2 * * *",r.EVERY_2ND_HOUR_FROM_1AM_THROUGH_11PM="0 1-23/2 * * *",r.EVERY_2ND_MONTH="0 0 1 */2 *",r.EVERY_QUARTER="0 0 1 */3 *",r.EVERY_6_MONTHS="0 0 1 */6 *",r.EVERY_YEAR="0 0 1 0 *",r.EVERY_30_MINUTES_BETWEEN_9AM_AND_5PM="0 */30 9-17 * * *",r.EVERY_30_MINUTES_BETWEEN_9AM_AND_6PM="0 */30 9-18 * * *",r.EVERY_30_MINUTES_BETWEEN_10AM_AND_7PM="0 */30 10-19 * * *",r.MONDAY_TO_FRIDAY_AT_1AM="0 0 01 * * 1-5",r.MONDAY_TO_FRIDAY_AT_2AM="0 0 02 * * 1-5",r.MONDAY_TO_FRIDAY_AT_3AM="0 0 03 * * 1-5",r.MONDAY_TO_FRIDAY_AT_4AM="0 0 04 * * 1-5",r.MONDAY_TO_FRIDAY_AT_5AM="0 0 05 * * 1-5",r.MONDAY_TO_FRIDAY_AT_6AM="0 0 06 * * 1-5",r.MONDAY_TO_FRIDAY_AT_7AM="0 0 07 * * 1-5",r.MONDAY_TO_FRIDAY_AT_8AM="0 0 08 * * 1-5",r.MONDAY_TO_FRIDAY_AT_9AM="0 0 09 * * 1-5",r.MONDAY_TO_FRIDAY_AT_09_30AM="0 30 09 * * 1-5",r.MONDAY_TO_FRIDAY_AT_10AM="0 0 10 * * 1-5",r.MONDAY_TO_FRIDAY_AT_11AM="0 0 11 * * 1-5",r.MONDAY_TO_FRIDAY_AT_11_30AM="0 30 11 * * 1-5",r.MONDAY_TO_FRIDAY_AT_12PM="0 0 12 * * 1-5",r.MONDAY_TO_FRIDAY_AT_1PM="0 0 13 * * 1-5",r.MONDAY_TO_FRIDAY_AT_2PM="0 0 14 * * 1-5",r.MONDAY_TO_FRIDAY_AT_3PM="0 0 15 * * 1-5",r.MONDAY_TO_FRIDAY_AT_4PM="0 0 16 * * 1-5",r.MONDAY_TO_FRIDAY_AT_5PM="0 0 17 * * 1-5",r.MONDAY_TO_FRIDAY_AT_6PM="0 0 18 * * 1-5",r.MONDAY_TO_FRIDAY_AT_7PM="0 0 19 * * 1-5",r.MONDAY_TO_FRIDAY_AT_8PM="0 0 20 * * 1-5",r.MONDAY_TO_FRIDAY_AT_9PM="0 0 21 * * 1-5",r.MONDAY_TO_FRIDAY_AT_10PM="0 0 22 * * 1-5",r.MONDAY_TO_FRIDAY_AT_11PM="0 0 23 * * 1-5",r))(st||{});var rt=(u=>(u.PENDING="pending",u.QUEUED="queued",u.RUNNING="running",u.COMPLETED="completed",u.FAILED="failed",u.DELAYED="delayed",u.CANCELED="canceled",u.MERGED="merged",u.SKIPPED="skipped",u))(rt||{});var Se=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new U,this.client.addWorkflows(e.workflows),this.http=oe(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),i=await this.handleAction({actions:t});return t.transformResponse(i)}}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":we,"novu-framework-sdk":$,"novu-framework-api":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(),i=await e.method(),s=t.searchParams.get("action")||"",a=t.searchParams.get("workflowId")||"",l=t.searchParams.get("stepId")||"",c=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",p={};try{i==="POST"&&(p=await e.body());}catch{}try{s!=="health-check"&&this.validateHmac(p,c);let u=this.getPostActionMap(p,a,l,s),g=this.getGetActionMap(a,l);if(i==="POST")return await this.handlePostAction(s,u);if(i==="GET")return await this.handleGetAction(s,g);if(i==="OPTIONS")return this.createResponse(200,{})}catch(u){return this.handleError(u)}return this.createError(new ne(i))}getPostActionMap(e,t,i,s){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let a=await this.client.executeWorkflow({...e,workflowId:t,stepId:i,action:s});return this.createResponse(200,a)},preview:async()=>{let a=await this.client.executeWorkflow({...e,workflowId:t,stepId:i,action:s});return this.createResponse(200,a)}}}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.tenant&&{tenant:e.tenant},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},i=await this.http.post("/events/trigger",t);return this.createResponse(200,i)}}getGetActionMap(e,t){return {discover:async()=>{let i=await this.client.discover();return this.createResponse(200,i)},"health-check":async()=>{let i=await this.client.healthCheck();return this.createResponse(200,i)},code:async()=>{let i=await this.client.getCode(e,t);return this.createResponse(200,i)}}}async handlePostAction(e,t){if(Object.values(V).includes(e)){let i=t[e];return i()}else throw new C(e,V)}async handleGetAction(e,t){if(Object.values(F).includes(e)){let i=t[e];return i()}else throw new C(e,F)}isClientError(e){let t=Object.values(w).includes(e.code),i=lt(e);return t||i}handleError(e){return this.isClientError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):(console.error(e),this.createError(new re))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new pe;if(!this.client.secretKey)throw new ue;let[i,s]=t.split(",");if(!i||!s)throw new de;let[a,l]=i.split("="),[c,p]=s.split("=");if(Number(a)<Date.now()-1500)throw new he;if(!(this.hashHmac(this.client.secretKey,`${l}.${JSON.stringify(e)}`)===p))throw new ce}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};function lt(n){return n?.statusCode>=400&&n?.statusCode<500}var ct={type:"object",properties:{webhookUrl:{type:"string",format:"uri"},text:{type:"string"},blocks:{type:"array",items:{type:"object",properties:{type:{enum:["image","context","actions","divider","section","input","file","header","video","rich_text"]}},required:["type"],additionalProperties:!0,allOf:[{if:{properties:{type:{const:"image"}}},then:{$ref:"#/definitions/ImageBlock"}},{if:{properties:{type:{const:"context"}}},then:{$ref:"#/definitions/ContextBlock"}},{if:{properties:{type:{const:"actions"}}},then:{$ref:"#/definitions/ActionsBlock"}},{if:{properties:{type:{const:"divider"}}},then:{$ref:"#/definitions/DividerBlock"}},{if:{properties:{type:{const:"section"}}},then:{$ref:"#/definitions/SectionBlock"}},{if:{properties:{type:{const:"Input"}}},then:{$ref:"#/definitions/InputBlock"}},{if:{properties:{type:{const:"Video"}}},then:{$ref:"#/definitions/VideoBlock"}},{if:{properties:{type:{const:"rich_text"}}},then:{$ref:"#/definitions/RichTextBlock"}}]}}},definitions:{KnownBlock:{oneOf:[{$ref:"#/definitions/ImageBlock"},{$ref:"#/definitions/ContextBlock"},{$ref:"#/definitions/ActionsBlock"},{$ref:"#/definitions/DividerBlock"},{$ref:"#/definitions/SectionBlock"},{$ref:"#/definitions/InputBlock"},{$ref:"#/definitions/FileBlock"},{$ref:"#/definitions/HeaderBlock"},{$ref:"#/definitions/VideoBlock"},{$ref:"#/definitions/RichTextBlock"}]},ImageBlock:{type:"object",properties:{type:{type:"string",const:"image",description:"The type of block. For an image block, `type` is always `image`."},block_id:{type:"string"},image_url:{type:"string",description:"The URL of the image to be displayed. Maximum length for this field is 3000 characters."},alt_text:{type:"string",description:`A plain-text summary of the image. This should not contain any markup.
24
+ `);}async executeProviders(e,t,i){return t.providers.reduce(async(n,a)=>{let l=await n,c=this.previewProvider.bind(this),p=this.executeProvider.bind(this),g=await(e.action==="preview"?c:p)(e,t,a,i);return {...l,[a.type]:g}},Promise.resolve({}))}previewProvider(e,t,i,n){return console.log(` ${f.MOCK} Mocked provider: \`${i.type}\``),this.mock(i.outputs.schema)}async executeProvider(e,t,i,n){let a=Te__default.default({indent:2}).start(`Executing provider: \`${i.type}\``);try{if(e.stepId===t.stepId){let l=await this.createStepControls(t,e),c=await i.resolve({controls:l,outputs:n}),p=await this.validate(c,i.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,i.type);return a.succeed(`Executed provider: \`${i.type}\``),p}else a.stopAndPersist({symbol:f.HYDRATED,text:`Hydrated provider: \`${i.type}\``});}catch(l){throw a.stopAndPersist({symbol:f.ERROR,text:`Failed to execute provider: \`${i.type}\``}),new le(`Failed to execute provider: '${i.type}'.
25
+ ${l.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let i=Te__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let n=await this.createStepControls(t,e),a=await this.compileControls(n,e),l=await t.resolve(a),c=await this.validate(l,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),p=await this.executeProviders(e,t,c);return i.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:c,providers:p}}catch(n){throw i.stopAndPersist({prefixText:"",symbol:f.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),n}}else {let i=Te__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let n=e.state.find(a=>a.stepId===t.stepId);if(n){let a=await this.validate(n.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return i.stopAndPersist({symbol:f.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:a,providers:await this.executeProviders(e,t,a)}}else throw new z(e.workflowId,t.stepId)}catch(n){throw i.stopAndPersist({symbol:f.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),n}}}async compileControls(e,t){let i=this.templateEngine.parse(JSON.stringify(e)),n=await this.templateEngine.render(i,{...t.payload||t.data,subscriber:t.subscriber});return JSON.parse(n)}async createStepControls(e,t){let i=t.controls||t.inputs;return await this.validate(i,e.controls.unknownSchema,"step","controls",t.workflowId,e.stepId)}async previewStep(e,t){let i=Te__default.default({indent:1}).start(`Previewing stepId: \`${t.stepId}\``);try{if(e.stepId===t.stepId){let n=await this.createStepControls(t,e),a=await this.compileControls(n,e),l=await t.resolve(a),c=await this.validate(l,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return i.stopAndPersist({symbol:f.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:c,providers:await this.executeProviders(e,t,c)}}else {let n=this.mock(t.results.schema);return i.stopAndPersist({symbol:f.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:n,providers:await this.executeProviders(e,t,n)}}}catch(n){throw i.stopAndPersist({symbol:f.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),n}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let i;if(e)t?i=this.getStepCode(e,t):i=this.getWorkflowCode(e);else throw new U(e);return i}};function st(s){return JSON.parse(JSON.stringify(s))}var rt=(r=>(r.EVERY_SECOND="* * * * * *",r.EVERY_5_SECONDS="*/5 * * * * *",r.EVERY_10_SECONDS="*/10 * * * * *",r.EVERY_30_SECONDS="*/30 * * * * *",r.EVERY_MINUTE="*/1 * * * *",r.EVERY_5_MINUTES="0 */5 * * * *",r.EVERY_10_MINUTES="0 */10 * * * *",r.EVERY_30_MINUTES="0 */30 * * * *",r.EVERY_HOUR="0 0-23/1 * * *",r.EVERY_2_HOURS="0 0-23/2 * * *",r.EVERY_3_HOURS="0 0-23/3 * * *",r.EVERY_4_HOURS="0 0-23/4 * * *",r.EVERY_5_HOURS="0 0-23/5 * * *",r.EVERY_6_HOURS="0 0-23/6 * * *",r.EVERY_7_HOURS="0 0-23/7 * * *",r.EVERY_8_HOURS="0 0-23/8 * * *",r.EVERY_9_HOURS="0 0-23/9 * * *",r.EVERY_10_HOURS="0 0-23/10 * * *",r.EVERY_11_HOURS="0 0-23/11 * * *",r.EVERY_12_HOURS="0 0-23/12 * * *",r.EVERY_DAY_AT_1AM="0 01 * * *",r.EVERY_DAY_AT_2AM="0 02 * * *",r.EVERY_DAY_AT_3AM="0 03 * * *",r.EVERY_DAY_AT_4AM="0 04 * * *",r.EVERY_DAY_AT_5AM="0 05 * * *",r.EVERY_DAY_AT_6AM="0 06 * * *",r.EVERY_DAY_AT_7AM="0 07 * * *",r.EVERY_DAY_AT_8AM="0 08 * * *",r.EVERY_DAY_AT_9AM="0 09 * * *",r.EVERY_DAY_AT_10AM="0 10 * * *",r.EVERY_DAY_AT_11AM="0 11 * * *",r.EVERY_DAY_AT_NOON="0 12 * * *",r.EVERY_DAY_AT_1PM="0 13 * * *",r.EVERY_DAY_AT_2PM="0 14 * * *",r.EVERY_DAY_AT_3PM="0 15 * * *",r.EVERY_DAY_AT_4PM="0 16 * * *",r.EVERY_DAY_AT_5PM="0 17 * * *",r.EVERY_DAY_AT_6PM="0 18 * * *",r.EVERY_DAY_AT_7PM="0 19 * * *",r.EVERY_DAY_AT_8PM="0 20 * * *",r.EVERY_DAY_AT_9PM="0 21 * * *",r.EVERY_DAY_AT_10PM="0 22 * * *",r.EVERY_DAY_AT_11PM="0 23 * * *",r.EVERY_DAY_AT_MIDNIGHT="0 0 * * *",r.EVERY_WEEK="0 0 * * 0",r.EVERY_WEEKDAY="0 0 * * 1-5",r.EVERY_WEEKEND="0 0 * * 6,0",r.EVERY_1ST_DAY_OF_MONTH_AT_MIDNIGHT="0 0 1 * *",r.EVERY_1ST_DAY_OF_MONTH_AT_NOON="0 12 1 * *",r.EVERY_2ND_HOUR="0 */2 * * *",r.EVERY_2ND_HOUR_FROM_1AM_THROUGH_11PM="0 1-23/2 * * *",r.EVERY_2ND_MONTH="0 0 1 */2 *",r.EVERY_QUARTER="0 0 1 */3 *",r.EVERY_6_MONTHS="0 0 1 */6 *",r.EVERY_YEAR="0 0 1 0 *",r.EVERY_30_MINUTES_BETWEEN_9AM_AND_5PM="0 */30 9-17 * * *",r.EVERY_30_MINUTES_BETWEEN_9AM_AND_6PM="0 */30 9-18 * * *",r.EVERY_30_MINUTES_BETWEEN_10AM_AND_7PM="0 */30 10-19 * * *",r.MONDAY_TO_FRIDAY_AT_1AM="0 0 01 * * 1-5",r.MONDAY_TO_FRIDAY_AT_2AM="0 0 02 * * 1-5",r.MONDAY_TO_FRIDAY_AT_3AM="0 0 03 * * 1-5",r.MONDAY_TO_FRIDAY_AT_4AM="0 0 04 * * 1-5",r.MONDAY_TO_FRIDAY_AT_5AM="0 0 05 * * 1-5",r.MONDAY_TO_FRIDAY_AT_6AM="0 0 06 * * 1-5",r.MONDAY_TO_FRIDAY_AT_7AM="0 0 07 * * 1-5",r.MONDAY_TO_FRIDAY_AT_8AM="0 0 08 * * 1-5",r.MONDAY_TO_FRIDAY_AT_9AM="0 0 09 * * 1-5",r.MONDAY_TO_FRIDAY_AT_09_30AM="0 30 09 * * 1-5",r.MONDAY_TO_FRIDAY_AT_10AM="0 0 10 * * 1-5",r.MONDAY_TO_FRIDAY_AT_11AM="0 0 11 * * 1-5",r.MONDAY_TO_FRIDAY_AT_11_30AM="0 30 11 * * 1-5",r.MONDAY_TO_FRIDAY_AT_12PM="0 0 12 * * 1-5",r.MONDAY_TO_FRIDAY_AT_1PM="0 0 13 * * 1-5",r.MONDAY_TO_FRIDAY_AT_2PM="0 0 14 * * 1-5",r.MONDAY_TO_FRIDAY_AT_3PM="0 0 15 * * 1-5",r.MONDAY_TO_FRIDAY_AT_4PM="0 0 16 * * 1-5",r.MONDAY_TO_FRIDAY_AT_5PM="0 0 17 * * 1-5",r.MONDAY_TO_FRIDAY_AT_6PM="0 0 18 * * 1-5",r.MONDAY_TO_FRIDAY_AT_7PM="0 0 19 * * 1-5",r.MONDAY_TO_FRIDAY_AT_8PM="0 0 20 * * 1-5",r.MONDAY_TO_FRIDAY_AT_9PM="0 0 21 * * 1-5",r.MONDAY_TO_FRIDAY_AT_10PM="0 0 22 * * 1-5",r.MONDAY_TO_FRIDAY_AT_11PM="0 0 23 * * 1-5",r))(rt||{});var at=(u=>(u.PENDING="pending",u.QUEUED="queued",u.RUNNING="running",u.COMPLETED="completed",u.FAILED="failed",u.DELAYED="delayed",u.CANCELED="canceled",u.MERGED="merged",u.SKIPPED="skipped",u))(at||{});var Se=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new F,this.client.addWorkflows(e.workflows),this.http=ne(this.client.secretKey),this.frameworkName=e.frameworkName,this.hmacEnabled=this.client.strictAuthentication;}createHandler(){return async(...e)=>{let t=await this.handler(...e),i=await this.handleAction({actions:t});return t.transformResponse(i)}}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":we,"novu-framework-sdk":Y,"novu-framework-api":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(),i=await e.method(),n=t.searchParams.get("action")||"",a=t.searchParams.get("workflowId")||"",l=t.searchParams.get("stepId")||"",c=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",p={};try{i==="POST"&&(p=await e.body());}catch{}try{n!=="health-check"&&this.validateHmac(p,c);let u=this.getPostActionMap(p,a,l,n),g=this.getGetActionMap(a,l);if(i==="POST")return await this.handlePostAction(n,u);if(i==="GET")return await this.handleGetAction(n,g);if(i==="OPTIONS")return this.createResponse(200,{})}catch(u){return this.handleError(u)}return this.createError(new se(i))}getPostActionMap(e,t,i,n){return {trigger:this.triggerAction({workflowId:t,...e}),execute:async()=>{let a=await this.client.executeWorkflow({...e,workflowId:t,stepId:i,action:n});return this.createResponse(200,a)},preview:async()=>{let a=await this.client.executeWorkflow({...e,workflowId:t,stepId:i,action:n});return this.createResponse(200,a)}}}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.tenant&&{tenant:e.tenant},...e.bridgeUrl&&{bridgeUrl:e.bridgeUrl},...e.controls&&{controls:e.controls}},i=await this.http.post("/events/trigger",t);return this.createResponse(200,i)}}getGetActionMap(e,t){return {discover:async()=>{let i=await this.client.discover();return this.createResponse(200,i)},"health-check":async()=>{let i=await this.client.healthCheck();return this.createResponse(200,i)},code:async()=>{let i=await this.client.getCode(e,t);return this.createResponse(200,i)}}}async handlePostAction(e,t){if(Object.values(C).includes(e)){let i=t[e];return i()}else throw new $(e,C)}async handleGetAction(e,t){if(Object.values(L).includes(e)){let i=t[e];return i()}else throw new $(e,L)}isBridgeError(e){return Object.values(w).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 I))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new pe;if(!this.client.secretKey)throw new ue;let[i,n]=t.split(",");if(!i||!n)throw new de;let[a,l]=i.split("="),[c,p]=n.split("=");if(Number(a)<Date.now()-1500)throw new he;if(!(this.hashHmac(this.client.secretKey,`${l}.${JSON.stringify(e)}`)===p))throw new ce}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var ct={type:"object",properties:{webhookUrl:{type:"string",format:"uri"},text:{type:"string"},blocks:{type:"array",items:{type:"object",properties:{type:{enum:["image","context","actions","divider","section","input","file","header","video","rich_text"]}},required:["type"],additionalProperties:!0,allOf:[{if:{properties:{type:{const:"image"}}},then:{$ref:"#/definitions/ImageBlock"}},{if:{properties:{type:{const:"context"}}},then:{$ref:"#/definitions/ContextBlock"}},{if:{properties:{type:{const:"actions"}}},then:{$ref:"#/definitions/ActionsBlock"}},{if:{properties:{type:{const:"divider"}}},then:{$ref:"#/definitions/DividerBlock"}},{if:{properties:{type:{const:"section"}}},then:{$ref:"#/definitions/SectionBlock"}},{if:{properties:{type:{const:"Input"}}},then:{$ref:"#/definitions/InputBlock"}},{if:{properties:{type:{const:"Video"}}},then:{$ref:"#/definitions/VideoBlock"}},{if:{properties:{type:{const:"rich_text"}}},then:{$ref:"#/definitions/RichTextBlock"}}]}}},definitions:{KnownBlock:{oneOf:[{$ref:"#/definitions/ImageBlock"},{$ref:"#/definitions/ContextBlock"},{$ref:"#/definitions/ActionsBlock"},{$ref:"#/definitions/DividerBlock"},{$ref:"#/definitions/SectionBlock"},{$ref:"#/definitions/InputBlock"},{$ref:"#/definitions/FileBlock"},{$ref:"#/definitions/HeaderBlock"},{$ref:"#/definitions/VideoBlock"},{$ref:"#/definitions/RichTextBlock"}]},ImageBlock:{type:"object",properties:{type:{type:"string",const:"image",description:"The type of block. For an image block, `type` is always `image`."},block_id:{type:"string"},image_url:{type:"string",description:"The URL of the image to be displayed. Maximum length for this field is 3000 characters."},alt_text:{type:"string",description:`A plain-text summary of the image. This should not contain any markup.
25
26
  Maximum length for this field is 2000 characters.`},title:{$ref:"#/definitions/PlainTextElement",description:`An optional title for the image in the form of a {@link PlainTextElement } object.
26
27
  Maximum length for the text in this field is 2000 characters.`}},required:["alt_text","image_url","type"],additionalProperties:!1,description:"Displays an image. A simple image block, designed to make those cat photos really pop."},PlainTextElement:{type:"object",properties:{type:{type:"string",const:"plain_text",description:"The formatting to use for this text object."},text:{type:"string",description:"The text for the block. The minimum length is 1 and maximum length is 3000 characters."},emoji:{type:"boolean",description:"Indicates whether emojis in a text field should be escaped into the colon emoji format."}},required:["type","text"],additionalProperties:!1,description:"Defines an object containing some text."},ContextBlock:{type:"object",properties:{type:{type:"string",const:"context",description:"The type of block. For a context block, `type` is always `context`."},block_id:{type:"string"},elements:{type:"array",items:{anyOf:[{$ref:"#/definitions/ImageElement"},{$ref:"#/definitions/PlainTextElement"},{$ref:"#/definitions/MrkdwnElement"}]},description:`An array of {@link ImageElement }, {@link PlainTextElement } or {@link MrkdwnElement } objects.
27
28
  Maximum number of items is 10.`}},required:["elements","type"],additionalProperties:!1,description:"Displays contextual info, which can include both images and text."},ImageElement:{type:"object",properties:{type:{type:"string",const:"image",description:"The type of element. In this case `type` is always `image`."},image_url:{type:"string",description:"The URL of the image to be displayed."},alt_text:{type:"string",description:"A plain-text summary of the image. This should not contain any markup."}},required:["type","image_url","alt_text"],additionalProperties:!1,description:"Displays an image as part of a larger block of content. Use this `image` block if you want a block with\nonly an image in it."},MrkdwnElement:{type:"object",properties:{type:{type:"string",const:"mrkdwn",description:"The formatting to use for this text object."},text:{type:"string",description:`The text for the block. This field accepts any of the standard text formatting markup.
@@ -102,25 +103,25 @@ that contain remote files. If you want to add remote files to messages,
102
103
  Maximum length for the text in this field is 150 characters.`}},required:["text","type"],additionalProperties:!1,description:"Displays a larger-sized text block. A `header` is a plain-text block that displays in a larger, bold\nfont. Use it to delineate between different groups of content in your app's surfaces."},VideoBlock:{type:"object",properties:{type:{type:"string",const:"video",description:"The type of block. For a video block, `type` is always `video`."},block_id:{type:"string",description:"A string acting as a unique identifier for a block. If not specified, a `block_id` will be generated.\nYou can use this `block_id` when you receive an interaction payload to\n{@link https://api.slack.com/interactivity/handling#payloads identify the source of the action}.\nMaximum length for this field is 255 characters. `block_id` should be unique for each message and each iteration of\na message. If a message is updated, use a new `block_id`."},video_url:{type:"string",description:`The URL to be embedded. Must match any existing
103
104
  {@link https://api.slack.com/reference/messaging/link-unfurling#configuring_domains unfurl domains} within the app
104
105
  and point to a HTTPS URL.`},thumbnail_url:{type:"string",description:"The thumbnail image URL."},alt_text:{type:"string",description:"A tooltip for the video. Required for accessibility."},title:{$ref:"#/definitions/PlainTextElement",description:"Video title as a {@link PlainTextElement } object. `text` within must be less than 200 characters."},title_url:{type:"string",description:`Hyperlink for the title text. Must correspond to the non-embeddable URL for the video.
105
- Must go to an HTTPS URL.`},author_name:{type:"string",description:"Author name to be displayed. Must be less than 50 characters."},provider_name:{type:"string",description:"The originating application or domain of the video, e.g. YouTube."},provider_icon_url:{type:"string",description:"Icon for the video provider, e.g. YouTube icon."},description:{$ref:"#/definitions/PlainTextElement",description:"Description for video using a {@link PlainTextElement } object."}},required:["alt_text","thumbnail_url","title","type","video_url"],additionalProperties:!1,description:"Displays an embedded video player. A video block is designed to embed videos in all app surfaces (e.g.\nlink unfurls, messages, modals, App Home) \u2014 anywhere you can put blocks! To use the video block within your app, you\nmust have the {@link https://api.slack.com/scopes/links.embed:write `links.embed:write` scope}."}},additionalProperties:!1},Me={output:ct};var Ce={slack:Me};var pt={type:"object",properties:{ipPoolName:{type:"string"}},required:["ipPoolName"],additionalProperties:!1},je={output:pt};var $e={sendgrid:je};var Ue={};var Ye={};var Ve={};var Fe={chat:Ce,sms:Ve,email:$e,push:Ye,in_app:Ue};var dt={type:"object",properties:{type:{enum:["regular"],default:"regular"},amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]}},required:["amount","unit"],additionalProperties:!1},ht={type:"object",properties:{duration:{type:"number"}},required:["duration"],additionalProperties:!1},Ae={output:dt,result:ht};var ut={type:"object",properties:{amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]},digestKey:{type:"string"},lookBackWindow:{type:"object",properties:{amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]}},required:["amount","unit"],additionalProperties:!1}},required:["amount","unit"],additionalProperties:!1},mt={type:"object",properties:{cron:{type:"string"},digestKey:{type:"string"}},required:["cron"],additionalProperties:!1},ft={oneOf:[ut,mt]},yt={type:"object",properties:{events:{type:"array",items:{type:"object",properties:{id:{type:"string"},time:{type:"string"},payload:{type:"object"}},required:["id","time","payload"],additionalProperties:!1}}},required:["events"],additionalProperties:!1},Ee={output:ft,result:yt};var gt={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},_t={type:"object",properties:{},required:[],additionalProperties:!1},Le={output:gt,result:_t};var bt={type:"object",properties:{subject:{type:"string"},body:{type:"string"}},required:["subject","body"],additionalProperties:!1},wt={type:"object",properties:{},required:[],additionalProperties:!1},qe={output:bt,result:wt};var Tt={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},xt={type:"object",properties:{seen:{type:"boolean"},read:{type:"boolean"},lastSeenDate:{type:"string",format:"date-time",nullable:!0},lastReadDate:{type:"string",format:"date-time",nullable:!0}},required:["seen","read","lastSeenDate","lastReadDate"],additionalProperties:!1},We={output:Tt,result:xt};var kt={type:"object",properties:{subject:{type:"string"},body:{type:"string"}},required:["subject","body"],additionalProperties:!1},Rt={type:"object",properties:{},required:[],additionalProperties:!1},Be={output:kt,result:Rt};var St={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},At={type:"object",properties:{},required:[],additionalProperties:!1},Ge={output:St,result:At};var T={chat:Le,sms:Ge,push:Be,email:qe,in_app:We};var _={type:"object",properties:{},required:[],additionalProperties:!1};function Et(n,e,t){let i=t||{},s=oe(process.env.NOVU_SECRET_KEY),a=async c=>{if(!process.env.NOVU_SECRET_KEY)throw new se;c.payload;if(i.payloadSchema){let m=await be(i.payloadSchema,c.payload);if(m.success===!1)throw new ee(n,m.errors);m.data;}let u=await Ie(),g={name:n,to:c.to,payload:{...c?.payload},...c.transactionId&&{transactionId:c.transactionId},...c.overrides&&{overrides:c.overrides},...c.actor&&{actor:c.actor},...c.tenant&&{tenant:c.tenant},...u&&{bridgeUrl:u}},x=await s.post("/events/trigger",g);return {cancel:async()=>s.delete(`/events/trigger/${x.transactionId}`),data:x}},l={workflowId:n,options:{...i,inputSchema:y(i.controlSchema||i.inputSchema||_),controlSchema:y(i.controlSchema||i.inputSchema||_),payloadSchema:y(i.payloadSchema||_)},steps:[],code:e.toString(),data:{schema:y(i.payloadSchema||_),unknownSchema:i.payloadSchema||_},payload:{schema:y(i.payloadSchema||_),unknownSchema:i.payloadSchema||_},inputs:{schema:y(i.controlSchema||i.inputSchema||_),unknownSchema:i.controlSchema||i.inputSchema||_},controls:{schema:y(i.controlSchema||i.inputSchema||_),unknownSchema:i.controlSchema||i.inputSchema||_},execute:e};return e({payload:{},subscriber:{},environment:{},controls:{},step:{push:E(l,"push",T.push.output,T.push.result),chat:E(l,"chat",T.chat.output,T.chat.result),email:E(l,"email",T.email.output,T.email.result),sms:E(l,"sms",T.sms.output,T.sms.result),inApp:E(l,"in_app",T.in_app.output,T.in_app.result),digest:E(l,"digest",Ee.output,Ee.result),delay:E(l,"delay",Ae.output,Ae.result),custom:Ot(l,"custom")}}),Pt(l),{trigger:a,definition:l}}function E(n,e,t,i){return async(s,a,l={})=>{let c=l?.controlSchema||l?.inputSchema||_,p={stepId:s,type:e,inputs:{schema:y(c),unknownSchema:c},controls:{schema:y(c),unknownSchema:c},outputs:{schema:y(t),unknownSchema:t},results:{schema:y(i),unknownSchema:i},resolve:a,code:a.toString(),options:l,providers:[]};Ke(n,s,p),Object.values(B).includes(e)&&Object.keys(l.providers||{}).length>0&&vt(p,e,l.providers||{});}}function Ke(n,e,t){if(n.steps.some(i=>i.stepId===e))throw new fe(e);n.steps.push(t);}function vt(n,e,t){let i=Fe[e];Object.entries(t).forEach(([s,a])=>{let l=i[s];n.providers.push({type:s,code:a.toString(),resolve:a,outputs:{schema:y(l.output),unknownSchema:l.output}});});}function Ot(n,e){return async(t,i,s={})=>{let a=s?.controlSchema||s?.inputSchema||_,l=s?.outputSchema||_;Ke(n,t,{stepId:t,type:e,inputs:{schema:y(a),unknownSchema:a},controls:{schema:y(a),unknownSchema:a},outputs:{schema:y(l),unknownSchema:l},results:{schema:y(l),unknownSchema:l},resolve:i,code:i.toString(),options:s,providers:[]});}}function Pt(n){console.log(`
106
- ${d.bold(d.underline("Discovered workflowId:"))} '${n.workflowId}'`),n.steps.forEach((e,t)=>{let i=t===n.steps.length-1?"\u2514":"\u251C";console.log(`${i} ${f.STEP} Discovered stepId: '${e.stepId}' Type: '${e.type}'`),e.providers.forEach((s,a)=>{let l=a===e.providers.length-1?"\u2514":"\u251C";console.log(` ${l} ${f.PROVIDER} Discovered provider: '${s.type}'`);});});}
106
+ Must go to an HTTPS URL.`},author_name:{type:"string",description:"Author name to be displayed. Must be less than 50 characters."},provider_name:{type:"string",description:"The originating application or domain of the video, e.g. YouTube."},provider_icon_url:{type:"string",description:"Icon for the video provider, e.g. YouTube icon."},description:{$ref:"#/definitions/PlainTextElement",description:"Description for video using a {@link PlainTextElement } object."}},required:["alt_text","thumbnail_url","title","type","video_url"],additionalProperties:!1,description:"Displays an embedded video player. A video block is designed to embed videos in all app surfaces (e.g.\nlink unfurls, messages, modals, App Home) \u2014 anywhere you can put blocks! To use the video block within your app, you\nmust have the {@link https://api.slack.com/scopes/links.embed:write `links.embed:write` scope}."}},additionalProperties:!1},Me={output:ct};var Ce={slack:Me};var pt={type:"object",properties:{ipPoolName:{type:"string"}},required:["ipPoolName"],additionalProperties:!1},je={output:pt};var $e={sendgrid:je};var Ue={};var Ye={};var Fe={};var Ve={chat:Ce,sms:Fe,email:$e,push:Ye,in_app:Ue};var dt={type:"object",properties:{type:{enum:["regular"],default:"regular"},amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]}},required:["amount","unit"],additionalProperties:!1},ht={type:"object",properties:{duration:{type:"number"}},required:["duration"],additionalProperties:!1},Ae={output:dt,result:ht};var ut={type:"object",properties:{amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]},digestKey:{type:"string"},lookBackWindow:{type:"object",properties:{amount:{type:"number"},unit:{type:"string",enum:["seconds","minutes","hours","days","weeks","months"]}},required:["amount","unit"],additionalProperties:!1}},required:["amount","unit"],additionalProperties:!1},mt={type:"object",properties:{cron:{type:"string"},digestKey:{type:"string"}},required:["cron"],additionalProperties:!1},ft={oneOf:[ut,mt]},yt={type:"object",properties:{events:{type:"array",items:{type:"object",properties:{id:{type:"string"},time:{type:"string"},payload:{type:"object"}},required:["id","time","payload"],additionalProperties:!1}}},required:["events"],additionalProperties:!1},Ee={output:ft,result:yt};var gt={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},_t={type:"object",properties:{},required:[],additionalProperties:!1},Le={output:gt,result:_t};var bt={type:"object",properties:{subject:{type:"string"},body:{type:"string"}},required:["subject","body"],additionalProperties:!1},wt={type:"object",properties:{},required:[],additionalProperties:!1},qe={output:bt,result:wt};var Tt={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},xt={type:"object",properties:{seen:{type:"boolean"},read:{type:"boolean"},lastSeenDate:{type:"string",format:"date-time",nullable:!0},lastReadDate:{type:"string",format:"date-time",nullable:!0}},required:["seen","read","lastSeenDate","lastReadDate"],additionalProperties:!1},We={output:Tt,result:xt};var kt={type:"object",properties:{subject:{type:"string"},body:{type:"string"}},required:["subject","body"],additionalProperties:!1},Rt={type:"object",properties:{},required:[],additionalProperties:!1},Be={output:kt,result:Rt};var St={type:"object",properties:{body:{type:"string"}},required:["body"],additionalProperties:!1},At={type:"object",properties:{},required:[],additionalProperties:!1},Ge={output:St,result:At};var x={chat:Le,sms:Ge,push:Be,email:qe,in_app:We};var _={type:"object",properties:{},required:[],additionalProperties:!1};function Et(s,e,t){let i=t||{},n=ne(process.env.NOVU_SECRET_KEY),a=async c=>{if(!process.env.NOVU_SECRET_KEY)throw new re;c.payload;if(i.payloadSchema){let m=await be(i.payloadSchema,c.payload);if(m.success===!1)throw new te(s,m.errors);m.data;}let u=await Ie(),g={name:s,to:c.to,payload:{...c?.payload},...c.transactionId&&{transactionId:c.transactionId},...c.overrides&&{overrides:c.overrides},...c.actor&&{actor:c.actor},...c.tenant&&{tenant:c.tenant},...u&&{bridgeUrl:u}},k=await n.post("/events/trigger",g);return {cancel:async()=>n.delete(`/events/trigger/${k.transactionId}`),data:k}},l={workflowId:s,options:{...i,inputSchema:y(i.controlSchema||i.inputSchema||_),controlSchema:y(i.controlSchema||i.inputSchema||_),payloadSchema:y(i.payloadSchema||_)},steps:[],code:e.toString(),data:{schema:y(i.payloadSchema||_),unknownSchema:i.payloadSchema||_},payload:{schema:y(i.payloadSchema||_),unknownSchema:i.payloadSchema||_},inputs:{schema:y(i.controlSchema||i.inputSchema||_),unknownSchema:i.controlSchema||i.inputSchema||_},controls:{schema:y(i.controlSchema||i.inputSchema||_),unknownSchema:i.controlSchema||i.inputSchema||_},execute:e};return e({payload:{},subscriber:{},environment:{},controls:{},step:{push:E(l,"push",x.push.output,x.push.result),chat:E(l,"chat",x.chat.output,x.chat.result),email:E(l,"email",x.email.output,x.email.result),sms:E(l,"sms",x.sms.output,x.sms.result),inApp:E(l,"in_app",x.in_app.output,x.in_app.result),digest:E(l,"digest",Ee.output,Ee.result),delay:E(l,"delay",Ae.output,Ae.result),custom:Ot(l,"custom")}}),Pt(l),{trigger:a,definition:l}}function E(s,e,t,i){return async(n,a,l={})=>{let c=l?.controlSchema||l?.inputSchema||_,p={stepId:n,type:e,inputs:{schema:y(c),unknownSchema:c},controls:{schema:y(c),unknownSchema:c},outputs:{schema:y(t),unknownSchema:t},results:{schema:y(i),unknownSchema:i},resolve:a,code:a.toString(),options:l,providers:[]};Ke(s,n,p),Object.values(G).includes(e)&&Object.keys(l.providers||{}).length>0&&vt(p,e,l.providers||{});}}function Ke(s,e,t){if(s.steps.some(i=>i.stepId===e))throw new fe(e);s.steps.push(t);}function vt(s,e,t){let i=Ve[e];Object.entries(t).forEach(([n,a])=>{let l=i[n];s.providers.push({type:n,code:a.toString(),resolve:a,outputs:{schema:y(l.output),unknownSchema:l.output}});});}function Ot(s,e){return async(t,i,n={})=>{let a=n?.controlSchema||n?.inputSchema||_,l=n?.outputSchema||_;Ke(s,t,{stepId:t,type:e,inputs:{schema:y(a),unknownSchema:a},controls:{schema:y(a),unknownSchema:a},outputs:{schema:y(l),unknownSchema:l},results:{schema:y(l),unknownSchema:l},resolve:i,code:i.toString(),options:n,providers:[]});}}function Pt(s){console.log(`
107
+ ${d.bold(d.underline("Discovered workflowId:"))} '${s.workflowId}'`),s.steps.forEach((e,t)=>{let i=t===s.steps.length-1?"\u2514":"\u251C";console.log(`${i} ${f.STEP} Discovered stepId: '${e.stepId}' Type: '${e.type}'`),e.providers.forEach((n,a)=>{let l=a===e.providers.length-1?"\u2514":"\u251C";console.log(` ${l} ${f.PROVIDER} Discovered provider: '${n.type}'`);});});}
107
108
 
108
109
  exports.ActionStepEnum = Qe;
109
- exports.ChannelStepEnum = B;
110
- exports.Client = U;
111
- exports.CronExpression = st;
110
+ exports.ChannelStepEnum = G;
111
+ exports.Client = F;
112
+ exports.CronExpression = rt;
112
113
  exports.ErrorCodeEnum = w;
113
- exports.GetActionEnum = F;
114
+ exports.GetActionEnum = L;
114
115
  exports.HttpHeaderKeysEnum = xe;
115
- exports.HttpMethodEnum = L;
116
+ exports.HttpMethodEnum = q;
116
117
  exports.HttpQueryKeysEnum = Pe;
117
- exports.HttpStatusEnum = q;
118
- exports.JobStatusEnum = rt;
118
+ exports.HttpStatusEnum = W;
119
+ exports.JobStatusEnum = at;
119
120
  exports.NovuApiEndpointsEnum = Je;
120
121
  exports.NovuRequestHandler = Se;
121
- exports.PostActionEnum = V;
122
- exports.RETRYABLE_ERROR_STATUS_CODES = Vt;
123
- exports.ResourceEnum = W;
122
+ exports.PostActionEnum = C;
123
+ exports.RETRYABLE_ERROR_STATUS_CODES = Ft;
124
+ exports.ResourceEnum = B;
124
125
  exports.SIGNATURE_TIMESTAMP_TOLERANCE = Oe;
125
126
  exports.SIGNATURE_TIMESTAMP_TOLERANCE_MINUTES = ve;
126
127
  exports.workflow = Et;
package/dist/next.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { NextApiResponse } from 'next';
2
2
  import { NextRequest } from 'next/server';
3
- import { q as SupportedFrameworkName, b as ServeHandlerOptions } from './handler-Mor_4K8F.js';
3
+ import { q as SupportedFrameworkName, b as ServeHandlerOptions } from './handler-3oTUJvk2.js';
4
4
  import 'json-schema-to-ts';
5
5
  import 'zod';
6
6
  import '@novu/shared';
package/dist/next.js CHANGED
@@ -6,22 +6,23 @@ var liquidjs = require('liquidjs');
6
6
  var ne = require('ora');
7
7
  var crossFetch = require('cross-fetch');
8
8
  var v = require('chalk');
9
- var Ae = require('ajv');
10
- var xe = require('ajv-formats');
9
+ var shared = require('@novu/shared');
10
+ var xe = require('ajv');
11
+ var ve = require('ajv-formats');
11
12
  var zodToJsonSchema = require('zod-to-json-schema');
12
13
 
13
14
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
15
 
15
16
  var ne__default = /*#__PURE__*/_interopDefault(ne);
16
17
  var v__default = /*#__PURE__*/_interopDefault(v);
17
- var Ae__default = /*#__PURE__*/_interopDefault(Ae);
18
18
  var xe__default = /*#__PURE__*/_interopDefault(xe);
19
+ var ve__default = /*#__PURE__*/_interopDefault(ve);
19
20
 
20
- var k=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(k||{}),U=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(U||{});var w=(l=>(l.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",l.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",l.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",l.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",l.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",l.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",l.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",l.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",l.STEP_NOT_FOUND_ERROR="StepNotFoundError",l.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",l.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",l.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",l.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",l.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",l.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",l.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",l.INVALID_ACTION_ERROR="InvalidActionError",l.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",l.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",l.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",l.SIGNATURE_INVALID_ERROR="SignatureInvalidError",l.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",l.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",l.PLATFORM_ERROR="PlatformError",l.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",l.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",l))(w||{});var L=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(L||{});var I=class extends Error{data},b=class extends I{statusCode=404},f=class extends I{statusCode=400},_=class extends I{statusCode=401},x=class extends I{statusCode=500},V=class extends I{statusCode=409};var F=class extends f{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},y=class extends f{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 f{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends f{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;}},M=class extends f{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 f{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;}},j=class extends f{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 K=class extends Error{statusCode;message;code;constructor(e,t,r){super(r),this.statusCode=e,this.code=t;}};var ue=()=>typeof Response<"u"?Response:crossFetch.Response;var p={info:o=>v__default.default.blue(o),warning:o=>v__default.default.yellow(o),error:o=>v__default.default.red(o),success:o=>v__default.default.green(o),underline:o=>v__default.default.underline(o),bold:o=>v__default.default.bold(o)},R={SUCCESS:p.success("\u2714"),ERROR:p.error("\u2717"),WARNING:p.warning("\u26A0"),INFO:p.info("\u2139"),ARROW:p.bold("\u2192"),MOCK:p.info("\u25CB"),HYDRATED:p.bold(p.info("\u2192")),STEP:p.info("\u03C3"),ACTION:p.info("\u03B1"),DURATION:p.info("\u0394"),PROVIDER:p.info("\u2699"),OUTPUT:p.info("\u21E2"),INPUT:p.info("\u21E0"),WORKFLOW:p.info("\u03C9"),STATE:p.info("\u03C3"),EXECUTE:p.info("\u03B5"),PREVIEW:p.info("\u03C1")};var de=o=>Object.values(o).map(e=>`\`${e}\``).join(", "),q=o=>o.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Re=(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)}),c=await i.json();if(i.ok)return c;throw new K(c.statusCode,c.error,c.message)},delete:async r=>(await fetch(t+"/v1"+r,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${o}`}})).json()}};var Y=class extends I{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${de(L)}`},S=class extends f{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${de(t)}`);}};var X=class extends x{code="PlatformError";message="Something went wrong. Please try again later."};var P=class extends V{constructor(e,t){super(`${q(e)} with id: \`${t}\` already exists. Please use a different id.`);}},m=class extends b{constructor(e,t){super(`${q(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends x{constructor(e,t){super(`Failed to execute ${q(e)} with id: \`${t}\`. Please try again later.`);}};var J=class extends m{code="ProviderNotFoundError";constructor(e){super("provider",e);}},B=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var z=class extends _{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.");}},Z=class extends _{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},Q=class extends _{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},H=class extends _{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},ee=class extends _{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var te=class extends m{code="StepNotFoundError";constructor(e){super("step",e);}};var C=class extends m{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},re=class extends P{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var oe=class{ajv;compiledSchemas;constructor(){this.ajv=new Ae__default.default({useDefaults:!0,removeAdditional:"all"}),xe__default.default(this.ajv),this.compiledSchemas=new Map;}isSchema(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);return r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r)),r(e)?{success:!0,data:e}:{success:!1,errors:r.errors.map(i=>({path:i.instancePath,message:i.message}))}}transformToJsonSchema(e){return e}};var se=class{isSchema(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 Ee=[new se,new oe],Oe=async(o,e)=>{for(let t of Ee)if(t.isSchema(o))return t.validate(e,o);throw new Error("Invalid schema")},Te=o=>{for(let e of Ee)if(e.isSchema(o))return e.transformToJsonSchema(o);throw new Error("Invalid schema")};var fe={name:"@novu/framework",version:"2.0.0-canary.1",description:"The Code-First Notifications Workflow SDK.",main:"./dist/index.js",types:"./dist/index.d.ts",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},private:!1,repository:{type:"git",url:"git+https://github.com/novuhq/novu.git"},files:["dist","README.md"],scripts:{preinstall:"npx only-allow pnpm",test:"vitest","test:watch":"vitest --watch",lint:"eslint src --ext .ts","lint:fix":"eslint src --ext .ts --fix",format:"prettier --check --ignore-path .gitignore .","format:fix":"prettier --write --ignore-path .gitignore .",build:"tsup","build:watch":"tsup --watch","$comment:bump:prerelease":"This is a workaround to support `npm version prerelease` with lerna","bump:prerelease":"npm version prerelease --preid=alpha & PID=$!; (sleep 1 && kill -9 $PID) & wait $PID","release:alpha":"pnpm bump:prerelease || pnpm build && npm publish"},keywords:["novu","code-first","workflows","durable","sdk","notifications","email","sms","push","webhooks","next","nuxt","h3","express"],author:"Novu Team <engineering@novu.co>",license:"ISC",exports:{".":{require:"./dist/index.js",import:"./dist/index.js",types:"./dist/index.d.ts"},"./express":{require:"./dist/express.js",import:"./dist/express.js",types:"./dist/express.d.ts"},"./next":{require:"./dist/next.js",import:"./dist/next.js",types:"./dist/next.d.ts"},"./nuxt":{require:"./dist/nuxt.js",import:"./dist/nuxt.js",types:"./dist/nuxt.d.ts"},"./h3":{require:"./dist/h3.js",import:"./dist/h3.js",types:"./dist/h3.d.ts"},"./sveltekit":{require:"./dist/sveltekit.js",import:"./dist/sveltekit.js",types:"./dist/sveltekit.d.ts"},"./remix":{require:"./dist/remix.js",import:"./dist/remix.js",types:"./dist/remix.d.ts"}},peerDependencies:{"@sveltejs/kit":">=1.27.3","@vercel/node":">=2.15.9",express:">=4.19.2",h3:">=1.8.1",next:">=12.0.0",zod:">=3.0.0","zod-to-json-schema":">=3.0.0"},peerDependenciesMeta:{"@sveltejs/kit":{optional:!0},"@vercel/node":{optional:!0},express:{optional:!0},fastify:{optional:!0},h3:{optional:!0},next:{optional:!0},zod:{optional:!0},"zod-to-json-schema":{optional:!0}},devDependencies:{"@sveltejs/kit":"^1.27.3","@types/express":"^4.17.13","@types/json-schema":"^7.0.15","@types/node":"^20.11.20","@vercel/node":"^2.15.9",express:"^4.19.2",h3:"^1.11.1",next:"^13.5.4",prettier:"^3.2.5","ts-node":"^10.9.2",tsup:"^8.0.2",typescript:"^5.3.3",vitest:"^1.2.1",zod:"^3.23.0","zod-to-json-schema":"^3.23.0"},dependencies:{"@novu/shared":"workspace:*",ajv:"^8.12.0","ajv-formats":"^2.1.1","better-ajv-errors":"^1.2.0",chalk:"^4.1.2","cross-fetch":"^4.0.0","json-schema-faker":"^0.5.6","json-schema-to-ts":"^3.0.0",liquidjs:"^10.13.1",ora:"^5.4.1"}};var D=fe.version,ie="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Se(){return process.env.NODE_ENV==="development"}var ae=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:!Se()};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 re(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:D,frameworkVersion:ie,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new C(e)}getStep(e,t){let s=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(s)return s;throw new te(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(Te(e))}async validate(e,t,r,s,i,c,d){let n=await Oe(t,e);if(n.success)return n.data;switch(r){case"event":this.throwInvalidEvent(s,i,n.errors);case"step":this.throwInvalidStep(c,s,i,n.errors);case"provider":this.throwInvalidProvider(c,d,s,i,n.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 j(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 M(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 y(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,s,i)=>{let c=this.getStep(e.workflowId,r),d=Pe(e),n=await this.createStepControls(c,d),h=e.action==="preview";if(!h&&await this.shouldSkip(i?.skip,n))return t({options:{skip:!0}}),{};let a=this.previewStep.bind(this),u=this.executeStep.bind(this),N=await(h?a:u)(e,{...c,providers:c.providers.map(E=>{let O=i?.providers?.[E.type];if(!O)throw new J(E.type);return {...E,resolve:O}}),resolve:s});return r===e.stepId&&t(N),N.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let s=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
21
- ${p.bold(p.underline(s))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),c=process.hrtime(),d={outputs:{},providers:{},options:{}},n,h=new Promise(A=>{n=A;}),a=A=>{n(),d=A;},u;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new y(e.workflowId,{message:"Event `payload` is required"});let A=await this.createExecutionPayload(e,i);await Promise.race([h,i.execute({payload:A,environment:{},inputs:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,a),sms:this.executeStepFactory(e,a),inApp:this.executeStepFactory(e,a),digest:this.executeStepFactory(e,a),delay:this.executeStepFactory(e,a),push:this.executeStepFactory(e,a),chat:this.executeStepFactory(e,a),custom:this.executeStepFactory(e,a)}})]);}catch(A){u=A;}let T=process.hrtime(c),N=T[0],E=T[1],O=N*1e3+E/1e6,we=u?R.ERROR:R.SUCCESS,Ie=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${we} ${Ie} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,O,u),u)throw u;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:O}}}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?R.ERROR:R.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",c=r?"Failed to execute":i,d=r?p.error:p.success,n=`${s} ${c} workflowId: '${e.workflowId}`;console.log(`
21
+ var P=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(P||{}),L=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(L||{});var w=(l=>(l.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",l.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",l.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",l.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",l.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",l.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",l.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",l.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",l.STEP_NOT_FOUND_ERROR="StepNotFoundError",l.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",l.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",l.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",l.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",l.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",l.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",l.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",l.INVALID_ACTION_ERROR="InvalidActionError",l.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",l.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",l.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",l.SIGNATURE_INVALID_ERROR="SignatureInvalidError",l.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",l.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",l.BRIDGE_ERROR="BridgeError",l.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",l.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",l))(w||{});var b=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(b||{});var I=class extends Error{data},F=class extends I{statusCode=404},f=class extends I{statusCode=400},m=class extends I{statusCode=401},x=class extends I{statusCode=500},V=class extends I{statusCode=409};var W=class extends f{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};}},S=class extends f{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},$=class extends f{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},M=class extends f{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 f{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 f{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 f{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 q=class extends I{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var ue=()=>typeof Response<"u"?Response:crossFetch.Response;var p={info:s=>v__default.default.blue(s),warning:s=>v__default.default.yellow(s),error:s=>v__default.default.red(s),success:s=>v__default.default.green(s),underline:s=>v__default.default.underline(s),bold:s=>v__default.default.bold(s)},R={SUCCESS:p.success("\u2714"),ERROR:p.error("\u2717"),WARNING:p.warning("\u26A0"),INFO:p.info("\u2139"),ARROW:p.bold("\u2192"),MOCK:p.info("\u25CB"),HYDRATED:p.bold(p.info("\u2192")),STEP:p.info("\u03C3"),ACTION:p.info("\u03B1"),DURATION:p.info("\u0394"),PROVIDER:p.info("\u2699"),OUTPUT:p.info("\u21E2"),INPUT:p.info("\u21E0"),WORKFLOW:p.info("\u03C9"),STATE:p.info("\u03C3"),EXECUTE:p.info("\u03B5"),PREVIEW:p.info("\u03C1")};var de=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),X=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var Re=(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)}),c=await i.json();if(i.ok)return c;throw shared.checkIsResponseError(c)?new q(c.statusCode,c.error,c.message):new g("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 Y=class extends I{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${de(b)}`},C=class extends f{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${de(t)}`);}};var g=class extends x{code="BridgeError";message="Something went wrong. Please try again later."};var D=class extends V{constructor(e,t){super(`${X(e)} with id: \`${t}\` already exists. Please use a different id.`);}},_=class extends F{constructor(e,t){super(`${X(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},y=class extends x{constructor(e,t){super(`Failed to execute ${X(e)} with id: \`${t}\`. Please try again later.`);}};var B=class extends _{code="ProviderNotFoundError";constructor(e){super("provider",e);}},J=class extends y{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var z=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.");}},Z=class extends m{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},Q=class extends m{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},H=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`);}},ee=class extends m{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var te=class extends _{code="StepNotFoundError";constructor(e){super("step",e);}};var k=class extends _{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},re=class extends D{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var oe=class{ajv;compiledSchemas;constructor(){this.ajv=new xe__default.default({useDefaults:!0,removeAdditional:"all"}),ve__default.default(this.ajv),this.compiledSchemas=new Map;}isSchema(e){return typeof e=="boolean"?!1:e.type==="object"||!!e.anyOf||!!e.oneOf}async validate(e,t){let r=this.compiledSchemas.get(t);return r||(r=this.ajv.compile(t),this.compiledSchemas.set(t,r)),r(e)?{success:!0,data:e}:{success:!1,errors:r.errors.map(i=>({path:i.instancePath,message:i.message}))}}transformToJsonSchema(e){return e}};var se=class{isSchema(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 he=[new se,new oe],Oe=async(s,e)=>{for(let t of he)if(t.isSchema(s))return t.validate(e,s);throw new Error("Invalid schema")},Te=s=>{for(let e of he)if(e.isSchema(s))return e.transformToJsonSchema(s);throw new Error("Invalid schema")};var fe={name:"@novu/framework",version:"2.0.0-canary.3",description:"The Code-First Notifications Workflow SDK.",main:"./dist/index.js",types:"./dist/index.d.ts",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},private:!1,repository:{type:"git",url:"git+https://github.com/novuhq/novu.git"},files:["dist","README.md"],scripts:{preinstall:"npx only-allow pnpm",test:"vitest","test:watch":"vitest --watch",lint:"eslint src --ext .ts","lint:fix":"eslint src --ext .ts --fix",format:"prettier --check --ignore-path .gitignore .","format:fix":"prettier --write --ignore-path .gitignore .",build:"tsup","build:watch":"tsup --watch","$comment:bump:prerelease":"This is a workaround to support `npm version prerelease` with lerna","bump:prerelease":"npm version prerelease --preid=alpha & PID=$!; (sleep 1 && kill -9 $PID) & wait $PID","release:alpha":"pnpm bump:prerelease || pnpm build && npm publish"},keywords:["novu","code-first","workflows","durable","sdk","notifications","email","sms","push","webhooks","next","nuxt","h3","express"],author:"Novu Team <engineering@novu.co>",license:"ISC",exports:{".":{require:"./dist/index.js",import:"./dist/index.js",types:"./dist/index.d.ts"},"./express":{require:"./dist/express.js",import:"./dist/express.js",types:"./dist/express.d.ts"},"./next":{require:"./dist/next.js",import:"./dist/next.js",types:"./dist/next.d.ts"},"./nuxt":{require:"./dist/nuxt.js",import:"./dist/nuxt.js",types:"./dist/nuxt.d.ts"},"./h3":{require:"./dist/h3.js",import:"./dist/h3.js",types:"./dist/h3.d.ts"},"./sveltekit":{require:"./dist/sveltekit.js",import:"./dist/sveltekit.js",types:"./dist/sveltekit.d.ts"},"./remix":{require:"./dist/remix.js",import:"./dist/remix.js",types:"./dist/remix.d.ts"}},peerDependencies:{"@sveltejs/kit":">=1.27.3","@vercel/node":">=2.15.9",express:">=4.19.2",h3:">=1.8.1",next:">=12.0.0",zod:">=3.0.0","zod-to-json-schema":">=3.0.0"},peerDependenciesMeta:{"@sveltejs/kit":{optional:!0},"@vercel/node":{optional:!0},express:{optional:!0},fastify:{optional:!0},h3:{optional:!0},next:{optional:!0},zod:{optional:!0},"zod-to-json-schema":{optional:!0}},devDependencies:{"@sveltejs/kit":"^1.27.3","@types/express":"^4.17.13","@types/json-schema":"^7.0.15","@types/node":"^20.11.20","@vercel/node":"^2.15.9",express:"^4.19.2",h3:"^1.11.1",next:"^13.5.4",prettier:"^3.2.5","ts-node":"^10.9.2",tsup:"^8.0.2",typescript:"^5.3.3",vitest:"^1.2.1",zod:"^3.23.0","zod-to-json-schema":"^3.23.0"},dependencies:{"@novu/shared":"^2.0.0-canary.0",ajv:"^8.12.0","ajv-formats":"^2.1.1","better-ajv-errors":"^1.2.0",chalk:"^4.1.2","cross-fetch":"^4.0.0","json-schema-faker":"^0.5.6","json-schema-to-ts":"^3.0.0",liquidjs:"^10.13.1",ora:"^5.4.1"}};var U=fe.version,ie="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function Se(){return process.env.NODE_ENV==="development"}var ae=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=U;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!Se()};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 re(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:U,frameworkVersion:ie,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 te(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(Te(e))}async validate(e,t,r,o,i,c,d){let n=await Oe(t,e);if(n.success)return n.data;switch(r){case"event":this.throwInvalidEvent(o,i,n.errors);case"step":this.throwInvalidStep(c,o,i,n.errors);case"provider":this.throwInvalidProvider(c,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 K(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 M(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new $(t,r);case"payload":throw new S(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let c=this.getStep(e.workflowId,r),d=Ce(e),n=await this.createStepControls(c,d),E=e.action==="preview";if(!E&&await this.shouldSkip(i?.skip,n))return t({options:{skip:!0}}),{};let a=this.previewStep.bind(this),u=this.executeStep.bind(this),N=await(E?a:u)(e,{...c,providers:c.providers.map(h=>{let O=i?.providers?.[h.type];if(!O)throw new B(h.type);return {...h,resolve:O}}),resolve:o});return r===e.stepId&&t(N),N.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
22
+ ${p.bold(p.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),c=process.hrtime(),d={outputs:{},providers:{},options:{}},n,E=new Promise(A=>{n=A;}),a=A=>{n(),d=A;},u;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new S(e.workflowId,{message:"Event `payload` is required"});let A=await this.createExecutionPayload(e,i);await Promise.race([E,i.execute({payload:A,environment:{},inputs:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,a),sms:this.executeStepFactory(e,a),inApp:this.executeStepFactory(e,a),digest:this.executeStepFactory(e,a),delay:this.executeStepFactory(e,a),push:this.executeStepFactory(e,a),chat:this.executeStepFactory(e,a),custom:this.executeStepFactory(e,a)}})]);}catch(A){u=A;}let T=process.hrtime(c),N=T[0],h=T[1],O=N*1e3+h/1e6,we=u?R.ERROR:R.SUCCESS,Ie=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${we} ${Ie} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,O,u),u)throw u;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:O}}}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?R.ERROR:R.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",c=r?"Failed to execute":i,d=r?p.error:p.success,n=`${o} ${c} workflowId: '${e.workflowId}`;console.log(`
22
23
  ${p.bold(d(n))}'`),console.log(` \u251C ${R.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${R.ACTION} action: '${e.action}'`),console.log(` \u2514 ${R.DURATION} duration: '${t.toFixed(2)}ms'
23
- `);}async executeProviders(e,t,r){return t.providers.reduce(async(s,i)=>{let c=await s,d=this.previewProvider.bind(this),n=this.executeProvider.bind(this),a=await(e.action==="preview"?d:n)(e,t,i,r);return {...c,[i.type]:a}},Promise.resolve({}))}previewProvider(e,t,r,s){return console.log(` ${R.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,s){let i=ne__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let c=await this.createStepControls(t,e),d=await r.resolve({controls:c,outputs:s}),n=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),n}else i.stopAndPersist({symbol:R.HYDRATED,text:`Hydrated provider: \`${r.type}\``});}catch(c){throw i.stopAndPersist({symbol:R.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new B(`Failed to execute provider: '${r.type}'.
24
- ${c.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=ne__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let s=await this.createStepControls(t,e),i=await this.compileControls(s,e),c=await t.resolve(i),d=await this.validate(c,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(s){throw r.stopAndPersist({prefixText:"",symbol:R.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),s}}else {let r=ne__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:R.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new F(e.workflowId,t.stepId)}catch(s){throw r.stopAndPersist({symbol:R.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),s}}}async compileControls(e,t){let r=this.templateEngine.parse(JSON.stringify(e)),s=await this.templateEngine.render(r,{...t.payload||t.data,subscriber:t.subscriber});return JSON.parse(s)}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=ne__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),c=await t.resolve(i),d=await this.validate(c,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:R.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:R.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:s,providers:await this.executeProviders(e,t,s)}}}catch(s){throw r.stopAndPersist({symbol:R.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 C(e);return r}};function Pe(o){return JSON.parse(JSON.stringify(o))}var ce=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new ae,this.client.addWorkflows(e.workflows),this.http=Re(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":ie,"novu-framework-sdk":D,"novu-framework-api":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")||"",i=t.searchParams.get("workflowId")||"",c=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{s!=="health-check"&&this.validateHmac(n,d);let h=this.getPostActionMap(n,i,c,s),a=this.getGetActionMap(i,c);if(r==="POST")return await this.handlePostAction(s,h);if(r==="GET")return await this.handleGetAction(s,a);if(r==="OPTIONS")return this.createResponse(200,{})}catch(h){return this.handleError(h)}return this.createError(new Y(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.tenant&&{tenant:e.tenant},...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(k).includes(e)){let r=t[e];return r()}else throw new S(e,k)}async handleGetAction(e,t){if(Object.values(U).includes(e)){let r=t[e];return r()}else throw new S(e,U)}isClientError(e){let t=Object.values(w).includes(e.code),r=ke(e);return t||r}handleError(e){return this.isClientError(e)?(e.statusCode===500&&console.error(e),this.createError(e)):(console.error(e),this.createError(new X))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new Z;if(!this.client.secretKey)throw new ee;let[r,s]=t.split(",");if(!r||!s)throw new Q;let[i,c]=r.split("="),[d,n]=s.split("=");if(Number(i)<Date.now()-1500)throw new H;if(!(this.hashHmac(this.client.secretKey,`${c}.${JSON.stringify(e)}`)===n))throw new z}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};function ke(o){return o?.statusCode>=400&&o?.statusCode<500}var Ue="next",Cr=o=>{let t=new ce({frameworkName:Ue,...o,handler:(i,c,d)=>{let n=c,h=a=>{let u=typeof n.headers.get=="function"?n.headers.get(a):n.headers[a];return Array.isArray(u)?u[0]:u};return {body:()=>typeof n.json=="function"?n.json():n.body,headers:h,method:()=>i||n.method||"",queryString:(a,u)=>{let T=n.query?.[a]||u.searchParams.get(a);return Array.isArray(T)?T[0]:T},url:()=>{let a;try{a=new URL(n.url);}catch{}if(a){let E=h("host");if(E){let O=new URL(E.includes("://")?E:`${a.protocol}//${E}`);a.protocol=O.protocol,a.host=O.host,a.port=O.port,a.username=O.username,a.password=O.password;}return a}let u="https",T=h("host")||"";try{process.env.NODE_ENV==="development"&&(u="http");}catch{}return new URL(n.url,`${u}://${T}`)},transformResponse:({body:a,headers:u,status:T})=>{if(typeof d?.setHeader=="function"&&Object.entries(u).forEach(([E,O])=>{d.setHeader(E,O);}),typeof d?.status=="function"&&typeof d?.send=="function"){d.status(T).send(a);return}let N=ue();return new N(a,{status:T,headers:u})}}}}).createHandler(),r=t.bind(null,void 0);return Object.defineProperties(r,{GET:{value:t.bind(null,"GET")},POST:{value:t.bind(null,"POST")},OPTIONS:{value:t.bind(null,"OPTIONS")}})};
24
+ `);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let c=await o,d=this.previewProvider.bind(this),n=this.executeProvider.bind(this),a=await(e.action==="preview"?d:n)(e,t,i,r);return {...c,[i.type]:a}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${R.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=ne__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let c=await this.createStepControls(t,e),d=await r.resolve({controls:c,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}else i.stopAndPersist({symbol:R.HYDRATED,text:`Hydrated provider: \`${r.type}\``});}catch(c){throw i.stopAndPersist({symbol:R.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new J(`Failed to execute provider: '${r.type}'.
25
+ ${c.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=ne__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),c=await t.resolve(i),d=await this.validate(c,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:R.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=ne__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:R.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new W(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:R.ERROR,text:`Failed to hydrate stepId: \`${t.stepId}\``}),o}}}async compileControls(e,t){let r=this.templateEngine.parse(JSON.stringify(e)),o=await this.templateEngine.render(r,{...t.payload||t.data,subscriber:t.subscriber});return JSON.parse(o)}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=ne__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),c=await t.resolve(i),d=await this.validate(c,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:R.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:R.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:R.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}};function Ce(s){return JSON.parse(JSON.stringify(s))}var ce=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new ae,this.client.addWorkflows(e.workflows),this.http=Re(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":ie,"novu-framework-sdk":U,"novu-framework-api":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")||"",c=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 E=this.getPostActionMap(n,i,c,o),a=this.getGetActionMap(i,c);if(r==="POST")return await this.handlePostAction(o,E);if(r==="GET")return await this.handleGetAction(o,a);if(r==="OPTIONS")return this.createResponse(200,{})}catch(E){return this.handleError(E)}return this.createError(new Y(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.tenant&&{tenant:e.tenant},...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(P).includes(e)){let r=t[e];return r()}else throw new C(e,P)}async handleGetAction(e,t){if(Object.values(L).includes(e)){let r=t[e];return r()}else throw new C(e,L)}isBridgeError(e){return Object.values(w).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 g))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new Z;if(!this.client.secretKey)throw new ee;let[r,o]=t.split(",");if(!r||!o)throw new Q;let[i,c]=r.split("="),[d,n]=o.split("=");if(Number(i)<Date.now()-1500)throw new H;if(!(this.hashHmac(this.client.secretKey,`${c}.${JSON.stringify(e)}`)===n))throw new z}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var Ue="next",Ur=s=>{let t=new ce({frameworkName:Ue,...s,handler:(i,c,d)=>{let n=c,E=a=>{let u=typeof n.headers.get=="function"?n.headers.get(a):n.headers[a];return Array.isArray(u)?u[0]:u};return {body:()=>typeof n.json=="function"?n.json():n.body,headers:E,method:()=>i||n.method||"",queryString:(a,u)=>{let T=n.query?.[a]||u.searchParams.get(a);return Array.isArray(T)?T[0]:T},url:()=>{let a;try{a=new URL(n.url);}catch{}if(a){let h=E("host");if(h){let O=new URL(h.includes("://")?h:`${a.protocol}//${h}`);a.protocol=O.protocol,a.host=O.host,a.port=O.port,a.username=O.username,a.password=O.password;}return a}let u="https",T=E("host")||"";try{process.env.NODE_ENV==="development"&&(u="http");}catch{}return new URL(n.url,`${u}://${T}`)},transformResponse:({body:a,headers:u,status:T})=>{if(typeof d?.setHeader=="function"&&Object.entries(u).forEach(([h,O])=>{d.setHeader(h,O);}),typeof d?.status=="function"&&typeof d?.send=="function"){d.status(T).send(a);return}let N=ue();return new N(a,{status:T,headers:u})}}}}).createHandler(),r=t.bind(null,void 0);return Object.defineProperties(r,{GET:{value:t.bind(null,"GET")},POST:{value:t.bind(null,"POST")},OPTIONS:{value:t.bind(null,"OPTIONS")}})};
25
26
 
26
27
  exports.frameworkName = Ue;
27
- exports.serve = Cr;
28
+ exports.serve = Ur;
package/dist/nuxt.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as h3 from 'h3';
2
2
  import { H3Event } from 'h3';
3
- import { q as SupportedFrameworkName, b as ServeHandlerOptions } from './handler-Mor_4K8F.js';
3
+ import { q as SupportedFrameworkName, b as ServeHandlerOptions } from './handler-3oTUJvk2.js';
4
4
  import 'json-schema-to-ts';
5
5
  import 'zod';
6
6
  import '@novu/shared';