@ronaldroe/micro-flow 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/classes/base.js +2 -2
- package/dist/src/classes/base.js.map +3 -3
- package/dist/src/classes/steps/logic_step.js.map +2 -2
- package/dist/src/classes/steps/step.js +1 -1
- package/dist/src/classes/steps/step.js.map +2 -2
- package/dist/src/classes/workflow.js +1 -1
- package/dist/src/classes/workflow.js.map +3 -3
- package/package.json +1 -1
- package/src/classes/base.js +2 -2
- package/src/classes/steps/logic_step.js +2 -0
- package/src/classes/steps/step.js +0 -11
- package/src/classes/workflow.js +1 -1
package/dist/src/classes/base.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var h=Object.defineProperty;var a=(i,t)=>h(i,"name",{value:t,configurable:!0});import{base_types as
|
|
1
|
+
var h=Object.defineProperty;var a=(i,t)=>h(i,"name",{value:t,configurable:!0});import p from"crypto";import{base_types as o}from"../enums/index.js";import e from"./state.js";class r{static{a(this,"Base")}constructor({name:t,base_type:s=o.STEP}){this.id=p.randomUUID(),this.name=t??`${s}-${this.id}`,this.base_type=s,this.timing={cancel_time:null,complete_time:null,execution_time_ms:null,start_time:null}}async execute(){throw new Error("Execute method not implemented")}log(t,s=null){if(!t||!e.get(`events.${this.base_type}`))throw new Error("Invalid event name or event emitter not found");if(e.get(`events.${this.base_type}`).emit(t,this),e.get("log_suppress"))return;const n=s?`
|
|
2
2
|
[${this.base_type.toUpperCase()} - ${this.name}] ${s}`:`
|
|
3
|
-
[${this.base_type.toUpperCase()} - ${this.name}] Event: ${t}`,m=t.endsWith("_failed")?"error":"log";console[m](n)}markAsComplete(){this.timing.complete_time=new Date,this.status=e.get("statuses")[this.base_type].COMPLETE,this.timing.execution_time_ms=this.timing.complete_time-this.timing.start_time,this.steps_by_id&&delete this.steps_by_id,this.log(e.get(`event_names.${this.base_type}`)[`${this.base_type.toUpperCase()}_COMPLETE`],`${this.base_type.charAt(0).toUpperCase()+this.base_type.slice(1)} "${this.name}" complete.`)}markAsFailed(){this.timing.complete_time=new Date,this.status=e.get("statuses")[this.base_type].FAILED,this.timing.execution_time_ms=this.timing.complete_time-this.timing.start_time,this.log(e.get(`event_names.${this.base_type}`)[`${this.base_type.toUpperCase()}_FAILED`],`${this.base_type.charAt(0).toUpperCase()+this.base_type.slice(1)} "${this.name}" failed.`)}markAsWaiting(){}markAsPending(){}markAsRunning(){this.timing.start_time=new Date,this.status=e.get("statuses")[this.base_type].RUNNING,this.log(e.get(`event_names.${this.base_type}`)[`${this.base_type.toUpperCase()}_RUNNING`],`${this.base_type.charAt(0).toUpperCase()+this.base_type.slice(1)} "${this.name}" started.`)}getState(t){return e.get(t)}setState(t,s){e.set(t,s)}deleteState(t){e.delete(t)}}export{
|
|
3
|
+
[${this.base_type.toUpperCase()} - ${this.name}] Event: ${t}`,m=t.endsWith("_failed")?"error":"log";console[m](n)}markAsComplete(){this.timing.complete_time=new Date,this.status=e.get("statuses")[this.base_type].COMPLETE,this.timing.execution_time_ms=this.timing.complete_time-this.timing.start_time,this.steps_by_id&&delete this.steps_by_id,this.log(e.get(`event_names.${this.base_type}`)[`${this.base_type.toUpperCase()}_COMPLETE`],`${this.base_type.charAt(0).toUpperCase()+this.base_type.slice(1)} "${this.name}" complete.`)}markAsFailed(){this.timing.complete_time=new Date,this.status=e.get("statuses")[this.base_type].FAILED,this.timing.execution_time_ms=this.timing.complete_time-this.timing.start_time,this.log(e.get(`event_names.${this.base_type}`)[`${this.base_type.toUpperCase()}_FAILED`],`${this.base_type.charAt(0).toUpperCase()+this.base_type.slice(1)} "${this.name}" failed.`)}markAsWaiting(){}markAsPending(){}markAsRunning(){this.timing.start_time=this.timing.start_time??new Date,this.status=e.get("statuses")[this.base_type].RUNNING,this.log(e.get(`event_names.${this.base_type}`)[`${this.base_type.toUpperCase()}_RUNNING`],`${this.base_type.charAt(0).toUpperCase()+this.base_type.slice(1)} "${this.name}" started.`)}getState(t){return e.get(t)}setState(t,s){e.set(t,s)}deleteState(t){e.delete(t)}}export{r as default};
|
|
4
4
|
//# sourceMappingURL=base.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/classes/base.js"],
|
|
4
|
-
"sourcesContent": ["import { base_types } from '../enums/index.js';\nimport State from './state.js';\n\n/**\n * Base class for workflows and steps.\n * Provides common functionality for timing, status management, logging, and state access.\n * @class Base\n */\nexport default class Base {\n /**\n * Creates a new Base instance.\n * @param {Object} options - Configuration options.\n * @param {string} [options.name] - Name of the instance.\n * @param {string} [options.base_type=base_types.STEP] - Type of the base instance.\n */\n constructor({ name, base_type = base_types.STEP }) {\n this.id = crypto.randomUUID();\n this.name = name ?? `${base_type}-${this.id}`;\n\n this.base_type = base_type;\n this.timing = {\n cancel_time: null,\n complete_time: null,\n
|
|
5
|
-
"mappings": "+EAAA,OAAS,
|
|
6
|
-
"names": ["base_types", "State", "Base", "__name", "name", "base_type", "event_name", "message", "logMessage", "logType", "path", "value"]
|
|
4
|
+
"sourcesContent": ["import crypto from 'crypto';\nimport { base_types } from '../enums/index.js';\nimport State from './state.js';\n\n/**\n * Base class for workflows and steps.\n * Provides common functionality for timing, status management, logging, and state access.\n * @class Base\n */\nexport default class Base {\n /**\n * Creates a new Base instance.\n * @param {Object} options - Configuration options.\n * @param {string} [options.name] - Name of the instance.\n * @param {string} [options.base_type=base_types.STEP] - Type of the base instance.\n */\n constructor({ name, base_type = base_types.STEP }) {\n this.id = crypto.randomUUID();\n this.name = name ?? `${base_type}-${this.id}`;\n\n this.base_type = base_type;\n this.timing = {\n cancel_time: null,\n complete_time: null,\n execution_time_ms: null,\n start_time: null,\n }\n }\n\n /**\n * Executes the instance. Must be overridden by subclasses.\n * @async\n * @throws {Error} Throws if not implemented in subclass.\n */\n async execute() {\n throw new Error('Execute method not implemented');\n }\n\n /**\n * Logs an event and emits it to the appropriate event emitter.\n * @param {string} event_name - Name of the event to log.\n * @param {string} [message=null] - Optional message to log.\n * @throws {Error} Throws if event name is invalid or event emitter not found.\n */\n log(event_name, message = null) {\n if (!event_name || !State.get(`events.${this.base_type}`)) {\n throw new Error('Invalid event name or event emitter not found');\n }\n\n State.get(`events.${this.base_type}`).emit(event_name, this);\n if (State.get('log_suppress')) {\n return;\n }\n\n const logMessage = message ? `\\n[${this.base_type.toUpperCase()} - ${this.name}] ${message}` : `\\n[${this.base_type.toUpperCase()} - ${this.name}] Event: ${event_name}`;\n const logType = event_name.endsWith('_failed') ? 'error' : 'log';\n\n console[logType](logMessage);\n }\n\n /**\n * Marks the instance as complete and calculates execution time.\n */\n markAsComplete() {\n this.timing.complete_time = new Date();\n this.status = State.get('statuses')[this.base_type].COMPLETE;\n this.timing.execution_time_ms = this.timing.complete_time - this.timing.start_time;\n\n if (this.steps_by_id) {\n delete this.steps_by_id;\n }\n\n this.log(\n State.get(`event_names.${this.base_type}`)[`${this.base_type.toUpperCase()}_COMPLETE`],\n `${this.base_type.charAt(0).toUpperCase() + this.base_type.slice(1)} \"${this.name}\" complete.`\n );\n }\n\n /**\n * Marks the instance as failed and calculates execution time.\n */\n markAsFailed() {\n this.timing.complete_time = new Date();\n this.status = State.get('statuses')[this.base_type].FAILED;\n this.timing.execution_time_ms = this.timing.complete_time - this.timing.start_time;\n\n this.log(\n State.get(`event_names.${this.base_type}`)[`${this.base_type.toUpperCase()}_FAILED`],\n `${this.base_type.charAt(0).toUpperCase() + this.base_type.slice(1)} \"${this.name}\" failed.`\n );\n }\n\n /**\n * Marks the instance as waiting. To be implemented by subclasses.\n */\n markAsWaiting() { }\n\n /**\n * Marks the instance as pending. To be implemented by subclasses.\n */\n markAsPending() { }\n\n /**\n * Marks the instance as running and sets the start time.\n */\n markAsRunning() {\n this.timing.start_time = this.timing.start_time ?? new Date();\n this.status = State.get('statuses')[this.base_type].RUNNING;\n\n this.log(\n State.get(`event_names.${this.base_type}`)[`${this.base_type.toUpperCase()}_RUNNING`],\n `${this.base_type.charAt(0).toUpperCase() + this.base_type.slice(1)} \"${this.name}\" started.`\n );\n }\n\n // State management methods\n /**\n * Gets a value from the global state.\n * @param {string} path - Path to the state property.\n * @returns {*} The state value at the specified path.\n */\n getState(path) {\n return State.get(path);\n }\n\n /**\n * Sets a value in the global state.\n * @param {string} path - Path to the state property.\n * @param {*} value - Value to set.\n */\n setState(path, value) {\n State.set(path, value);\n }\n\n /**\n * Deletes a property from the global state.\n * @param {string} path - Path to the state property to delete.\n */\n deleteState(path) {\n State.delete(path);\n }\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAOA,MAAY,SACnB,OAAS,cAAAC,MAAkB,oBAC3B,OAAOC,MAAW,aAOlB,MAAOC,CAAmB,CAT1B,MAS0B,CAAAC,EAAA,aAOxB,YAAY,CAAE,KAAAC,EAAM,UAAAC,EAAYL,EAAW,IAAK,EAAG,CACjD,KAAK,GAAKD,EAAO,WAAW,EAC5B,KAAK,KAAOK,GAAQ,GAAGC,CAAS,IAAI,KAAK,EAAE,GAE3C,KAAK,UAAYA,EACjB,KAAK,OAAS,CACZ,YAAa,KACb,cAAe,KACf,kBAAmB,KACnB,WAAY,IACd,CACF,CAOA,MAAM,SAAU,CACd,MAAM,IAAI,MAAM,gCAAgC,CAClD,CAQA,IAAIC,EAAYC,EAAU,KAAM,CAC9B,GAAI,CAACD,GAAc,CAACL,EAAM,IAAI,UAAU,KAAK,SAAS,EAAE,EACtD,MAAM,IAAI,MAAM,+CAA+C,EAIjE,GADAA,EAAM,IAAI,UAAU,KAAK,SAAS,EAAE,EAAE,KAAKK,EAAY,IAAI,EACvDL,EAAM,IAAI,cAAc,EAC1B,OAGF,MAAMO,EAAaD,EAAU;AAAA,GAAM,KAAK,UAAU,YAAY,CAAC,MAAM,KAAK,IAAI,KAAKA,CAAO,GAAK;AAAA,GAAM,KAAK,UAAU,YAAY,CAAC,MAAM,KAAK,IAAI,YAAYD,CAAU,GAChKG,EAAUH,EAAW,SAAS,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AAM,IAAIS,CAAI,CACvB,CAOA,SAASA,EAAMC,EAAO,CACpBV,EAAM,IAAIS,EAAMC,CAAK,CACvB,CAMA,YAAYD,EAAM,CAChBT,EAAM,OAAOS,CAAI,CACnB,CACF",
|
|
6
|
+
"names": ["crypto", "base_types", "State", "Base", "__name", "name", "base_type", "event_name", "message", "logMessage", "logType", "path", "value"]
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/classes/steps/logic_step.js"],
|
|
4
|
-
"sourcesContent": ["import Step from './step.js';\nimport { conditional_step_comparators, step_types } from '../../enums/index.js';\n\n/**\n * LogicStep class for conditional logic operations.\n * @class LogicStep\n * @extends Step\n */\nexport default class LogicStep extends Step {\n static step_name = 'logic';\n\n /**\n * Creates a new LogicStep instance.\n * @param {Object} options - Configuration options.\n * @param {string} [options.name] - Name of the step.\n * @param {Object} [options.conditional] - Conditional configuration.\n * @param {*} [options.conditional.subject] - Subject to evaluate.\n * @param {conditional_step_comparators|string} [options.conditional.operator] - Comparison operator.\n * @param {*} [options.conditional.value] - Value to compare against.\n * @param {Function} [options.callable=async () => {}] - Function to execute.\n */\n constructor({\n name,\n callable = async () => {},\n conditional = {\n operator: null,\n subject: null,\n value: null,\n },\n }) {\n super({\n name,\n base_type: step_types.LOGIC,\n callable\n });\n\n this.setConditional(conditional);\n }\n\n /**\n * Evaluates the conditional expression.\n * @returns {boolean} True if the condition is met.\n * @throws {Error} Throws if operator is unknown.\n */\n checkCondition() {\n const subject = this.conditional.subject;\n const operator = this.conditional.operator;\n const value = this.conditional.value;\n\n switch (operator) {\n case this.getState('conditional_step_comparators.STRICT_EQUALS'):\n case this.getState('conditional_step_comparators.SIGN_STRICT_EQUALS'):\n return subject === value;\n case this.getState('conditional_step_comparators.SIGN_EQUALS'):\n case this.getState('conditional_step_comparators.EQUALS'):\n return subject == value;\n case this.getState('conditional_step_comparators.NOT_EQUALS'):\n case this.getState('conditional_step_comparators.SIGN_NOT_EQUALS'):\n return subject != value;\n case this.getState('conditional_step_comparators.STRICT_NOT_EQUALS'):\n case this.getState('conditional_step_comparators.SIGN_STRICT_NOT_EQUALS'):\n return subject !== value;\n case this.getState('conditional_step_comparators.GREATER_THAN'):\n case this.getState('conditional_step_comparators.SIGN_GREATER_THAN'):\n return subject > value;\n case this.getState('conditional_step_comparators.LESS_THAN'):\n case this.getState('conditional_step_comparators.SIGN_LESS_THAN'):\n return subject < value;\n case this.getState('conditional_step_comparators.GREATER_THAN_OR_EQUAL'):\n case this.getState('conditional_step_comparators.SIGN_GREATER_THAN_OR_EQUAL'):\n return subject >= value;\n case this.getState('conditional_step_comparators.LESS_THAN_OR_EQUAL'):\n case this.getState('conditional_step_comparators.SIGN_LESS_THAN_OR_EQUAL'):\n return subject <= value;\n case this.getState('conditional_step_comparators.STRING_CONTAINS'):\n case this.getState('conditional_step_comparators.STRING_INCLUDES'):\n case this.getState('conditional_step_comparators.ARRAY_CONTAINS'):\n case this.getState('conditional_step_comparators.ARRAY_INCLUDES'):\n case this.getState('conditional_step_comparators.IN'):\n return (Array.isArray(subject) || typeof subject === 'string') && subject.includes(value);\n case this.getState('conditional_step_comparators.STRING_NOT_CONTAINS'):\n case this.getState('conditional_step_comparators.STRING_NOT_INCLUDES'):\n case this.getState('conditional_step_comparators.ARRAY_NOT_CONTAINS'):\n case this.getState('conditional_step_comparators.ARRAY_NOT_INCLUDES'):\n case this.getState('conditional_step_comparators.NOT_IN'):\n return (Array.isArray(subject) || typeof subject === 'string') && !subject.includes(value);\n case this.getState('conditional_step_comparators.EMPTY'):\n return subject === '' || subject === null || subject === undefined || subject.length === 0;\n case this.getState('conditional_step_comparators.NOT_EMPTY'):\n return subject !== '' && subject !== null && subject !== undefined && subject.length > 0;\n case this.getState('conditional_step_comparators.REGEX_MATCH'):\n if (typeof value !== 'string') {\n throw new Error(`Regex input must be a string.`);\n }\n const regex = new RegExp(value);\n return regex.test(subject);\n case this.getState('conditional_step_comparators.REGEX_NOT_MATCH'):\n if (typeof value !== 'string') {\n throw new Error(`Regex input must be a string.`);\n }\n const notMatchRegex = new RegExp(value);\n return !notMatchRegex.test(subject);\n case this.getState('conditional_step_comparators.STRING_STARTS_WITH'):\n return typeof subject === 'string' && typeof value === 'string' && subject.startsWith(value);\n case this.getState('conditional_step_comparators.STRING_ENDS_WITH'):\n return typeof subject === 'string' && typeof value === 'string' && subject.endsWith(value);\n case this.getState('conditional_step_comparators.NULLISH'):\n return subject === null || subject === undefined;\n case this.getState('conditional_step_comparators.NOT_NULLISH'):\n return subject !== null && subject !== undefined;\n case this.getState('conditional_step_comparators.IS_TYPE'):\n return typeof subject === value;\n case this.getState('conditional_step_comparators.IS_NOT_TYPE'):\n return typeof subject !== value;\n case this.getState('conditional_step_comparators.CUSTOM_FUNCTION'):\n if (typeof value !== 'function') {\n throw new Error(`Invalid custom function: ${value}`);\n }\n return value(subject);\n default:\n throw new Error(`Unknown operator: ${operator}`);\n }\n }\n\n /**\n * Checks if the conditional configuration is valid.\n * @returns {boolean} True if conditional is valid.\n */\n conditionalIsValid() {\n return (\n this.conditional.subject !== null &&\n this.conditional.subject !== undefined &&\n this.conditional.operator !== null &&\n this.conditional.operator !== undefined &&\n this.conditional.value !== null &&\n this.conditional.value !== undefined\n );\n }\n\n /**\n * Sets the conditional properties.\n * @param {Object} conditional - Conditional configuration object.\n */\n setConditional(conditional) {\n this.conditional = { subject: conditional.subject, operator: conditional.operator, value: conditional.value };\n }\n}\n"],
|
|
5
|
-
"mappings": "+EAAA,OAAOA,MAAU,YACjB,OAAuC,cAAAC,MAAkB,uBAOzD,MAAOC,UAAgCF,CAAK,CAR5C,MAQ4C,CAAAG,EAAA,kBAC1C,OAAO,UAAY,QAYnB,YAAY,CACV,KAAAC,EACA,SAAAC,EAAWF,EAAA,SAAY,CAAC,EAAb,YACX,YAAAG,EAAc,CACZ,SAAU,KACV,QAAS,KACT,MAAO,IACT,CACF,EAAG,CACD,MA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IAAI,MAAM,qBAAqBC,CAAQ,EAAE,CACnD,CACF,CAMA,oBAAqB,
|
|
4
|
+
"sourcesContent": ["import Step from './step.js';\nimport { conditional_step_comparators, step_types } from '../../enums/index.js';\n\n/**\n * LogicStep class for conditional logic operations.\n * @class LogicStep\n * @extends Step\n */\nexport default class LogicStep extends Step {\n static step_name = 'logic';\n\n /**\n * Creates a new LogicStep instance.\n * @param {Object} options - Configuration options.\n * @param {string} [options.name] - Name of the step.\n * @param {Object} [options.conditional] - Conditional configuration.\n * @param {*} [options.conditional.subject] - Subject to evaluate.\n * @param {conditional_step_comparators|string} [options.conditional.operator] - Comparison operator.\n * @param {*} [options.conditional.value] - Value to compare against.\n * @param {Function} [options.callable=async () => {}] - Function to execute.\n */\n constructor({\n name,\n callable = async () => {},\n conditional = {\n operator: null,\n subject: null,\n value: null,\n },\n }) {\n super({\n name,\n base_type: step_types.LOGIC,\n callable\n });\n\n this.setConditional(conditional);\n }\n\n /**\n * Evaluates the conditional expression.\n * @returns {boolean} True if the condition is met.\n * @throws {Error} Throws if operator is unknown.\n */\n checkCondition() {\n const subject = this.conditional.subject;\n const operator = this.conditional.operator;\n const value = this.conditional.value;\n\n switch (operator) {\n case this.getState('conditional_step_comparators.STRICT_EQUALS'):\n case this.getState('conditional_step_comparators.SIGN_STRICT_EQUALS'):\n return subject === value;\n case this.getState('conditional_step_comparators.SIGN_EQUALS'):\n case this.getState('conditional_step_comparators.EQUALS'):\n return subject == value;\n case this.getState('conditional_step_comparators.NOT_EQUALS'):\n case this.getState('conditional_step_comparators.SIGN_NOT_EQUALS'):\n return subject != value;\n case this.getState('conditional_step_comparators.STRICT_NOT_EQUALS'):\n case this.getState('conditional_step_comparators.SIGN_STRICT_NOT_EQUALS'):\n return subject !== value;\n case this.getState('conditional_step_comparators.GREATER_THAN'):\n case this.getState('conditional_step_comparators.SIGN_GREATER_THAN'):\n return subject > value;\n case this.getState('conditional_step_comparators.LESS_THAN'):\n case this.getState('conditional_step_comparators.SIGN_LESS_THAN'):\n return subject < value;\n case this.getState('conditional_step_comparators.GREATER_THAN_OR_EQUAL'):\n case this.getState('conditional_step_comparators.SIGN_GREATER_THAN_OR_EQUAL'):\n return subject >= value;\n case this.getState('conditional_step_comparators.LESS_THAN_OR_EQUAL'):\n case this.getState('conditional_step_comparators.SIGN_LESS_THAN_OR_EQUAL'):\n return subject <= value;\n case this.getState('conditional_step_comparators.STRING_CONTAINS'):\n case this.getState('conditional_step_comparators.STRING_INCLUDES'):\n case this.getState('conditional_step_comparators.ARRAY_CONTAINS'):\n case this.getState('conditional_step_comparators.ARRAY_INCLUDES'):\n case this.getState('conditional_step_comparators.IN'):\n return (Array.isArray(subject) || typeof subject === 'string') && subject.includes(value);\n case this.getState('conditional_step_comparators.STRING_NOT_CONTAINS'):\n case this.getState('conditional_step_comparators.STRING_NOT_INCLUDES'):\n case this.getState('conditional_step_comparators.ARRAY_NOT_CONTAINS'):\n case this.getState('conditional_step_comparators.ARRAY_NOT_INCLUDES'):\n case this.getState('conditional_step_comparators.NOT_IN'):\n return (Array.isArray(subject) || typeof subject === 'string') && !subject.includes(value);\n case this.getState('conditional_step_comparators.EMPTY'):\n return subject === '' || subject === null || subject === undefined || subject.length === 0;\n case this.getState('conditional_step_comparators.NOT_EMPTY'):\n return subject !== '' && subject !== null && subject !== undefined && subject.length > 0;\n case this.getState('conditional_step_comparators.REGEX_MATCH'):\n if (typeof value !== 'string') {\n throw new Error(`Regex input must be a string.`);\n }\n const regex = new RegExp(value);\n return regex.test(subject);\n case this.getState('conditional_step_comparators.REGEX_NOT_MATCH'):\n if (typeof value !== 'string') {\n throw new Error(`Regex input must be a string.`);\n }\n const notMatchRegex = new RegExp(value);\n return !notMatchRegex.test(subject);\n case this.getState('conditional_step_comparators.STRING_STARTS_WITH'):\n return typeof subject === 'string' && typeof value === 'string' && subject.startsWith(value);\n case this.getState('conditional_step_comparators.STRING_ENDS_WITH'):\n return typeof subject === 'string' && typeof value === 'string' && subject.endsWith(value);\n case this.getState('conditional_step_comparators.NULLISH'):\n return subject === null || subject === undefined;\n case this.getState('conditional_step_comparators.NOT_NULLISH'):\n return subject !== null && subject !== undefined;\n case this.getState('conditional_step_comparators.IS_TYPE'):\n return typeof subject === value;\n case this.getState('conditional_step_comparators.IS_NOT_TYPE'):\n return typeof subject !== value;\n case this.getState('conditional_step_comparators.CUSTOM_FUNCTION'):\n if (typeof value !== 'function') {\n throw new Error(`Invalid custom function: ${value}`);\n }\n return value(subject);\n default:\n throw new Error(`Unknown operator: ${operator}`);\n }\n }\n\n /**\n * Checks if the conditional configuration is valid.\n * @returns {boolean} True if conditional is valid.\n */\n conditionalIsValid() {\n // Check if all conditional properties are set (not null or undefined)\n // Can't use falsy check here because valid values could be falsy (e.g. empty string, 0, false)\n return (\n this.conditional.subject !== null &&\n this.conditional.subject !== undefined &&\n this.conditional.operator !== null &&\n this.conditional.operator !== undefined &&\n this.conditional.value !== null &&\n this.conditional.value !== undefined\n );\n }\n\n /**\n * Sets the conditional properties.\n * @param {Object} conditional - Conditional configuration object.\n */\n setConditional(conditional) {\n this.conditional = { subject: conditional.subject, operator: conditional.operator, value: conditional.value };\n }\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAOA,MAAU,YACjB,OAAuC,cAAAC,MAAkB,uBAOzD,MAAOC,UAAgCF,CAAK,CAR5C,MAQ4C,CAAAG,EAAA,kBAC1C,OAAO,UAAY,QAYnB,YAAY,CACV,KAAAC,EACA,SAAAC,EAAWF,EAAA,SAAY,CAAC,EAAb,YACX,YAAAG,EAAc,CACZ,SAAU,KACV,QAAS,KACT,MAAO,IACT,CACF,EAAG,CACD,MAAM,CACJ,KAAAF,EACA,UAAWH,EAAW,MACtB,SAAAI,CACF,CAAC,EAED,KAAK,eAAeC,CAAW,CACjC,CAOA,gBAAiB,CACf,MAAMC,EAAU,KAAK,YAAY,QAC3BC,EAAW,KAAK,YAAY,SAC5BC,EAAQ,KAAK,YAAY,MAE/B,OAAQD,EAAU,CAChB,KAAK,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/B,CAMA,eAAeF,EAAa,CAC1B,KAAK,YAAc,CAAE,QAASA,EAAY,QAAS,SAAUA,EAAY,SAAU,MAAOA,EAAY,KAAM,CAC9G,CACF",
|
|
6
6
|
"names": ["Step", "step_types", "LogicStep", "__name", "name", "callable", "conditional", "subject", "operator", "value"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var l=Object.defineProperty;var i=(h,t)=>l(h,"name",{value:t,configurable:!0});import u from"../base.js";import"../workflow.js";import{base_types as o,step_types as p}from"../../enums/index.js";class _ extends u{static{i(this,"Step")}static step_name="step";#t=null;constructor({name:t,callable:s=i(async()=>{},"callable"),max_retries:e=0,max_timeout_ms:r=3e4,step_type:n=p.ACTION,sub_step_type:a=null}){super({name:t,base_type:o.STEP}),this.callable=s,this.#t=s,this.max_retries=e,this.retry_count=0,this.max_timeout_ms=r,this.step_type=n,this.sub_step_type=a,this.errors=[],this.result=null,this.retry_results=[],this.timeout=null}async execute(){this.timeout||(this.timeout=new Promise((e,r)=>setTimeout(r,this.max_timeout_ms,new Error(`Step "${this.name}" timed out after ${this.max_timeout_ms}ms`)))),this.markAsRunning();try{this.result=await Promise.race([this._callable(),this.timeout])}catch(e){if(this.max_retries&&this.retry_count<this.max_retries)this.retry_count++,this.retry_results.push({retry_count:this.retry_count,result:await this.execute()});else if(this.errors.push(e),this.markAsFailed(),this.getState("exit_on_error"))throw e}const{FAILED:t,COMPLETE:s}=this.getState("statuses")[this.base_type];return[t,s].includes(this.status)||this.markAsComplete(),["step","workflow"].includes(this.callable_type)?this.#t:this}getCallableType(t){if(t&&t.base_type===o.WORKFLOW)return"workflow";if(t&&t.base_type===o.STEP)return"step";if(typeof t=="function")return"function";throw new Error("Invalid callable type. Must be one of function, Step, or Workflow.")}setParentWorkflowValue(t,s,e){const r=this.getState("workflows")[t];if(!r)throw new Error(`Parent workflow with ID ${t} not found.`);r[s]=e}set callable(t){this.callable_type=this.getCallableType(t),["step","workflow"].includes(this.callable_type)?(this.callable_type==="step"&&(t.parentWorkflowId=this.parentWorkflowId??null),this._callable=t.execute.bind(t)):this._callable=t.bind(this)}}export{_ as default};
|
|
2
2
|
//# sourceMappingURL=step.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/classes/steps/step.js"],
|
|
4
|
-
"sourcesContent": ["import Base from '../base.js';\nimport Workflow from '../workflow.js';\nimport { base_types, step_types } from '../../enums/index.js';\n\n/**\n * Step class representing an executable unit within a workflow.\n * @class Step\n * @extends Base\n */\nexport default class Step extends Base {\n static step_name = 'step';\n #callable_object = null;\n\n /**\n * Creates a new Step instance.\n * @param {Object} options - Configuration options.\n * @param {string} [options.name] - Name of the step.\n * @param {Function|Step|Workflow} [options.callable=async () => {}] - Function, Step, or Workflow to execute.\n * @param {number} [options.max_retries=0] - Maximum number of retries on failure.\n * @param {number} [options.max_timeout_ms=30000] - Maximum execution time in milliseconds before timing out.\n * @param {string} [options.step_type=step_types.ACTION] - Type of the step.\n * @param {sub_step_types|null} [options.sub_step_type=null] - Sub-type of the step (use values from the sub_step_types enum).\n */\n constructor({\n name,\n callable = async () => {},\n max_retries = 0,\n max_timeout_ms = 30000,\n step_type = step_types.ACTION,\n sub_step_type = null,\n }) {\n super({ name, base_type: base_types.STEP });\n\n this.callable = callable;\n\n // Store off the original callable object, because if it's a Step or Workflow,\n // this.callable is set to the execute method of that object, but we may need to access its properties later.\n this.#callable_object = callable;\n\n this.max_retries = max_retries;\n this.retry_count = 0;\n this.max_timeout_ms = max_timeout_ms;\n this.step_type = step_type;\n this.sub_step_type = sub_step_type;\n\n this.errors = [];\n this.result = null;\n this.retry_results = [];\n this.timeout = null;\n
|
|
5
|
-
"mappings": "+EAAA,OAAOA,MAAU,aACjB,MAAqB,iBACrB,OAAS,cAAAC,EAAY,cAAAC,MAAkB,uBAOvC,MAAOC,UAA2BH,CAAK,CATvC,MASuC,CAAAI,EAAA,aACrC,OAAO,UAAY,OACnBC,GAAmB,KAYnB,YAAY,CACV,KAAAC,EACA,SAAAC,EAAWH,EAAA,SAAY,CAAC,EAAb,YACX,YAAAI,EAAc,EACd,eAAAC,EAAiB,IACjB,UAAAC,EAAYR,EAAW,OACvB,cAAAS,EAAgB,IAClB,EAAG,CACD,MAAM,CAAE,KAAAL,EAAM,UAAWL,EAAW,IAAK,CAAC,EAE1C,KAAK,SAAWM,EAIhB,KAAKF,GAAmBE,EAExB,KAAK,YAAcC,EACnB,KAAK,YAAc,EACnB,KAAK,eAAiBC,EACtB,KAAK,UAAYC,EACjB,KAAK,cAAgBC,EAErB,KAAK,OAAS,CAAC,EACf,KAAK,OAAS,KACd,KAAK,cAAgB,CAAC,EACtB,KAAK,QAAU,
|
|
4
|
+
"sourcesContent": ["import Base from '../base.js';\nimport Workflow from '../workflow.js';\nimport { base_types, step_types } from '../../enums/index.js';\n\n/**\n * Step class representing an executable unit within a workflow.\n * @class Step\n * @extends Base\n */\nexport default class Step extends Base {\n static step_name = 'step';\n #callable_object = null;\n\n /**\n * Creates a new Step instance.\n * @param {Object} options - Configuration options.\n * @param {string} [options.name] - Name of the step.\n * @param {Function|Step|Workflow} [options.callable=async () => {}] - Function, Step, or Workflow to execute.\n * @param {number} [options.max_retries=0] - Maximum number of retries on failure.\n * @param {number} [options.max_timeout_ms=30000] - Maximum execution time in milliseconds before timing out.\n * @param {string} [options.step_type=step_types.ACTION] - Type of the step.\n * @param {sub_step_types|null} [options.sub_step_type=null] - Sub-type of the step (use values from the sub_step_types enum).\n */\n constructor({\n name,\n callable = async () => {},\n max_retries = 0,\n max_timeout_ms = 30000,\n step_type = step_types.ACTION,\n sub_step_type = null,\n }) {\n super({ name, base_type: base_types.STEP });\n\n this.callable = callable;\n\n // Store off the original callable object, because if it's a Step or Workflow,\n // this.callable is set to the execute method of that object, but we may need to access its properties later.\n this.#callable_object = callable;\n\n this.max_retries = max_retries;\n this.retry_count = 0;\n this.max_timeout_ms = max_timeout_ms;\n this.step_type = step_type;\n this.sub_step_type = sub_step_type;\n\n this.errors = [];\n this.result = null;\n this.retry_results = [];\n this.timeout = null;\n }\n\n /**\n * Executes the step's callable function, Step, or Workflow.\n * @async\n * @returns {Promise<Step>} The step instance with execution results.\n */\n async execute() {\n if (!this.timeout ) {\n this.timeout = new Promise((_, reject) =>\n setTimeout(reject, this.max_timeout_ms, new Error(`Step \"${this.name}\" timed out after ${this.max_timeout_ms}ms`))\n );\n }\n\n this.markAsRunning();\n\n try {\n this.result = await Promise.race([this._callable(), this.timeout]);\n } catch (error) {\n if (this.max_retries && this.retry_count < this.max_retries) {\n this.retry_count++;\n this.retry_results.push({\n retry_count: this.retry_count,\n result: await this.execute(),\n });\n } else {\n this.errors.push(error);\n\n this.markAsFailed();\n\n if (this.getState('exit_on_error')) {\n throw error;\n }\n }\n\n }\n\n const { FAILED, COMPLETE } = this.getState('statuses')[this.base_type];\n\n if (! [FAILED, COMPLETE].includes(this.status)) {\n this.markAsComplete();\n }\n\n if (['step', 'workflow'].includes(this.callable_type)) {\n return this.#callable_object;\n }\n\n return this;\n }\n\n /**\n * Determines the type of the callable (function, step, or workflow).\n * @param {Function|Step|Workflow} callable - The callable to check.\n * @returns {string} The type: 'function', 'step', or 'workflow'.\n * @throws {Error} Throws if callable type is invalid.\n */\n getCallableType(callable) {\n if (callable && callable.base_type === base_types.WORKFLOW) {\n return 'workflow';\n } else if (callable && callable.base_type === base_types.STEP) {\n return 'step';\n } else if (typeof callable === 'function') {\n return 'function';\n } \n\n throw new Error('Invalid callable type. Must be one of function, Step, or Workflow.');\n }\n\n /**\n * Sets a value in the parent workflow's state.\n * @param {string} workflowId - ID of the parent workflow.\n * @param {string} path - Path in the workflow state to set.\n * @param {*} value - Value to set at the specified path.\n * @throws {Error} Throws if parent workflow is not found.\n */\n setParentWorkflowValue(workflowId, path, value) {\n const parentWorkflow = this.getState('workflows')[workflowId];\n\n if (!parentWorkflow) {\n throw new Error(`Parent workflow with ID ${workflowId} not found.`);\n }\n\n parentWorkflow[path] = value;\n }\n\n /**\n * Sets the callable for the step and determines its type.\n * @param {Function|Step|Workflow} callable - The callable to set.\n */\n set callable(callable) {\n this.callable_type = this.getCallableType(callable);\n\n if (['step', 'workflow'].includes(this.callable_type)) {\n if (this.callable_type === 'step') {\n callable.parentWorkflowId = this.parentWorkflowId ?? null;\n }\n\n this._callable = callable.execute.bind(callable);\n } else {\n this._callable = callable.bind(this);\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAOA,MAAU,aACjB,MAAqB,iBACrB,OAAS,cAAAC,EAAY,cAAAC,MAAkB,uBAOvC,MAAOC,UAA2BH,CAAK,CATvC,MASuC,CAAAI,EAAA,aACrC,OAAO,UAAY,OACnBC,GAAmB,KAYnB,YAAY,CACV,KAAAC,EACA,SAAAC,EAAWH,EAAA,SAAY,CAAC,EAAb,YACX,YAAAI,EAAc,EACd,eAAAC,EAAiB,IACjB,UAAAC,EAAYR,EAAW,OACvB,cAAAS,EAAgB,IAClB,EAAG,CACD,MAAM,CAAE,KAAAL,EAAM,UAAWL,EAAW,IAAK,CAAC,EAE1C,KAAK,SAAWM,EAIhB,KAAKF,GAAmBE,EAExB,KAAK,YAAcC,EACnB,KAAK,YAAc,EACnB,KAAK,eAAiBC,EACtB,KAAK,UAAYC,EACjB,KAAK,cAAgBC,EAErB,KAAK,OAAS,CAAC,EACf,KAAK,OAAS,KACd,KAAK,cAAgB,CAAC,EACtB,KAAK,QAAU,IACjB,CAOA,MAAM,SAAU,CACT,KAAK,UACR,KAAK,QAAU,IAAI,QAAQ,CAACC,EAAGC,IAC7B,WAAWA,EAAQ,KAAK,eAAgB,IAAI,MAAM,SAAS,KAAK,IAAI,qBAAqB,KAAK,cAAc,IAAI,CAAC,CACnH,GAGF,KAAK,cAAc,EAEnB,GAAI,CACF,KAAK,OAAS,MAAM,QAAQ,KAAK,CAAC,KAAK,UAAU,EAAG,KAAK,OAAO,CAAC,CACnE,OAASC,EAAO,CACd,GAAI,KAAK,aAAe,KAAK,YAAc,KAAK,YAC9C,KAAK,cACL,KAAK,cAAc,KAAK,CACtB,YAAa,KAAK,YAClB,OAAQ,MAAM,KAAK,QAAQ,CAC7B,CAAC,UAED,KAAK,OAAO,KAAKA,CAAK,EAEtB,KAAK,aAAa,EAEd,KAAK,SAAS,eAAe,EAC/B,MAAMA,CAIZ,CAEA,KAAM,CAAE,OAAAC,EAAQ,SAAAC,CAAS,EAAI,KAAK,SAAS,UAAU,EAAE,KAAK,SAAS,EAMrE,MAJM,CAACD,EAAQC,CAAQ,EAAE,SAAS,KAAK,MAAM,GAC3C,KAAK,eAAe,EAGlB,CAAC,OAAQ,UAAU,EAAE,SAAS,KAAK,aAAa,EAC3C,KAAKX,GAGP,IACT,CAQA,gBAAgBE,EAAU,CACxB,GAAIA,GAAYA,EAAS,YAAcN,EAAW,SAChD,MAAO,WACF,GAAIM,GAAYA,EAAS,YAAcN,EAAW,KACvD,MAAO,OACF,GAAI,OAAOM,GAAa,WAC7B,MAAO,WAGT,MAAM,IAAI,MAAM,oEAAoE,CACtF,CASA,uBAAuBU,EAAYC,EAAMC,EAAO,CAC9C,MAAMC,EAAiB,KAAK,SAAS,WAAW,EAAEH,CAAU,EAE5D,GAAI,CAACG,EACH,MAAM,IAAI,MAAM,2BAA2BH,CAAU,aAAa,EAGpEG,EAAeF,CAAI,EAAIC,CACzB,CAMA,IAAI,SAASZ,EAAU,CACrB,KAAK,cAAgB,KAAK,gBAAgBA,CAAQ,EAE9C,CAAC,OAAQ,UAAU,EAAE,SAAS,KAAK,aAAa,GAC9C,KAAK,gBAAkB,SACzBA,EAAS,iBAAmB,KAAK,kBAAoB,MAGvD,KAAK,UAAYA,EAAS,QAAQ,KAAKA,CAAQ,GAE/C,KAAK,UAAYA,EAAS,KAAK,IAAI,CAEvC,CACF",
|
|
6
6
|
"names": ["Base", "base_types", "step_types", "Step", "__name", "#callable_object", "name", "callable", "max_retries", "max_timeout_ms", "step_type", "sub_step_type", "_", "reject", "error", "FAILED", "COMPLETE", "workflowId", "path", "value", "parentWorkflow"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var o=Object.defineProperty;var r=(i,t)=>o(i,"name",{value:t,configurable:!0});import a from"./base.js";import{base_types as
|
|
1
|
+
var o=Object.defineProperty;var r=(i,t)=>o(i,"name",{value:t,configurable:!0});import a from"crypto";import n from"./base.js";import{base_types as p}from"../enums/index.js";class _ extends n{static{r(this,"Workflow")}constructor({name:t,exit_on_error:s=!1,steps:e=[],throw_on_empty:h=!1}){super({name:t,base_type:p.WORKFLOW}),this.initializeWorkflowState(),this.addSteps(e),this.exit_on_error=s,this.throw_on_empty=h,this.sessions={},this.current_session_id=null}async execute(){if(this.current_session_id||(this.current_session_id=a.randomUUID()),this.isEmpty()){if(this.throw_on_empty)throw new Error("Cannot execute an empty workflow");return this.markAsComplete(),this.prepareResult("Workflow is empty",null),this}this.markAsRunning();for(let t=0;t<this._steps.length;t++){if(this.should_break){this.log(this.getState("event_names.workflow").WORKFLOW_BREAK_EXECUTED,`Workflow "${this.name}" execution broken at step ${this._steps[t].name} - ${this._steps[t].id}.`);break}if(this.should_skip){this.log(this.getState("events.workflow.event_names.WORKFLOW_STEP_SKIPPED"),`Workflow "${this.name}" skipping step ${this._steps[t].name} - ${this._steps[t].id}.`),this.should_skip=!1;continue}this.current_step=this._steps[t].id;try{const s=await this.step();this.prepareResult("Success",s)}catch(s){if(this.markAsFailed(),this.prepareResult(`Workflow execution failed at step ${this.steps_by_id[this.current_step].name} - ${this.current_step}`,{error:s}),this.exit_on_error)return this}if(this.should_pause)return this.markAsPaused(),this.should_pause=!1,this}return this.markAsComplete(),this}async resume(){return this.should_pause=!1,this.timing.resume_time=new Date,this.getState("events.workflow").emit(this.getState("event_names.workflow").WORKFLOW_RESUMED,this.getState()),this.execute()}async step(){const t=this.steps_by_id[this.current_step];t.parentWorkflowId=this.id;const s=await t.execute();if(t.status===this.getState("statuses.step.FAILED"))throw t.errors[t.errors.length-1]??new Error(`Step "${t.name}" failed`);return s}addStep(t){if(typeof t.getCallableType!="function")throw new Error("Invalid step type. Must be an instance of Step.");Array.isArray(this._steps)||(this._steps=[]),(!this.steps_by_id||typeof this.steps_by_id!="object")&&(this.steps_by_id={}),this.steps_by_id[t.id]=t,t.parentWorkflowId=this.id,this._steps.push(t)}addStepAtIndex(t,s){(!this.steps_by_id||typeof this.steps_by_id!="object")&&(this.steps_by_id={}),this.steps_by_id[t.id]=t,t.parentWorkflowId=this.id,this._steps.splice(s,0,t)}addSteps(t){t.forEach(s=>this.addStep(s))}clearSteps(){this._steps=[]}closeCurrentSession(){this.current_session_id&&(this.sessions[this.current_session_id]={results:[...this.results],status:this.status,timing:{...this.timing},closed_at:new Date},this.current_session_id=null)}deleteStep(t){this._steps=this._steps.filter(s=>s.id!==t)}deleteStepByIndex(t){this._steps.splice(t,1)}initializeWorkflowState(){this.results=[],this.exit_on_error=!1,this.current_step=null,this.should_break=!1,this.should_continue=!1,this.should_pause=!1,this.should_skip=!1,this.status=this.getState("statuses.workflow").CREATED,this._steps=[],this.throw_on_empty=this.throw_on_empty,this.timing={...this.timing,create_time:new Date,pause_time:null,resume_time:null};const t=this.getState("workflows");t[this.id]=this,this.setState("workflows",t),this.log(this.getState("event_names.workflow").WORKFLOW_CREATED,`Workflow "${this.name}" initialized.`)}isEmpty(){return!this._steps||!this._steps.length}markAsComplete(){super.markAsComplete(),this.closeCurrentSession()}markAsCreated(){return this.timing.create_time=new Date,this.log(this.getState("event_names.workflow").WORKFLOW_CREATED,`Workflow "${this.name}" created.`),this.getState("statuses.workflow").CREATED}markAsFailed(){super.markAsFailed(),this.closeCurrentSession()}markAsPaused(){this.timing.pause_time=new Date,this.status=this.getState("statuses.workflow").PAUSED,this.getState("events.workflow").emit(this.getState("event_names.workflow").WORKFLOW_PAUSED,this.getState())}markAsResumed(){this.timing.resume_time=new Date,this.status=this.getState("statuses.workflow").RUNNING,this.getState("events.workflow").emit(this.getState("event_names.workflow").WORKFLOW_RESUMED,this.getState())}moveStep(t,s){const[e]=this._steps.splice(t,1);this._steps.splice(s,0,e),this.getState("events.workflow").emit(this.getState("event_names.workflow").WORKFLOW_STEP_MOVED,this.getState())}pause(){this.should_pause=!0,this.timing.pause_time=new Date,this.getState("events.workflow").emit(this.getState("event_names.workflow").WORKFLOW_PAUSED,this.getState())}popStep(){return this._steps.pop()}prepareResult(t,s){this.results.push({message:t,data:s})}pushStep(t){this.addStep(t)}pushSteps(t){t.forEach(s=>this.addStep(s))}shiftStep(){return this._steps.shift()}unshiftStep(t){if(typeof t.getCallableType!="function")throw new Error("Invalid step type. Must be an instance of Step.");(!this.steps_by_id||typeof this.steps_by_id!="object")&&(this.steps_by_id={}),this.steps_by_id[t.id]=t,t.parentWorkflowId=this.id,this._steps.unshift(t)}get steps(){return this._steps}set steps(t){t.forEach((s,e)=>{if(typeof s.getCallableType!="function")throw new Error(`Invalid step type. Step at index ${e} is not an instance of Step.`)}),this.addSteps(t)}}export{_ as default};
|
|
2
2
|
//# sourceMappingURL=workflow.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/classes/workflow.js"],
|
|
4
|
-
"sourcesContent": ["import Base from './base.js';\nimport { base_types } from '../enums/index.js';\n\n/**\n * Workflow class for managing and executing a sequence of steps.\n * @class Workflow\n * @extends Base\n */\nexport default class Workflow extends Base {\n /**\n * Creates a new Workflow instance.\n * @param {Object} options - Configuration options.\n * @param {string} [options.name] - Name of the workflow.\n * @param {boolean} [options.exit_on_error=false] - Whether to exit on error.\n * @param {Array<Step>} [options.steps=[]] - Array of steps to add to the workflow.\n * @param {boolean} [options.throw_on_empty=false] - Whether to throw error if workflow is empty.\n */\n constructor({\n name,\n exit_on_error = false,\n steps = [],\n throw_on_empty = false\n }) {\n super({ name, base_type: base_types.WORKFLOW });\n\n this.initializeWorkflowState();\n\n this.addSteps(steps);\n\n this.exit_on_error = exit_on_error;\n this.throw_on_empty = throw_on_empty;\n this.sessions = {};\n this.current_session_id = null;\n }\n\n /**\n * Executes the workflow by running all steps in sequence.\n * @async\n * @returns {Promise<Workflow>} The workflow instance with execution results.\n * @throws {Error} Throws if workflow is empty and throw_on_empty is true.\n */\n async execute() {\n if (!this.current_session_id) {\n this.current_session_id = crypto.randomUUID();\n }\n\n if (this.isEmpty()) {\n if (this.throw_on_empty) {\n throw new Error('Cannot execute an empty workflow');\n }\n\n this.markAsComplete();\n this.prepareResult('Workflow is empty', null);\n return this;\n }\n \n this.markAsRunning();\n\n for (let i = 0; i < this._steps.length; i++) {\n if (this.should_break) {\n this.should_break = false;\n this.log(this.getState('event_names.workflow').WORKFLOW_BREAK_EXECUTED, `Workflow \"${this.name}\" execution broken at step ${this._steps[i].name} - ${this._steps[i].id}.`);\n break;\n }\n\n if (this.should_skip) {\n this.log(\n this.getState('events.workflow.event_names.WORKFLOW_STEP_SKIPPED'),\n `Workflow \"${this.name}\" skipping step ${this._steps[i].name} - ${this._steps[i].id}.`\n );\n this.should_skip = false;\n continue;\n }\n\n this.current_step = this._steps[i].id;\n\n try {\n const step_result = await this.step();\n this.prepareResult('Success', step_result);\n } catch (error) {\n this.markAsFailed();\n this.prepareResult(`Workflow execution failed at step ${this.steps_by_id[this.current_step].name} - ${this.current_step}`, { error });\n \n if (this.exit_on_error) {\n return this;\n }\n }\n\n if (this.should_pause) {\n this.markAsPaused();\n this.should_pause = false;\n return this;\n }\n }\n\n this.markAsComplete();\n return this;\n }\n\n /**\n * Resumes a paused workflow.\n * @async\n * @returns {Promise<Workflow>} The workflow instance.\n */\n async resume() {\n this.should_pause = false;\n this.timing.resume_time = new Date();\n\n this.getState('events.workflow').emit(\n this.getState('event_names.workflow').WORKFLOW_RESUMED,\n this.getState()\n );\n return this.execute();\n }\n\n /**\n * Executes a single step in the workflow.\n * @async\n * @returns {Promise<*>} The result of the step execution.\n */\n async step() {\n const step = this.steps_by_id[this.current_step];\n\n step.parentWorkflowId = this.id;\n const result = await step.execute();\n\n if (step.status === this.getState('statuses.step.FAILED')) {\n throw step.errors[step.errors.length - 1] ?? new Error(`Step \"${step.name}\" failed`);\n }\n\n return result;\n }\n\n /**\n * Adds a step to the workflow.\n * @param {Step} step - The step to add.\n * @throws {Error} Throws if step is not a valid Step instance.\n */\n addStep(step) {\n if (typeof step.getCallableType !== 'function') {\n throw new Error('Invalid step type. Must be an instance of Step.');\n }\n\n if (!Array.isArray(this._steps)) {\n this._steps = [];\n }\n\n if (!this.steps_by_id || typeof this.steps_by_id !== 'object') {\n this.steps_by_id = {};\n }\n\n this.steps_by_id[step.id] = step;\n\n step.parentWorkflowId = this.id;\n this._steps.push(step);\n }\n\n /**\n * Adds a step at a specific index in the workflow.\n * @param {Step} step - The step to add.\n * @param {number} index - The index at which to insert the step.\n */\n addStepAtIndex(step, index) {\n if (!this.steps_by_id || typeof this.steps_by_id !== 'object') {\n this.steps_by_id = {};\n }\n\n this.steps_by_id[step.id] = step;\n step.parentWorkflowId = this.id;\n this._steps.splice(index, 0, step);\n }\n\n /**\n * Adds multiple steps to the workflow.\n * @param {Step[]} steps - Array of steps to add.\n */\n addSteps(steps) {\n steps.forEach(step => this.addStep(step));\n }\n\n /**\n * Clears all steps from the workflow.\n */\n clearSteps() {\n this._steps = [];\n }\n\n /**\n * Closes the current session and stores a snapshot of the workflow state.\n */\n closeCurrentSession() {\n if (!this.current_session_id) {\n return;\n }\n\n this.sessions[this.current_session_id] = {\n results: [...this.results],\n status: this.status,\n timing: { ...this.timing },\n closed_at: new Date()\n };\n this.current_session_id = null;\n }\n\n /**\n * Deletes a step from the workflow by its ID.\n * @param {string} stepId - The ID of the step to delete.\n */\n deleteStep(stepId) {\n this._steps = this._steps.filter(step => step.id !== stepId);\n }\n\n /**\n * Deletes a step from the workflow by its index.\n * @param {number} index - The index of the step to delete.\n */\n deleteStepByIndex(index) {\n this._steps.splice(index, 1);\n }\n\n /**\n * Initializes the workflow state with default values.\n */\n initializeWorkflowState() {\n this.results = [];\n this.exit_on_error = false;\n this.current_step = null;\n this.should_break = false;\n this.should_continue = false;\n this.should_pause = false;\n this.should_skip = false;\n this.status = this.getState('statuses.workflow').CREATED;\n this._steps = [];\n this.throw_on_empty = this.throw_on_empty;\n this.timing = {\n ...this.timing,\n create_time: new Date(),\n pause_time: null,\n resume_time: null,\n }\n\n const workflows = this.getState('workflows');\n workflows[this.id] = this;\n this.setState('workflows', workflows);\n\n this.log(\n this.getState('event_names.workflow').WORKFLOW_CREATED,\n `Workflow \"${this.name}\" initialized.`\n );\n }\n\n /**\n * Checks if the workflow has no steps.\n * @returns {boolean} True if the workflow is empty.\n */\n isEmpty() {\n return !this._steps || !this._steps.length\n }\n\n /**\n * Marks the workflow as complete and closes the current session.\n */\n markAsComplete() {\n super.markAsComplete();\n this.closeCurrentSession();\n }\n\n /**\n * Marks the workflow as created.\n * @returns {string} The CREATED status.\n */\n markAsCreated() {\n this.timing.create_time = new Date();\n \n this.log(\n this.getState('event_names.workflow').WORKFLOW_CREATED,\n `Workflow \"${this.name}\" created.`\n );\n\n return this.getState('statuses.workflow').CREATED;\n }\n\n /**\n * Marks the workflow as failed and closes the current session.\n */\n markAsFailed() {\n super.markAsFailed();\n this.closeCurrentSession();\n }\n\n /**\n * Marks the workflow as paused.\n */\n markAsPaused() {\n this.timing.pause_time = new Date();\n this.status = this.getState('statuses.workflow').PAUSED;\n\n this.getState('events.workflow').emit(\n this.getState('event_names.workflow').WORKFLOW_PAUSED,\n this.getState()\n );\n }\n \n /**\n * Marks the workflow as resumed.\n */\n markAsResumed() {\n this.timing.resume_time = new Date();\n this.status = this.getState('statuses.workflow').RUNNING;\n\n this.getState('events.workflow').emit(\n this.getState('event_names.workflow').WORKFLOW_RESUMED,\n this.getState()\n );\n }\n\n /**\n * Moves a step from one index to another.\n * @param {number} fromIndex - The current index of the step.\n * @param {number} toIndex - The target index for the step.\n */\n moveStep(fromIndex, toIndex) {\n const [step] = this._steps.splice(fromIndex, 1);\n this._steps.splice(toIndex, 0, step);\n\n this.getState('events.workflow').emit(\n this.getState('event_names.workflow').WORKFLOW_STEP_MOVED,\n this.getState()\n );\n }\n\n /**\n * Pauses the workflow execution.\n */\n pause() {\n this.should_pause = true;\n this.timing.pause_time = new Date();\n\n this.getState('events.workflow').emit(\n this.getState('event_names.workflow').WORKFLOW_PAUSED,\n this.getState()\n );\n }\n\n /**\n * Removes and returns the last step from the workflow.\n * @returns {Step} The last step.\n */\n popStep() {\n return this._steps.pop();\n }\n\n /**\n * Prepares a result object and adds it to the results array.\n * @param {string} message - Result message.\n * @param {*} data - Result data.\n */\n prepareResult(message, data) {\n this.results.push({ message, data });\n }\n\n /**\n * Adds a step to the end of the workflow.\n * @param {Step} step - The step to add.\n */\n pushStep(step) {\n this.addStep(step);\n }\n\n /**\n * Adds multiple steps to the end of the workflow.\n * @param {Step[]} steps - Array of steps to add.\n */\n pushSteps(steps) {\n steps.forEach(step => this.addStep(step));\n }\n\n /**\n * Removes and returns the first step from the workflow.\n * @returns {Step} The first step.\n */\n shiftStep() {\n return this._steps.shift();\n }\n\n /**\n * Adds a step to the beginning of the workflow.\n * @param {Step} step - The step to add.\n * @throws {Error} Throws if step is not a valid Step instance.\n */\n unshiftStep(step) {\n if (typeof step.getCallableType !== 'function') {\n throw new Error('Invalid step type. Must be an instance of Step.');\n }\n\n if (!this.steps_by_id || typeof this.steps_by_id !== 'object') {\n this.steps_by_id = {};\n }\n\n this.steps_by_id[step.id] = step;\n\n step.parentWorkflowId = this.id;\n this._steps.unshift(step);\n }\n\n /**\n * Gets the array of steps in the workflow.\n * @returns {Step[]} Array of steps.\n */\n get steps() {\n return this._steps;\n }\n\n /**\n * Sets the steps array by adding multiple steps.\n * @param {Step[]} steps - Array of steps to add.\n */\n set steps(steps) {\n steps.forEach((step, index) => {\n if (typeof step.getCallableType !== 'function') {\n throw new Error(`Invalid step type. Step at index ${index} is not an instance of Step.`);\n }\n });\n\n this.addSteps(steps);\n }\n}\n"],
|
|
5
|
-
"mappings": "+EAAA,OAAOA,MAAU,YACjB,OAAS,cAAAC,MAAkB,oBAO3B,MAAOC,UAA+BF,CAAK,
|
|
6
|
-
"names": ["Base", "base_types", "Workflow", "__name", "name", "exit_on_error", "steps", "throw_on_empty", "i", "step_result", "error", "step", "result", "index", "stepId", "workflows", "fromIndex", "toIndex", "message", "data"]
|
|
4
|
+
"sourcesContent": ["import crypto from 'crypto';\nimport Base from './base.js';\nimport { base_types } from '../enums/index.js';\n\n/**\n * Workflow class for managing and executing a sequence of steps.\n * @class Workflow\n * @extends Base\n */\nexport default class Workflow extends Base {\n /**\n * Creates a new Workflow instance.\n * @param {Object} options - Configuration options.\n * @param {string} [options.name] - Name of the workflow.\n * @param {boolean} [options.exit_on_error=false] - Whether to exit on error.\n * @param {Array<Step>} [options.steps=[]] - Array of steps to add to the workflow.\n * @param {boolean} [options.throw_on_empty=false] - Whether to throw error if workflow is empty.\n */\n constructor({\n name,\n exit_on_error = false,\n steps = [],\n throw_on_empty = false\n }) {\n super({ name, base_type: base_types.WORKFLOW });\n\n this.initializeWorkflowState();\n\n this.addSteps(steps);\n\n this.exit_on_error = exit_on_error;\n this.throw_on_empty = throw_on_empty;\n this.sessions = {};\n this.current_session_id = null;\n }\n\n /**\n * Executes the workflow by running all steps in sequence.\n * @async\n * @returns {Promise<Workflow>} The workflow instance with execution results.\n * @throws {Error} Throws if workflow is empty and throw_on_empty is true.\n */\n async execute() {\n if (!this.current_session_id) {\n this.current_session_id = crypto.randomUUID();\n }\n\n if (this.isEmpty()) {\n if (this.throw_on_empty) {\n throw new Error('Cannot execute an empty workflow');\n }\n\n this.markAsComplete();\n this.prepareResult('Workflow is empty', null);\n return this;\n }\n \n this.markAsRunning();\n\n for (let i = 0; i < this._steps.length; i++) {\n if (this.should_break) {\n this.log(this.getState('event_names.workflow').WORKFLOW_BREAK_EXECUTED, `Workflow \"${this.name}\" execution broken at step ${this._steps[i].name} - ${this._steps[i].id}.`);\n break;\n }\n\n if (this.should_skip) {\n this.log(\n this.getState('events.workflow.event_names.WORKFLOW_STEP_SKIPPED'),\n `Workflow \"${this.name}\" skipping step ${this._steps[i].name} - ${this._steps[i].id}.`\n );\n this.should_skip = false;\n continue;\n }\n\n this.current_step = this._steps[i].id;\n\n try {\n const step_result = await this.step();\n this.prepareResult('Success', step_result);\n } catch (error) {\n this.markAsFailed();\n this.prepareResult(`Workflow execution failed at step ${this.steps_by_id[this.current_step].name} - ${this.current_step}`, { error });\n \n if (this.exit_on_error) {\n return this;\n }\n }\n\n if (this.should_pause) {\n this.markAsPaused();\n this.should_pause = false;\n return this;\n }\n }\n\n this.markAsComplete();\n return this;\n }\n\n /**\n * Resumes a paused workflow.\n * @async\n * @returns {Promise<Workflow>} The workflow instance.\n */\n async resume() {\n this.should_pause = false;\n this.timing.resume_time = new Date();\n\n this.getState('events.workflow').emit(\n this.getState('event_names.workflow').WORKFLOW_RESUMED,\n this.getState()\n );\n return this.execute();\n }\n\n /**\n * Executes a single step in the workflow.\n * @async\n * @returns {Promise<*>} The result of the step execution.\n */\n async step() {\n const step = this.steps_by_id[this.current_step];\n\n step.parentWorkflowId = this.id;\n const result = await step.execute();\n\n if (step.status === this.getState('statuses.step.FAILED')) {\n throw step.errors[step.errors.length - 1] ?? new Error(`Step \"${step.name}\" failed`);\n }\n\n return result;\n }\n\n /**\n * Adds a step to the workflow.\n * @param {Step} step - The step to add.\n * @throws {Error} Throws if step is not a valid Step instance.\n */\n addStep(step) {\n if (typeof step.getCallableType !== 'function') {\n throw new Error('Invalid step type. Must be an instance of Step.');\n }\n\n if (!Array.isArray(this._steps)) {\n this._steps = [];\n }\n\n if (!this.steps_by_id || typeof this.steps_by_id !== 'object') {\n this.steps_by_id = {};\n }\n\n this.steps_by_id[step.id] = step;\n\n step.parentWorkflowId = this.id;\n this._steps.push(step);\n }\n\n /**\n * Adds a step at a specific index in the workflow.\n * @param {Step} step - The step to add.\n * @param {number} index - The index at which to insert the step.\n */\n addStepAtIndex(step, index) {\n if (!this.steps_by_id || typeof this.steps_by_id !== 'object') {\n this.steps_by_id = {};\n }\n\n this.steps_by_id[step.id] = step;\n step.parentWorkflowId = this.id;\n this._steps.splice(index, 0, step);\n }\n\n /**\n * Adds multiple steps to the workflow.\n * @param {Step[]} steps - Array of steps to add.\n */\n addSteps(steps) {\n steps.forEach(step => this.addStep(step));\n }\n\n /**\n * Clears all steps from the workflow.\n */\n clearSteps() {\n this._steps = [];\n }\n\n /**\n * Closes the current session and stores a snapshot of the workflow state.\n */\n closeCurrentSession() {\n if (!this.current_session_id) {\n return;\n }\n\n this.sessions[this.current_session_id] = {\n results: [...this.results],\n status: this.status,\n timing: { ...this.timing },\n closed_at: new Date()\n };\n this.current_session_id = null;\n }\n\n /**\n * Deletes a step from the workflow by its ID.\n * @param {string} stepId - The ID of the step to delete.\n */\n deleteStep(stepId) {\n this._steps = this._steps.filter(step => step.id !== stepId);\n }\n\n /**\n * Deletes a step from the workflow by its index.\n * @param {number} index - The index of the step to delete.\n */\n deleteStepByIndex(index) {\n this._steps.splice(index, 1);\n }\n\n /**\n * Initializes the workflow state with default values.\n */\n initializeWorkflowState() {\n this.results = [];\n this.exit_on_error = false;\n this.current_step = null;\n this.should_break = false;\n this.should_continue = false;\n this.should_pause = false;\n this.should_skip = false;\n this.status = this.getState('statuses.workflow').CREATED;\n this._steps = [];\n this.throw_on_empty = this.throw_on_empty;\n this.timing = {\n ...this.timing,\n create_time: new Date(),\n pause_time: null,\n resume_time: null,\n }\n\n const workflows = this.getState('workflows');\n workflows[this.id] = this;\n this.setState('workflows', workflows);\n\n this.log(\n this.getState('event_names.workflow').WORKFLOW_CREATED,\n `Workflow \"${this.name}\" initialized.`\n );\n }\n\n /**\n * Checks if the workflow has no steps.\n * @returns {boolean} True if the workflow is empty.\n */\n isEmpty() {\n return !this._steps || !this._steps.length\n }\n\n /**\n * Marks the workflow as complete and closes the current session.\n */\n markAsComplete() {\n super.markAsComplete();\n this.closeCurrentSession();\n }\n\n /**\n * Marks the workflow as created.\n * @returns {string} The CREATED status.\n */\n markAsCreated() {\n this.timing.create_time = new Date();\n \n this.log(\n this.getState('event_names.workflow').WORKFLOW_CREATED,\n `Workflow \"${this.name}\" created.`\n );\n\n return this.getState('statuses.workflow').CREATED;\n }\n\n /**\n * Marks the workflow as failed and closes the current session.\n */\n markAsFailed() {\n super.markAsFailed();\n this.closeCurrentSession();\n }\n\n /**\n * Marks the workflow as paused.\n */\n markAsPaused() {\n this.timing.pause_time = new Date();\n this.status = this.getState('statuses.workflow').PAUSED;\n\n this.getState('events.workflow').emit(\n this.getState('event_names.workflow').WORKFLOW_PAUSED,\n this.getState()\n );\n }\n \n /**\n * Marks the workflow as resumed.\n */\n markAsResumed() {\n this.timing.resume_time = new Date();\n this.status = this.getState('statuses.workflow').RUNNING;\n\n this.getState('events.workflow').emit(\n this.getState('event_names.workflow').WORKFLOW_RESUMED,\n this.getState()\n );\n }\n\n /**\n * Moves a step from one index to another.\n * @param {number} fromIndex - The current index of the step.\n * @param {number} toIndex - The target index for the step.\n */\n moveStep(fromIndex, toIndex) {\n const [step] = this._steps.splice(fromIndex, 1);\n this._steps.splice(toIndex, 0, step);\n\n this.getState('events.workflow').emit(\n this.getState('event_names.workflow').WORKFLOW_STEP_MOVED,\n this.getState()\n );\n }\n\n /**\n * Pauses the workflow execution.\n */\n pause() {\n this.should_pause = true;\n this.timing.pause_time = new Date();\n\n this.getState('events.workflow').emit(\n this.getState('event_names.workflow').WORKFLOW_PAUSED,\n this.getState()\n );\n }\n\n /**\n * Removes and returns the last step from the workflow.\n * @returns {Step} The last step.\n */\n popStep() {\n return this._steps.pop();\n }\n\n /**\n * Prepares a result object and adds it to the results array.\n * @param {string} message - Result message.\n * @param {*} data - Result data.\n */\n prepareResult(message, data) {\n this.results.push({ message, data });\n }\n\n /**\n * Adds a step to the end of the workflow.\n * @param {Step} step - The step to add.\n */\n pushStep(step) {\n this.addStep(step);\n }\n\n /**\n * Adds multiple steps to the end of the workflow.\n * @param {Step[]} steps - Array of steps to add.\n */\n pushSteps(steps) {\n steps.forEach(step => this.addStep(step));\n }\n\n /**\n * Removes and returns the first step from the workflow.\n * @returns {Step} The first step.\n */\n shiftStep() {\n return this._steps.shift();\n }\n\n /**\n * Adds a step to the beginning of the workflow.\n * @param {Step} step - The step to add.\n * @throws {Error} Throws if step is not a valid Step instance.\n */\n unshiftStep(step) {\n if (typeof step.getCallableType !== 'function') {\n throw new Error('Invalid step type. Must be an instance of Step.');\n }\n\n if (!this.steps_by_id || typeof this.steps_by_id !== 'object') {\n this.steps_by_id = {};\n }\n\n this.steps_by_id[step.id] = step;\n\n step.parentWorkflowId = this.id;\n this._steps.unshift(step);\n }\n\n /**\n * Gets the array of steps in the workflow.\n * @returns {Step[]} Array of steps.\n */\n get steps() {\n return this._steps;\n }\n\n /**\n * Sets the steps array by adding multiple steps.\n * @param {Step[]} steps - Array of steps to add.\n */\n set steps(steps) {\n steps.forEach((step, index) => {\n if (typeof step.getCallableType !== 'function') {\n throw new Error(`Invalid step type. Step at index ${index} is not an instance of Step.`);\n }\n });\n\n this.addSteps(steps);\n }\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAOA,MAAY,SACnB,OAAOC,MAAU,YACjB,OAAS,cAAAC,MAAkB,oBAO3B,MAAOC,UAA+BF,CAAK,CAT3C,MAS2C,CAAAG,EAAA,iBASzC,YAAY,CACV,KAAAC,EACA,cAAAC,EAAgB,GAChB,MAAAC,EAAQ,CAAC,EACT,eAAAC,EAAiB,EACnB,EAAG,CACD,MAAM,CAAE,KAAAH,EAAM,UAAWH,EAAW,QAAS,CAAC,EAE9C,KAAK,wBAAwB,EAE7B,KAAK,SAASK,CAAK,EAEnB,KAAK,cAAgBD,EACrB,KAAK,eAAiBE,EACtB,KAAK,SAAW,CAAC,EACjB,KAAK,mBAAqB,IAC5B,CAQA,MAAM,SAAU,CAKd,GAJK,KAAK,qBACR,KAAK,mBAAqBR,EAAO,WAAW,GAG1C,KAAK,QAAQ,EAAG,CAClB,GA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"throw_on_empty", "i", "step_result", "error", "step", "result", "index", "stepId", "workflows", "fromIndex", "toIndex", "message", "data"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ronaldroe/micro-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "A lightweight, flexible workflow orchestration library for Node.js and browser environments. Build complex, sequential processes with ease using an intuitive API that supports conditional logic, flow control, event handling, and state management.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"exports": {
|
package/src/classes/base.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
1
2
|
import { base_types } from '../enums/index.js';
|
|
2
3
|
import State from './state.js';
|
|
3
4
|
|
|
@@ -21,7 +22,6 @@ export default class Base {
|
|
|
21
22
|
this.timing = {
|
|
22
23
|
cancel_time: null,
|
|
23
24
|
complete_time: null,
|
|
24
|
-
end_time: null,
|
|
25
25
|
execution_time_ms: null,
|
|
26
26
|
start_time: null,
|
|
27
27
|
}
|
|
@@ -104,7 +104,7 @@ export default class Base {
|
|
|
104
104
|
* Marks the instance as running and sets the start time.
|
|
105
105
|
*/
|
|
106
106
|
markAsRunning() {
|
|
107
|
-
this.timing.start_time = new Date();
|
|
107
|
+
this.timing.start_time = this.timing.start_time ?? new Date();
|
|
108
108
|
this.status = State.get('statuses')[this.base_type].RUNNING;
|
|
109
109
|
|
|
110
110
|
this.log(
|
|
@@ -127,6 +127,8 @@ export default class LogicStep extends Step {
|
|
|
127
127
|
* @returns {boolean} True if conditional is valid.
|
|
128
128
|
*/
|
|
129
129
|
conditionalIsValid() {
|
|
130
|
+
// Check if all conditional properties are set (not null or undefined)
|
|
131
|
+
// Can't use falsy check here because valid values could be falsy (e.g. empty string, 0, false)
|
|
130
132
|
return (
|
|
131
133
|
this.conditional.subject !== null &&
|
|
132
134
|
this.conditional.subject !== undefined &&
|
|
@@ -47,7 +47,6 @@ export default class Step extends Base {
|
|
|
47
47
|
this.result = null;
|
|
48
48
|
this.retry_results = [];
|
|
49
49
|
this.timeout = null;
|
|
50
|
-
this.start_time = null;
|
|
51
50
|
}
|
|
52
51
|
|
|
53
52
|
/**
|
|
@@ -62,10 +61,6 @@ export default class Step extends Base {
|
|
|
62
61
|
);
|
|
63
62
|
}
|
|
64
63
|
|
|
65
|
-
if (!this.start_time) {
|
|
66
|
-
this.start_time = new Date();
|
|
67
|
-
}
|
|
68
|
-
|
|
69
64
|
this.markAsRunning();
|
|
70
65
|
|
|
71
66
|
try {
|
|
@@ -77,15 +72,9 @@ export default class Step extends Base {
|
|
|
77
72
|
retry_count: this.retry_count,
|
|
78
73
|
result: await this.execute(),
|
|
79
74
|
});
|
|
80
|
-
|
|
81
|
-
this.timing.end_time = new Date();
|
|
82
|
-
this.timing.execution_time_ms = this.timing.end_time - this.timing.start_time;
|
|
83
75
|
} else {
|
|
84
76
|
this.errors.push(error);
|
|
85
77
|
|
|
86
|
-
this.timing.end_time = new Date();
|
|
87
|
-
this.timing.execution_time_ms = this.timing.end_time - this.timing.start_time;
|
|
88
|
-
|
|
89
78
|
this.markAsFailed();
|
|
90
79
|
|
|
91
80
|
if (this.getState('exit_on_error')) {
|
package/src/classes/workflow.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
1
2
|
import Base from './base.js';
|
|
2
3
|
import { base_types } from '../enums/index.js';
|
|
3
4
|
|
|
@@ -58,7 +59,6 @@ export default class Workflow extends Base {
|
|
|
58
59
|
|
|
59
60
|
for (let i = 0; i < this._steps.length; i++) {
|
|
60
61
|
if (this.should_break) {
|
|
61
|
-
this.should_break = false;
|
|
62
62
|
this.log(this.getState('event_names.workflow').WORKFLOW_BREAK_EXECUTED, `Workflow "${this.name}" execution broken at step ${this._steps[i].name} - ${this._steps[i].id}.`);
|
|
63
63
|
break;
|
|
64
64
|
}
|