@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/express.d.ts +2 -2
- package/dist/express.js +10 -9
- package/dist/h3.d.ts +2 -2
- package/dist/h3.js +9 -8
- package/dist/{handler-Mor_4K8F.d.ts → handler-3oTUJvk2.d.ts} +15 -3
- package/dist/index.d.ts +4 -15
- package/dist/index.js +20 -19
- package/dist/next.d.ts +1 -1
- package/dist/next.js +9 -8
- package/dist/nuxt.d.ts +1 -1
- package/dist/nuxt.js +9 -8
- package/dist/remix.d.ts +1 -1
- package/dist/remix.js +9 -8
- package/dist/sveltekit.d.ts +1 -1
- package/dist/sveltekit.js +9 -8
- package/package.json +1 -1
package/dist/express.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { q as SupportedFrameworkName, b as ServeHandlerOptions } from './handler-
|
|
1
|
+
import { q as SupportedFrameworkName, b as ServeHandlerOptions } from './handler-3oTUJvk2.js';
|
|
2
2
|
import 'json-schema-to-ts';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '@novu/shared';
|
|
5
5
|
|
|
6
6
|
declare const frameworkName: SupportedFrameworkName;
|
|
7
7
|
/**
|
|
8
|
-
* Serve and register any declared
|
|
8
|
+
* Serve and register any declared workflows with Novu, making them available
|
|
9
9
|
* to be triggered by events.
|
|
10
10
|
*
|
|
11
11
|
* The return type is currently `any` to ensure there's no required type matches
|
package/dist/express.js
CHANGED
|
@@ -5,23 +5,24 @@ var jsonSchemaFaker = require('json-schema-faker');
|
|
|
5
5
|
var liquidjs = require('liquidjs');
|
|
6
6
|
var ie = require('ora');
|
|
7
7
|
require('cross-fetch');
|
|
8
|
-
var
|
|
9
|
-
var
|
|
8
|
+
var A = require('chalk');
|
|
9
|
+
var shared = require('@novu/shared');
|
|
10
|
+
var Ae = require('ajv');
|
|
10
11
|
var Ne = 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 ie__default = /*#__PURE__*/_interopDefault(ie);
|
|
16
|
-
var
|
|
17
|
-
var
|
|
17
|
+
var A__default = /*#__PURE__*/_interopDefault(A);
|
|
18
|
+
var Ae__default = /*#__PURE__*/_interopDefault(Ae);
|
|
18
19
|
var Ne__default = /*#__PURE__*/_interopDefault(Ne);
|
|
19
20
|
|
|
20
|
-
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),k=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(k||{});var h=(c=>(c.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",c.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",c.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",c.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",c.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",c.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",c.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",c.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",c.STEP_NOT_FOUND_ERROR="StepNotFoundError",c.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",c.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",c.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",c.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",c.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",c.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",c.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",c.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",c.SIGNATURE_INVALID_ERROR="SignatureInvalidError",c.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",c.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",c.PLATFORM_ERROR="PlatformError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",c))(h||{});var U=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(U||{});var O=class extends Error{data},L=class extends O{statusCode=404},R=class extends O{statusCode=400},T=class extends O{statusCode=401},m=class extends O{statusCode=500},b=class extends O{statusCode=409};var V=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},x=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},F=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},W=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},$=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},M=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},G=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var j=class extends Error{statusCode;message;code;constructor(e,t,r){super(r),this.statusCode=e,this.code=t;}};var l={info:s=>N__default.default.blue(s),warning:s=>N__default.default.yellow(s),error:s=>N__default.default.red(s),success:s=>N__default.default.green(s),underline:s=>N__default.default.underline(s),bold:s=>N__default.default.bold(s)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var de=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),K=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var ue=(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)}),n=await i.json();if(i.ok)return n;throw new j(n.statusCode,n.error,n.message)},delete:async r=>(await fetch(t+"/v1"+r,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`}})).json()}};var Y=class extends O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${de(U)}`},y=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${de(t)}`);}};var X=class extends m{code="PlatformError";message="Something went wrong. Please try again later."};var g=class extends b{constructor(e,t){super(`${K(e)} with id: \`${t}\` already exists. Please use a different id.`);}},w=class extends L{constructor(e,t){super(`${K(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},A=class extends m{constructor(e,t){super(`Failed to execute ${K(e)} with id: \`${t}\`. Please try again later.`);}};var J=class extends w{code="ProviderNotFoundError";constructor(e){super("provider",e);}},B=class extends A{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var q=class extends T{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 T{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},Z=class extends T{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},Q=class extends T{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},H=class extends T{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var ee=class extends w{code="StepNotFoundError";constructor(e){super("step",e);}};var S=class extends w{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},te=class extends g{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var re=class{ajv;compiledSchemas;constructor(){this.ajv=new me__default.default({useDefaults:!0,removeAdditional:"all"}),Ne__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 oe=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 Ee=[new oe,new re],he=async(s,e)=>{for(let t of Ee)if(t.isSchema(s))return t.validate(e,s);throw new Error("Invalid schema")},Oe=s=>{for(let e of Ee)if(e.isSchema(s))return e.transformToJsonSchema(s);throw new Error("Invalid schema")};var Te={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 P=Te.version,se="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function ye(){return process.env.NODE_ENV==="development"}var ne=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=P;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!ye()};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 te(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:P,frameworkVersion:se,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new S(e)}getStep(e,t){let o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new ee(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(Oe(e))}async validate(e,t,r,o,i,n,d){let a=await he(t,e);if(a.success)return a.data;switch(r){case"event":this.throwInvalidEvent(o,i,a.errors);case"step":this.throwInvalidStep(n,o,i,a.errors);case"provider":this.throwInvalidProvider(n,d,o,i,a.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 G(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 $(r,e,o);case"result":throw new M(r,e,o);case"controls":throw new W(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new F(t,r);case"payload":throw new x(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let n=this.getStep(e.workflowId,r),d=ge(e),a=await this.createStepControls(n,d),E=e.action==="preview";if(!E&&await this.shouldSkip(i?.skip,a))return t({options:{skip:!0}}),{};let u=this.previewStep.bind(this),I=this.executeStep.bind(this),C=await(E?u:I)(e,{...n,providers:n.providers.map(f=>{let v=i?.providers?.[f.type];if(!v)throw new J(f.type);return {...f,resolve:v}}),resolve:o});return r===e.stepId&&t(C),C.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
|
|
21
|
-
${l.bold(l.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),n=process.hrtime(),d={outputs:{},providers:{},options:{}},a,E=new Promise(
|
|
21
|
+
var g=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(g||{}),U=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(U||{});var h=(c=>(c.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",c.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",c.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",c.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",c.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",c.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",c.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",c.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",c.STEP_NOT_FOUND_ERROR="StepNotFoundError",c.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",c.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",c.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",c.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",c.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",c.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",c.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",c.INVALID_ACTION_ERROR="InvalidActionError",c.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",c.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",c.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",c.SIGNATURE_INVALID_ERROR="SignatureInvalidError",c.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",c.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",c.BRIDGE_ERROR="BridgeError",c.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",c.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",c))(h||{});var L=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(L||{});var O=class extends Error{data},b=class extends O{statusCode=404},R=class extends O{statusCode=400},T=class extends O{statusCode=401},m=class extends O{statusCode=500},V=class extends O{statusCode=409};var F=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},y=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},M=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},G=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},j=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var K=class extends O{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var l={info:s=>A__default.default.blue(s),warning:s=>A__default.default.yellow(s),error:s=>A__default.default.red(s),success:s=>A__default.default.green(s),underline:s=>A__default.default.underline(s),bold:s=>A__default.default.bold(s)},p={SUCCESS:l.success("\u2714"),ERROR:l.error("\u2717"),WARNING:l.warning("\u26A0"),INFO:l.info("\u2139"),ARROW:l.bold("\u2192"),MOCK:l.info("\u25CB"),HYDRATED:l.bold(l.info("\u2192")),STEP:l.info("\u03C3"),ACTION:l.info("\u03B1"),DURATION:l.info("\u0394"),PROVIDER:l.info("\u2699"),OUTPUT:l.info("\u21E2"),INPUT:l.info("\u21E0"),WORKFLOW:l.info("\u03C9"),STATE:l.info("\u03C3"),EXECUTE:l.info("\u03B5"),PREVIEW:l.info("\u03C1")};var 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 ue=(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)}),n=await i.json();if(i.ok)return n;throw shared.checkIsResponseError(n)?new K(n.statusCode,n.error,n.message):new N("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 O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${de(L)}`},S=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${de(t)}`);}};var N=class extends m{code="BridgeError";message="Something went wrong. Please try again later."};var P=class extends V{constructor(e,t){super(`${X(e)} with id: \`${t}\` already exists. Please use a different id.`);}},w=class extends b{constructor(e,t){super(`${X(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},v=class extends m{constructor(e,t){super(`Failed to execute ${X(e)} with id: \`${t}\`. Please try again later.`);}};var B=class extends w{code="ProviderNotFoundError";constructor(e){super("provider",e);}},J=class extends v{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var q=class extends T{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 T{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},Z=class extends T{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},Q=class extends T{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},H=class extends T{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var ee=class extends w{code="StepNotFoundError";constructor(e){super("step",e);}};var C=class extends w{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},te=class extends P{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var re=class{ajv;compiledSchemas;constructor(){this.ajv=new Ae__default.default({useDefaults:!0,removeAdditional:"all"}),Ne__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 oe=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 Ee=[new oe,new re],he=async(s,e)=>{for(let t of Ee)if(t.isSchema(s))return t.validate(e,s);throw new Error("Invalid schema")},Oe=s=>{for(let e of Ee)if(e.isSchema(s))return e.transformToJsonSchema(s);throw new Error("Invalid schema")};var Te={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 D=Te.version,se="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function ye(){return process.env.NODE_ENV==="development"}var ne=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:!ye()};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 te(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:D,frameworkVersion:se,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 o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new ee(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(Oe(e))}async validate(e,t,r,o,i,n,d){let a=await he(t,e);if(a.success)return a.data;switch(r){case"event":this.throwInvalidEvent(o,i,a.errors);case"step":this.throwInvalidStep(n,o,i,a.errors);case"provider":this.throwInvalidProvider(n,d,o,i,a.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 j(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 M(r,e,o);case"result":throw new G(r,e,o);case"controls":throw new $(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new y(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let n=this.getStep(e.workflowId,r),d=Se(e),a=await this.createStepControls(n,d),E=e.action==="preview";if(!E&&await this.shouldSkip(i?.skip,a))return t({options:{skip:!0}}),{};let u=this.previewStep.bind(this),I=this.executeStep.bind(this),k=await(E?u:I)(e,{...n,providers:n.providers.map(_=>{let x=i?.providers?.[_.type];if(!x)throw new B(_.type);return {..._,resolve:x}}),resolve:o});return r===e.stepId&&t(k),k.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
|
+
${l.bold(l.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),n=process.hrtime(),d={outputs:{},providers:{},options:{}},a,E=new Promise(f=>{a=f;}),u=f=>{a(),d=f;},I;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new y(e.workflowId,{message:"Event `payload` is required"});let f=await this.createExecutionPayload(e,i);await Promise.race([E,i.execute({payload:f,environment:{},inputs:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,u),sms:this.executeStepFactory(e,u),inApp:this.executeStepFactory(e,u),digest:this.executeStepFactory(e,u),delay:this.executeStepFactory(e,u),push:this.executeStepFactory(e,u),chat:this.executeStepFactory(e,u),custom:this.executeStepFactory(e,u)}})]);}catch(f){I=f;}let ce=process.hrtime(n),k=ce[0],_=ce[1],x=k*1e3+_/1e6,we=I?p.ERROR:p.SUCCESS,Ie=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${we} ${Ie} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,x,I),I)throw I;return {outputs:d.outputs,providers:d.providers,options:d.options,metadata:{status:"success",error:!1,duration:x}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let o=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",n=r?"Failed to execute":i,d=r?l.error:l.success,a=`${o} ${n} workflowId: '${e.workflowId}`;console.log(`
|
|
22
23
|
${l.bold(d(a))}'`),console.log(` \u251C ${p.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${p.ACTION} action: '${e.action}'`),console.log(` \u2514 ${p.DURATION} duration: '${t.toFixed(2)}ms'
|
|
23
|
-
`);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let n=await o,d=this.previewProvider.bind(this),a=this.executeProvider.bind(this),u=await(e.action==="preview"?d:a)(e,t,i,r);return {...n,[i.type]:u}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=ie__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let n=await this.createStepControls(t,e),d=await r.resolve({controls:n,outputs:o}),a=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),a}else i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``});}catch(n){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new
|
|
24
|
-
${n.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=ie__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),n=await t.resolve(i),d=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),a=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:a}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=ie__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new
|
|
24
|
+
`);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let n=await o,d=this.previewProvider.bind(this),a=this.executeProvider.bind(this),u=await(e.action==="preview"?d:a)(e,t,i,r);return {...n,[i.type]:u}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=ie__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let n=await this.createStepControls(t,e),d=await r.resolve({controls:n,outputs:o}),a=await this.validate(d,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),a}else i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``});}catch(n){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new J(`Failed to execute provider: '${r.type}'.
|
|
25
|
+
${n.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=ie__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),n=await t.resolve(i),d=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),a=await this.executeProviders(e,t,d);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:d,providers:a}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=ie__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new F(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.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=ie__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),n=await t.resolve(i),d=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:d,providers:await this.executeProviders(e,t,d)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new C(e);return r}};function Se(s){return JSON.parse(JSON.stringify(s))}var ae=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new ne,this.client.addWorkflows(e.workflows),this.http=ue(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":se,"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(),o=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",n=t.searchParams.get("stepId")||"",d=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",a={};try{r==="POST"&&(a=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(a,d);let E=this.getPostActionMap(a,i,n,o),u=this.getGetActionMap(i,n);if(r==="POST")return await this.handlePostAction(o,E);if(r==="GET")return await this.handleGetAction(o,u);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(g).includes(e)){let r=t[e];return r()}else throw new S(e,g)}async handleGetAction(e,t){if(Object.values(U).includes(e)){let r=t[e];return r()}else throw new S(e,U)}isBridgeError(e){return Object.values(h).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 N))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new z;if(!this.client.secretKey)throw new H;let[r,o]=t.split(",");if(!r||!o)throw new Z;let[i,n]=r.split("="),[d,a]=o.split("=");if(Number(i)<Date.now()-1500)throw new Q;if(!(this.hashHmac(this.client.secretKey,`${n}.${JSON.stringify(e)}`)===a))throw new q}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var De="express",kr=s=>new ae({frameworkName:De,...s,handler:(t,r)=>({body:()=>t.body,headers:o=>{let i=t.headers[o];return Array.isArray(i)?i[0]:i},method:()=>t.method||"GET",url:()=>{let o=t.headers.host||"",i=o?.includes("://")?"":`${t.protocol||"https"}://`;return new URL(t.originalUrl||t.url||"",`${i}${o||""}`)},queryString:o=>{let i=t.query[o];return Array.isArray(i)?i[0]:i},transformResponse:({body:o,headers:i,status:n})=>(Object.entries(i).forEach(([d,a])=>{r.setHeader(d,a);}),r.status(n).send(o))})}).createHandler();
|
|
25
26
|
|
|
26
27
|
exports.frameworkName = De;
|
|
27
|
-
exports.serve =
|
|
28
|
+
exports.serve = kr;
|
package/dist/h3.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { H3Event, EventHandlerRequest } from 'h3';
|
|
2
|
-
import { q as SupportedFrameworkName, b as ServeHandlerOptions } from './handler-
|
|
2
|
+
import { q as SupportedFrameworkName, b as ServeHandlerOptions } from './handler-3oTUJvk2.js';
|
|
3
3
|
import 'json-schema-to-ts';
|
|
4
4
|
import 'zod';
|
|
5
5
|
import '@novu/shared';
|
|
6
6
|
|
|
7
7
|
declare const frameworkName: SupportedFrameworkName;
|
|
8
8
|
/**
|
|
9
|
-
* In h3, serve and register any declared
|
|
9
|
+
* In h3, serve and register any declared workflows with Novu, making
|
|
10
10
|
* them available to be triggered by events.
|
|
11
11
|
*
|
|
12
12
|
* @example
|
package/dist/h3.js
CHANGED
|
@@ -7,22 +7,23 @@ var liquidjs = require('liquidjs');
|
|
|
7
7
|
var ie = require('ora');
|
|
8
8
|
require('cross-fetch');
|
|
9
9
|
var N = require('chalk');
|
|
10
|
-
var
|
|
11
|
-
var Ae = require('ajv
|
|
10
|
+
var shared = require('@novu/shared');
|
|
11
|
+
var Ae = require('ajv');
|
|
12
|
+
var ge = require('ajv-formats');
|
|
12
13
|
var zodToJsonSchema = require('zod-to-json-schema');
|
|
13
14
|
|
|
14
15
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
15
16
|
|
|
16
17
|
var ie__default = /*#__PURE__*/_interopDefault(ie);
|
|
17
18
|
var N__default = /*#__PURE__*/_interopDefault(N);
|
|
18
|
-
var Ne__default = /*#__PURE__*/_interopDefault(Ne);
|
|
19
19
|
var Ae__default = /*#__PURE__*/_interopDefault(Ae);
|
|
20
|
+
var ge__default = /*#__PURE__*/_interopDefault(ge);
|
|
20
21
|
|
|
21
|
-
var D=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(D||{}),k=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(k||{});var h=(a=>(a.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",a.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",a.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",a.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",a.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",a.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",a.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",a.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",a.STEP_NOT_FOUND_ERROR="StepNotFoundError",a.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",a.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",a.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",a.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",a.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",a.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",a.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",a.INVALID_ACTION_ERROR="InvalidActionError",a.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",a.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",a.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",a.SIGNATURE_INVALID_ERROR="SignatureInvalidError",a.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",a.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",a.PLATFORM_ERROR="PlatformError",a.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",a.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",a))(h||{});var U=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(U||{});var O=class extends Error{data},L=class extends O{statusCode=404},R=class extends O{statusCode=400},T=class extends O{statusCode=401},m=class extends O{statusCode=500},b=class extends O{statusCode=409};var V=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},x=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},F=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},W=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},$=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},M=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},G=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var j=class extends Error{statusCode;message;code;constructor(e,t,r){super(r),this.statusCode=e,this.code=t;}};var d={info:s=>N__default.default.blue(s),warning:s=>N__default.default.yellow(s),error:s=>N__default.default.red(s),success:s=>N__default.default.green(s),underline:s=>N__default.default.underline(s),bold:s=>N__default.default.bold(s)},p={SUCCESS: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 de=s=>Object.values(s).map(e=>`\`${e}\``).join(", "),K=s=>s.replaceAll(/(\w)(\w*)/g,(e,t,r)=>t.toUpperCase()+r.toLowerCase()).replaceAll(/[\s-]+/g,"");var ue=(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)}),n=await i.json();if(i.ok)return n;throw new j(n.statusCode,n.error,n.message)},delete:async r=>(await fetch(t+"/v1"+r,{method:"DELETE",headers:{"Content-Type":"application/json",Authorization:`ApiKey ${s}`}})).json()}};var Y=class extends O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${de(U)}`},g=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${de(t)}`);}};var X=class extends m{code="PlatformError";message="Something went wrong. Please try again later."};var y=class extends b{constructor(e,t){super(`${K(e)} with id: \`${t}\` already exists. Please use a different id.`);}},w=class extends L{constructor(e,t){super(`${K(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},A=class extends m{constructor(e,t){super(`Failed to execute ${K(e)} with id: \`${t}\`. Please try again later.`);}};var J=class extends w{code="ProviderNotFoundError";constructor(e){super("provider",e);}},B=class extends A{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var q=class extends T{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 T{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},Z=class extends T{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},Q=class extends T{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},H=class extends T{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var ee=class extends w{code="StepNotFoundError";constructor(e){super("step",e);}};var S=class extends w{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},te=class extends y{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var re=class{ajv;compiledSchemas;constructor(){this.ajv=new Ne__default.default({useDefaults:!0,removeAdditional:"all"}),Ae__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 oe=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 Ee=[new oe,new re],he=async(s,e)=>{for(let t of Ee)if(t.isSchema(s))return t.validate(e,s);throw new Error("Invalid schema")},Oe=s=>{for(let e of Ee)if(e.isSchema(s))return e.transformToJsonSchema(s);throw new Error("Invalid schema")};var Te={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 P=Te.version,se="2024-06-26";jsonSchemaFaker.JSONSchemaFaker.random.shuffle=function(){return ["[placeholder]"]};jsonSchemaFaker.JSONSchemaFaker.option({useDefaultValue:!0,alwaysFakeOptionals:!0});function ye(){return process.env.NODE_ENV==="development"}var ne=class{discoveredWorkflows=[];templateEngine=new liquidjs.Liquid;secretKey;version=P;strictAuthentication;constructor(e){let t=this.buildOptions(e);this.secretKey=t.secretKey,this.strictAuthentication=t.strictAuthentication;}buildOptions(e){let t={secretKey:void 0,strictAuthentication:!ye()};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 te(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:P,frameworkVersion:se,discovered:{workflows:e,steps:t}}}getWorkflow(e){let t=this.discoveredWorkflows.find(r=>r.workflowId===e);if(t)return t;throw new S(e)}getStep(e,t){let o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new ee(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(Oe(e))}async validate(e,t,r,o,i,n,l){let c=await he(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(o,i,c.errors);case"step":this.throwInvalidStep(n,o,i,c.errors);case"provider":this.throwInvalidProvider(n,l,o,i,c.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 G(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 $(r,e,o);case"result":throw new M(r,e,o);case"controls":throw new W(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new F(t,r);case"payload":throw new x(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let n=this.getStep(e.workflowId,r),l=Se(e),c=await this.createStepControls(n,l),E=e.action==="preview";if(!E&&await this.shouldSkip(i?.skip,c))return t({options:{skip:!0}}),{};let u=this.previewStep.bind(this),I=this.executeStep.bind(this),C=await(E?u:I)(e,{...n,providers:n.providers.map(f=>{let v=i?.providers?.[f.type];if(!v)throw new J(f.type);return {...f,resolve:v}}),resolve:o});return r===e.stepId&&t(C),C.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
|
-
${d.bold(d.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),n=process.hrtime(),l={outputs:{},providers:{},options:{}},c,E=new Promise(_=>{c=_;}),u=_=>{c(),l=_;},I;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new
|
|
22
|
+
var x=(r=>(r.TRIGGER="trigger",r.EXECUTE="execute",r.PREVIEW="preview",r))(x||{}),U=(r=>(r.DISCOVER="discover",r.HEALTH_CHECK="health-check",r.CODE="code",r))(U||{});var h=(a=>(a.WORKFLOW_NOT_FOUND_ERROR="WorkflowNotFoundError",a.WORKFLOW_ALREADY_EXISTS_ERROR="WorkflowAlreadyExistsError",a.WORKFLOW_EXECUTION_FAILED_ERROR="WorkflowExecutionFailedError",a.EXECUTION_STATE_OUTPUT_INVALID_ERROR="ExecutionStateOutputInvalidError",a.EXECUTION_STATE_RESULT_INVALID_ERROR="ExecutionStateResultInvalidError",a.EXECUTION_PROVIDER_OUTPUT_INVALID_ERROR="ExecutionProviderOutputInvalidError",a.PROVIDER_NOT_FOUND_ERROR="ProviderNotFoundError",a.PROVIDER_EXECUTION_FAILED_ERROR="ProviderExecutionFailedError",a.STEP_NOT_FOUND_ERROR="StepNotFoundError",a.STEP_ALREADY_EXISTS_ERROR="StepAlreadyExistsError",a.STEP_EXECUTION_FAILED_ERROR="StepExecutionFailedError",a.EXECUTION_STATE_CORRUPT_ERROR="ExecutionStateCorruptError",a.EXECUTION_EVENT_PAYLOAD_INVALID_ERROR="ExecutionEventPayloadInvalidError",a.EXECUTION_EVENT_CONTROL_INVALID_ERROR="ExecutionEventControlInvalidError",a.EXECUTION_STATE_CONTROL_INVALID_ERROR="ExecutionStateControlInvalidError",a.METHOD_NOT_ALLOWED_ERROR="MethodNotAllowedError",a.INVALID_ACTION_ERROR="InvalidActionError",a.MISSING_SECRET_KEY_ERROR="MissingSecretKeyError",a.SIGNATURE_MISMATCH_ERROR="SignatureMismatchError",a.SIGNATURE_NOT_FOUND_ERROR="SignatureNotFoundError",a.SIGNATURE_INVALID_ERROR="SignatureInvalidError",a.SIGNATURE_EXPIRED_ERROR="SignatureExpiredError",a.SIGNING_KEY_NOT_FOUND_ERROR="SigningKeyNotFoundError",a.BRIDGE_ERROR="BridgeError",a.SIGNATURE_VERSION_INVALID_ERROR="SignatureVersionInvalidError",a.WORKFLOW_PAYLOAD_INVALID_ERROR="WorkflowPayloadInvalidError",a))(h||{});var L=(r=>(r.POST="POST",r.GET="GET",r.OPTIONS="OPTIONS",r))(L||{});var O=class extends Error{data},b=class extends O{statusCode=404},R=class extends O{statusCode=400},T=class extends O{statusCode=401},m=class extends O{statusCode=500},V=class extends O{statusCode=409};var F=class extends R{code="ExecutionStateCorruptError";constructor(e,t){super(`Workflow with id: \`${e}\` has a corrupt state. Step with id: \`${t}\` does not exist. Please provide the missing state.`),this.data={workflowId:e,stepId:t};}},y=class extends R{code="ExecutionEventPayloadInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`payload\`. Please provide the correct event payload.`),this.data=t;}},W=class extends R{code="ExecutionEventControlInvalidError";constructor(e,t){super(`Workflow with id: \`${e}\` has invalid \`controls\`. Please provide the correct event controls.`),this.data=t;}},$=class extends R{code="ExecutionStateControlInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid \`controls\`. Please provide the correct step controls.`),this.data=r;}},M=class extends R{code="ExecutionStateOutputInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid output. Please provide the correct step output.`),this.data=r;}},G=class extends R{code="ExecutionStateResultInvalidError";constructor(e,t,r){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` has invalid result. Please provide the correct step result.`),this.data=r;}},j=class extends R{code="ExecutionProviderOutputInvalidError";constructor(e,t,r,o){super(`Workflow with id: \`${e}\` has an invalid state. Step with id: \`${t}\` and provider with id: \`${r}\` has invalid output. Please provide the correct provider output.`),this.data=o;}};var K=class extends O{statusCode;data;code;constructor(e,t,r){super(),this.data={message:r},this.statusCode=e,this.code=t;}};var d={info:s=>N__default.default.blue(s),warning:s=>N__default.default.yellow(s),error:s=>N__default.default.red(s),success:s=>N__default.default.green(s),underline:s=>N__default.default.underline(s),bold:s=>N__default.default.bold(s)},p={SUCCESS: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 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 ue=(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)}),n=await i.json();if(i.ok)return n;throw shared.checkIsResponseError(n)?new K(n.statusCode,n.error,n.message):new A("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 O{code="MethodNotAllowedError";statusCode=405;message=`Method not allowed. Please use one of ${de(L)}`},S=class extends R{code="InvalidActionError";constructor(e,t){super(`Invalid query string: \`action\`=\`${e}\`. Please use one of ${de(t)}`);}};var A=class extends m{code="BridgeError";message="Something went wrong. Please try again later."};var P=class extends V{constructor(e,t){super(`${X(e)} with id: \`${t}\` already exists. Please use a different id.`);}},w=class extends b{constructor(e,t){super(`${X(e)} with id: \`${t}\` does not exist. Please provide a valid id.`);}},g=class extends m{constructor(e,t){super(`Failed to execute ${X(e)} with id: \`${t}\`. Please try again later.`);}};var B=class extends w{code="ProviderNotFoundError";constructor(e){super("provider",e);}},J=class extends g{code="ProviderExecutionFailedError";constructor(e){super("workflow",e);}};var q=class extends T{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 T{code="SignatureNotFoundError";constructor(){super("Signature not found. Please provide a signature in the `novu-signature` header");}},Z=class extends T{code="SignatureInvalidError";constructor(){super("Signature is invalid. Please provide a valid signature in the `novu-signature` header");}},Q=class extends T{code="SignatureExpiredError";constructor(){super(`Signature expired. Please provide a signature with a timestamp no older than ${5} minutes in the \`novu-signature\` header`);}},H=class extends T{code="SigningKeyNotFoundError";constructor(){super("Signature key not found. Please provide a valid key in the Client constructor `config.secretKey`");}};var ee=class extends w{code="StepNotFoundError";constructor(e){super("step",e);}};var C=class extends w{code="WorkflowNotFoundError";constructor(e){super("workflow",e);}},te=class extends P{code="WorkflowAlreadyExistsError";constructor(e){super("workflow",e);}};var re=class{ajv;compiledSchemas;constructor(){this.ajv=new Ae__default.default({useDefaults:!0,removeAdditional:"all"}),ge__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 oe=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 Ee=[new oe,new re],he=async(s,e)=>{for(let t of Ee)if(t.isSchema(s))return t.validate(e,s);throw new Error("Invalid schema")},Oe=s=>{for(let e of Ee)if(e.isSchema(s))return e.transformToJsonSchema(s);throw new Error("Invalid schema")};var Te={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 D=Te.version,se="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 ne=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 te(t.definition.workflowId);this.discoveredWorkflows.push(t.definition);}}healthCheck(){let e=this.discoveredWorkflows.length,t=this.discoveredWorkflows.reduce((r,o)=>r+o.steps.length,0);return {status:"ok",sdkVersion:D,frameworkVersion:se,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 o=this.getWorkflow(e).steps.find(i=>i.stepId===t);if(o)return o;throw new ee(t)}getRegisteredWorkflows(){return this.discoveredWorkflows}discover(){return {workflows:this.getRegisteredWorkflows()}}mock(e){return jsonSchemaFaker.JSONSchemaFaker.generate(Oe(e))}async validate(e,t,r,o,i,n,l){let c=await he(t,e);if(c.success)return c.data;switch(r){case"event":this.throwInvalidEvent(o,i,c.errors);case"step":this.throwInvalidStep(n,o,i,c.errors);case"provider":this.throwInvalidProvider(n,l,o,i,c.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 j(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 M(r,e,o);case"result":throw new G(r,e,o);case"controls":throw new $(r,e,o);default:throw new Error(`Invalid payload type: '${t}'`)}}throwInvalidEvent(e,t,r){switch(e){case"controls":throw new W(t,r);case"payload":throw new y(t,r);default:throw new Error(`Invalid payload type: '${e}'`)}}executeStepFactory(e,t){return async(r,o,i)=>{let n=this.getStep(e.workflowId,r),l=Pe(e),c=await this.createStepControls(n,l),E=e.action==="preview";if(!E&&await this.shouldSkip(i?.skip,c))return t({options:{skip:!0}}),{};let u=this.previewStep.bind(this),I=this.executeStep.bind(this),k=await(E?u:I)(e,{...n,providers:n.providers.map(f=>{let v=i?.providers?.[f.type];if(!v)throw new B(f.type);return {...f,resolve:v}}),resolve:o});return r===e.stepId&&t(k),k.outputs}}async shouldSkip(e,t){return e?e(t):!1}async executeWorkflow(e){let o=`${{execute:"Executing",preview:"Previewing"}[e.action]} workflowId:`;console.log(`
|
|
23
|
+
${d.bold(d.underline(o))} '${e.workflowId}'`);let i=this.getWorkflow(e.workflowId),n=process.hrtime(),l={outputs:{},providers:{},options:{}},c,E=new Promise(_=>{c=_;}),u=_=>{c(),l=_;},I;try{if(e.action==="execute"&&!e.payload&&!e.data)throw new y(e.workflowId,{message:"Event `payload` is required"});let _=await this.createExecutionPayload(e,i);await Promise.race([E,i.execute({payload:_,environment:{},inputs:{},controls:{},subscriber:e.subscriber,step:{email:this.executeStepFactory(e,u),sms:this.executeStepFactory(e,u),inApp:this.executeStepFactory(e,u),digest:this.executeStepFactory(e,u),delay:this.executeStepFactory(e,u),push:this.executeStepFactory(e,u),chat:this.executeStepFactory(e,u),custom:this.executeStepFactory(e,u)}})]);}catch(_){I=_;}let ce=process.hrtime(n),k=ce[0],f=ce[1],v=k*1e3+f/1e6,Ie=I?p.ERROR:p.SUCCESS,_e=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action";if(console.log(`${Ie} ${_e} workflowId: \`${e.workflowId}\``),this.prettyPrintExecute(e,v,I),I)throw I;return {outputs:l.outputs,providers:l.providers,options:l.options,metadata:{status:"success",error:!1,duration:v}}}async createExecutionPayload(e,t){let r=e.payload||e.data;if(e.action==="preview"){let i=this.mock(t.payload.schema);r=Object.assign(i,r);}return await this.validate(r,t.payload.unknownSchema,"event","payload",e.workflowId)}prettyPrintExecute(e,t,r){let o=r?p.ERROR:p.SUCCESS,i=e.action==="execute"?"Executed":e.action==="preview"?"Previewed":"Invalid action",n=r?"Failed to execute":i,l=r?d.error:d.success,c=`${o} ${n} workflowId: '${e.workflowId}`;console.log(`
|
|
23
24
|
${d.bold(l(c))}'`),console.log(` \u251C ${p.STEP} stepId: '${e.stepId}'`),console.log(` \u251C ${p.ACTION} action: '${e.action}'`),console.log(` \u2514 ${p.DURATION} duration: '${t.toFixed(2)}ms'
|
|
24
|
-
`);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let n=await o,l=this.previewProvider.bind(this),c=this.executeProvider.bind(this),u=await(e.action==="preview"?l:c)(e,t,i,r);return {...n,[i.type]:u}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=ie__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let n=await this.createStepControls(t,e),l=await r.resolve({controls:n,outputs:o}),c=await this.validate(l,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),c}else i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``});}catch(n){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new
|
|
25
|
-
${n.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=ie__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),n=await t.resolve(i),l=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),c=await this.executeProviders(e,t,l);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:l,providers:c}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=ie__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new
|
|
25
|
+
`);}async executeProviders(e,t,r){return t.providers.reduce(async(o,i)=>{let n=await o,l=this.previewProvider.bind(this),c=this.executeProvider.bind(this),u=await(e.action==="preview"?l:c)(e,t,i,r);return {...n,[i.type]:u}},Promise.resolve({}))}previewProvider(e,t,r,o){return console.log(` ${p.MOCK} Mocked provider: \`${r.type}\``),this.mock(r.outputs.schema)}async executeProvider(e,t,r,o){let i=ie__default.default({indent:2}).start(`Executing provider: \`${r.type}\``);try{if(e.stepId===t.stepId){let n=await this.createStepControls(t,e),l=await r.resolve({controls:n,outputs:o}),c=await this.validate(l,r.outputs.unknownSchema,"step","output",e.workflowId,t.stepId,r.type);return i.succeed(`Executed provider: \`${r.type}\``),c}else i.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated provider: \`${r.type}\``});}catch(n){throw i.stopAndPersist({symbol:p.ERROR,text:`Failed to execute provider: \`${r.type}\``}),new J(`Failed to execute provider: '${r.type}'.
|
|
26
|
+
${n.message}`)}}async executeStep(e,t){if(e.stepId===t.stepId){let r=ie__default.default({indent:1}).start(`Executing stepId: \`${t.stepId}\``);try{let o=await this.createStepControls(t,e),i=await this.compileControls(o,e),n=await t.resolve(i),l=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId),c=await this.executeProviders(e,t,l);return r.succeed(`Executed stepId: \`${t.stepId}\``),{outputs:l,providers:c}}catch(o){throw r.stopAndPersist({prefixText:"",symbol:p.ERROR,text:`Failed to execute stepId: \`${t.stepId}\``}),o}}else {let r=ie__default.default({indent:1}).start(`Hydrating stepId: \`${t.stepId}\``);try{let o=e.state.find(i=>i.stepId===t.stepId);if(o){let i=await this.validate(o.outputs,t.results.unknownSchema,"step","result",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.HYDRATED,text:`Hydrated stepId: \`${t.stepId}\``}),{outputs:i,providers:await this.executeProviders(e,t,i)}}else throw new F(e.workflowId,t.stepId)}catch(o){throw r.stopAndPersist({symbol:p.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=ie__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),n=await t.resolve(i),l=await this.validate(n,t.outputs.unknownSchema,"step","output",e.workflowId,t.stepId);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:l,providers:await this.executeProviders(e,t,l)}}else {let o=this.mock(t.results.schema);return r.stopAndPersist({symbol:p.MOCK,text:`Mocked stepId: \`${t.stepId}\``}),{outputs:o,providers:await this.executeProviders(e,t,o)}}}catch(o){throw r.stopAndPersist({symbol:p.ERROR,text:`Failed to preview stepId: \`${t.stepId}\``}),o}}getStepCode(e,t){return {code:this.getStep(e,t).resolve.toString()}}getWorkflowCode(e){return {code:this.getWorkflow(e).execute.toString()}}getCode(e,t){let r;if(e)t?r=this.getStepCode(e,t):r=this.getWorkflowCode(e);else throw new C(e);return r}};function Pe(s){return JSON.parse(JSON.stringify(s))}var ae=class{frameworkName;handler;client;hmacEnabled;http;constructor(e){this.handler=e.handler,this.client=e.client?e.client:new ne,this.client.addWorkflows(e.workflows),this.http=ue(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":se,"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(),o=t.searchParams.get("action")||"",i=t.searchParams.get("workflowId")||"",n=t.searchParams.get("stepId")||"",l=await e.headers("novu-signature")||await e.headers("x-novu-signature")||"",c={};try{r==="POST"&&(c=await e.body());}catch{}try{o!=="health-check"&&this.validateHmac(c,l);let E=this.getPostActionMap(c,i,n,o),u=this.getGetActionMap(i,n);if(r==="POST")return await this.handlePostAction(o,E);if(r==="GET")return await this.handleGetAction(o,u);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(x).includes(e)){let r=t[e];return r()}else throw new S(e,x)}async handleGetAction(e,t){if(Object.values(U).includes(e)){let r=t[e];return r()}else throw new S(e,U)}isBridgeError(e){return Object.values(h).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 A))}validateHmac(e,t){if(!this.hmacEnabled)return;if(!t)throw new z;if(!this.client.secretKey)throw new H;let[r,o]=t.split(",");if(!r||!o)throw new Z;let[i,n]=r.split("="),[l,c]=o.split("=");if(Number(i)<Date.now()-1500)throw new Q;if(!(this.hashHmac(this.client.secretKey,`${n}.${JSON.stringify(e)}`)===c))throw new q}hashHmac(e,t){return crypto.createHmac("sha256",e).update(t).digest("hex")}};var Ve="h3",Fr=s=>new ae({frameworkName:Ve,...s,handler:t=>({body:()=>h3.readBody(t),headers:r=>h3.getHeader(t,r),method:()=>t.method,url:()=>new URL(String(t.path),`${process.env.NODE_ENV==="development"?"http":"https"}://${String(h3.getHeader(t,"host"))}`),queryString:r=>String(h3.getQuery(t)[r]),transformResponse:r=>{let{res:o}=t.node;return o.statusCode=r.status,h3.setHeaders(t,r.headers),h3.send(t,r.body)}})}).createHandler();
|
|
26
27
|
|
|
27
28
|
exports.frameworkName = Ve;
|
|
28
|
-
exports.serve =
|
|
29
|
+
exports.serve = Fr;
|
|
@@ -31,6 +31,17 @@ type ClientOptions = {
|
|
|
31
31
|
strictAuthentication?: boolean;
|
|
32
32
|
};
|
|
33
33
|
|
|
34
|
+
declare enum PostActionEnum {
|
|
35
|
+
TRIGGER = "trigger",
|
|
36
|
+
EXECUTE = "execute",
|
|
37
|
+
PREVIEW = "preview"
|
|
38
|
+
}
|
|
39
|
+
declare enum GetActionEnum {
|
|
40
|
+
DISCOVER = "discover",
|
|
41
|
+
HEALTH_CHECK = "health-check",
|
|
42
|
+
CODE = "code"
|
|
43
|
+
}
|
|
44
|
+
|
|
34
45
|
declare enum ChannelStepEnum {
|
|
35
46
|
EMAIL = "email",
|
|
36
47
|
SMS = "sms",
|
|
@@ -3218,7 +3229,7 @@ type Event = {
|
|
|
3218
3229
|
inputs: Record<string, unknown>;
|
|
3219
3230
|
controls: Record<string, unknown>;
|
|
3220
3231
|
state: State[];
|
|
3221
|
-
action:
|
|
3232
|
+
action: Exclude<PostActionEnum, PostActionEnum.TRIGGER>;
|
|
3222
3233
|
subscriber: Subscriber;
|
|
3223
3234
|
};
|
|
3224
3235
|
type State = {
|
|
@@ -3348,10 +3359,11 @@ declare class NovuRequestHandler<Input extends any[] = any[], Output = any> {
|
|
|
3348
3359
|
private getGetActionMap;
|
|
3349
3360
|
private handlePostAction;
|
|
3350
3361
|
private handleGetAction;
|
|
3351
|
-
private
|
|
3362
|
+
private isBridgeError;
|
|
3363
|
+
private isPlatformError;
|
|
3352
3364
|
private handleError;
|
|
3353
3365
|
private validateHmac;
|
|
3354
3366
|
private hashHmac;
|
|
3355
3367
|
}
|
|
3356
3368
|
|
|
3357
|
-
export { type ExecuteInput as $, type ActionStep as A, type PushResult as B, Client as C, type DiscoverProviderOutput as D, type Execute as E, type FromSchema as F, type ChatOutput as G, type HealthCheck as H, type ChatResult as I, type JsonSchema as J, type InAppOutput as K, type InAppResult as L, type DelayOutput as M, NovuRequestHandler as N, type DelayResult as O, type PushOutput as P, type digestRegularOutput as Q, type digestTimedOutput as R, type Schema as S, type DigestOutput as T, type DigestResult as U, type Step as V, type WorkflowOptions as W, type Subscriber as X, type Either as Y, type Awaitable as Z, type Prettify as _, type Workflow as a,
|
|
3369
|
+
export { type ExecuteInput as $, type ActionStep as A, type PushResult as B, Client as C, type DiscoverProviderOutput as D, type Execute as E, type FromSchema as F, type ChatOutput as G, type HealthCheck as H, type ChatResult as I, type JsonSchema as J, type InAppOutput as K, type InAppResult as L, type DelayOutput as M, NovuRequestHandler as N, type DelayResult as O, type PushOutput as P, type digestRegularOutput as Q, type digestTimedOutput as R, type Schema as S, type DigestOutput as T, type DigestResult as U, type Step as V, type WorkflowOptions as W, type Subscriber as X, type Either as Y, type Awaitable as Z, type Prettify as _, type Workflow as a, PostActionEnum as a0, GetActionEnum as a1, ChannelStepEnum as a2, ActionStepEnum as a3, type ServeHandlerOptions as b, type CodeResult as c, type ClientOptions as d, type StepType as e, type DiscoverStepOutput as f, type DiscoverWorkflowOutput as g, type DiscoverOutput as h, type EventTriggerResult as i, type EventTriggerParams as j, type EventTriggerResponse as k, type CancelEventTriggerResponse as l, type Event as m, type State as n, type ExecuteOutputMetadata as o, type ExecuteOutput as p, type SupportedFrameworkName as q, type Skip as r, type StepOptions as s, JobStatusEnum as t, type CustomStep as u, type ChannelStep as v, type EmailOutput as w, type EmailResult as x, type SmsOutput as y, type SmsResult as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { S as Schema, J as JsonSchema, F as FromSchema, E as Execute, W as WorkflowOptions, a as Workflow } from './handler-
|
|
2
|
-
export { A as ActionStep,
|
|
1
|
+
import { S as Schema, J as JsonSchema, F as FromSchema, E as Execute, W as WorkflowOptions, a as Workflow } from './handler-3oTUJvk2.js';
|
|
2
|
+
export { A as ActionStep, a3 as ActionStepEnum, Z as Awaitable, l as CancelEventTriggerResponse, v as ChannelStep, a2 as ChannelStepEnum, G as ChatOutput, I as ChatResult, C as Client, d as ClientOptions, c as CodeResult, u as CustomStep, M as DelayOutput, O as DelayResult, T as DigestOutput, U as DigestResult, h as DiscoverOutput, D as DiscoverProviderOutput, f as DiscoverStepOutput, g as DiscoverWorkflowOutput, Y as Either, w as EmailOutput, x as EmailResult, m as Event, j as EventTriggerParams, k as EventTriggerResponse, i as EventTriggerResult, $ as ExecuteInput, p as ExecuteOutput, o as ExecuteOutputMetadata, a1 as GetActionEnum, H as HealthCheck, K as InAppOutput, L as InAppResult, t as JobStatusEnum, N as NovuRequestHandler, a0 as PostActionEnum, _ as Prettify, P as PushOutput, B as PushResult, b as ServeHandlerOptions, r as Skip, y as SmsOutput, z as SmsResult, n as State, V as Step, s as StepOptions, e as StepType, X as Subscriber, q as SupportedFrameworkName, Q as digestRegularOutput, R as digestTimedOutput } from './handler-3oTUJvk2.js';
|
|
3
3
|
import { ValidateFunction as ValidateFunction$1 } from 'ajv';
|
|
4
4
|
import { ParseReturnType } from 'zod';
|
|
5
5
|
import 'json-schema-to-ts';
|
|
@@ -94,17 +94,6 @@ declare enum CronExpression {
|
|
|
94
94
|
MONDAY_TO_FRIDAY_AT_11PM = "0 0 23 * * 1-5"
|
|
95
95
|
}
|
|
96
96
|
|
|
97
|
-
declare enum PostActionEnum {
|
|
98
|
-
TRIGGER = "trigger",
|
|
99
|
-
EXECUTE = "execute",
|
|
100
|
-
PREVIEW = "preview"
|
|
101
|
-
}
|
|
102
|
-
declare enum GetActionEnum {
|
|
103
|
-
DISCOVER = "discover",
|
|
104
|
-
HEALTH_CHECK = "health-check",
|
|
105
|
-
CODE = "code"
|
|
106
|
-
}
|
|
107
|
-
|
|
108
97
|
declare enum NovuApiEndpointsEnum {
|
|
109
98
|
SYNC = "/v1/bridge/sync",
|
|
110
99
|
DIFF = "/v1/bridge/diff"
|
|
@@ -136,7 +125,7 @@ declare enum ErrorCodeEnum {
|
|
|
136
125
|
SIGNATURE_INVALID_ERROR = "SignatureInvalidError",
|
|
137
126
|
SIGNATURE_EXPIRED_ERROR = "SignatureExpiredError",
|
|
138
127
|
SIGNING_KEY_NOT_FOUND_ERROR = "SigningKeyNotFoundError",
|
|
139
|
-
|
|
128
|
+
BRIDGE_ERROR = "BridgeError",
|
|
140
129
|
SIGNATURE_VERSION_INVALID_ERROR = "SignatureVersionInvalidError",
|
|
141
130
|
WORKFLOW_PAYLOAD_INVALID_ERROR = "WorkflowPayloadInvalidError"
|
|
142
131
|
}
|
|
@@ -251,4 +240,4 @@ interface Validator<T_Schema extends Schema> {
|
|
|
251
240
|
*/
|
|
252
241
|
declare function workflow<T_PayloadSchema extends Schema, T_ControlSchema extends Schema, T_Payload = FromSchema<T_PayloadSchema>, T_Control = FromSchema<T_ControlSchema>>(workflowId: string, execute: Execute<T_Payload, T_Control>, workflowOptions?: WorkflowOptions<T_PayloadSchema, T_ControlSchema>): Workflow<T_Payload>;
|
|
253
242
|
|
|
254
|
-
export { CronExpression, ErrorCodeEnum, Execute, FromSchema,
|
|
243
|
+
export { CronExpression, ErrorCodeEnum, Execute, FromSchema, HttpHeaderKeysEnum, HttpMethodEnum, HttpQueryKeysEnum, HttpStatusEnum, JsonSchema, NovuApiEndpointsEnum, RETRYABLE_ERROR_STATUS_CODES, ResourceEnum, SIGNATURE_TIMESTAMP_TOLERANCE, SIGNATURE_TIMESTAMP_TOLERANCE_MINUTES, Schema, type ValidateFunction, type ValidateResult, type ValidationError, type Validator, Workflow, WorkflowOptions, workflow };
|