@cadenza.io/core 3.13.2 → 3.13.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +6 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils/tools.ts","../src/engine/SignalBroker.ts","../src/engine/GraphRunner.ts","../src/engine/GraphRun.ts","../src/utils/ColorRandomizer.ts","../src/engine/exporters/vue-flow/VueFlowExportVisitor.ts","../src/engine/exporters/vue-flow/VueFlowExporter.ts","../src/graph/execution/GraphNode.ts","../src/graph/context/GraphContext.ts","../src/graph/iterators/GraphNodeIterator.ts","../src/interfaces/SignalEmitter.ts","../src/utils/promise.ts","../src/graph/definition/GraphRoutine.ts","../src/graph/definition/Task.ts","../src/graph/iterators/TaskIterator.ts","../src/registry/GraphRegistry.ts","../src/graph/definition/DebounceTask.ts","../src/graph/definition/EphemeralTask.ts","../src/interfaces/ExecutionChain.ts","../src/graph/iterators/GraphLayerIterator.ts","../src/interfaces/GraphLayer.ts","../src/graph/execution/SyncGraphLayer.ts","../src/interfaces/GraphBuilder.ts","../src/engine/builders/GraphBreadthFirstBuilder.ts","../src/interfaces/GraphRunStrategy.ts","../src/engine/ThrottleEngine.ts","../src/graph/execution/AsyncGraphLayer.ts","../src/engine/builders/GraphAsyncQueueBuilder.ts","../src/engine/strategy/GraphAsyncRun.ts","../src/engine/strategy/GraphStandardRun.ts","../src/Cadenza.ts","../src/graph/definition/SignalTask.ts"],"sourcesContent":["import Cadenza, { CadenzaMode, TaskOptions } from \"./Cadenza\";\nimport GraphRun from \"./engine/GraphRun\";\nimport GraphRunner from \"./engine/GraphRunner\";\nimport SignalBroker from \"./engine/SignalBroker\";\nimport GraphContext from \"./graph/context/GraphContext\";\nimport DebounceTask, { DebounceOptions } from \"./graph/definition/DebounceTask\";\nimport EphemeralTask, {\n EphemeralTaskOptions,\n} from \"./graph/definition/EphemeralTask\";\nimport GraphRoutine from \"./graph/definition/GraphRoutine\";\nimport SignalTask from \"./graph/definition/SignalTask\";\nimport Task, {\n TaskFunction,\n TaskResult,\n ThrottleTagGetter,\n} from \"./graph/definition/Task\";\nimport SignalEmitter from \"./interfaces/SignalEmitter\";\nimport GraphRegistry from \"./registry/GraphRegistry\";\nimport { AnyObject } from \"./types/global\";\nimport {\n SchemaConstraints,\n SchemaDefinition,\n SchemaType,\n} from \"./types/schema\";\n\nexport default Cadenza;\nexport type {\n TaskResult,\n TaskOptions,\n AnyObject,\n SchemaDefinition,\n SchemaConstraints,\n SchemaType,\n ThrottleTagGetter,\n CadenzaMode,\n TaskFunction,\n DebounceOptions,\n EphemeralTaskOptions,\n};\nexport {\n Task,\n GraphRoutine,\n DebounceTask,\n EphemeralTask,\n SignalTask,\n SignalEmitter,\n GraphContext,\n GraphRegistry,\n GraphRun,\n SignalBroker,\n GraphRunner,\n};\n","/**\n * Creates a deep clone of the given input object or array, while allowing specific keys to be filtered out based on a provided criteria.\n *\n * @param {T} input The input data to be cloned. It can be an object or an array.\n * @param {(key: string) => boolean} [filterOut] A callback function to determine which keys should be excluded from the cloned structure. It receives the key as a parameter and should return `true` to exclude the key, or `false` to include it. Default is a function that includes all keys (`() => false`).\n * @return {T} Returns a deep clone of the input object or array with the specified keys filtered out.\n */\nexport function deepCloneFilter<T>(\n input: T,\n filterOut: (key: string) => boolean = () => false,\n): T {\n if (input === null || typeof input !== \"object\") {\n return input;\n }\n\n const visited = new WeakMap<any, any>(); // For cycle detection\n\n const stack: Array<{ source: any; target: any; key?: string }> = [];\n const output = Array.isArray(input) ? [] : {};\n\n stack.push({ source: input, target: output });\n visited.set(input, output);\n\n while (stack.length) {\n const { source, target, key } = stack.pop()!;\n const currentTarget = key !== undefined ? target[key] : target;\n\n if (\n // TODO Should probably not be done like this...\n key === \"taskInstance\" ||\n key === \"routineInstance\" ||\n key === \"task\" ||\n key === \"routine\" ||\n key === \"tasks\" ||\n key === \"routines\" ||\n key === \"httpServer\" ||\n key === \"httpsServer\"\n ) {\n target[key] = source;\n continue;\n }\n\n for (const [k, value] of Object.entries(source)) {\n if (filterOut(k)) continue;\n\n if (value && typeof value === \"object\") {\n if (visited.has(value)) {\n currentTarget[k] = visited.get(value); // Cycle: link to existing clone\n continue;\n }\n\n const clonedValue = Array.isArray(value) ? [] : {};\n currentTarget[k] = clonedValue;\n visited.set(value, clonedValue);\n\n stack.push({ source: value, target: currentTarget, key: k });\n } else {\n currentTarget[k] = value;\n }\n }\n }\n\n return output as T;\n}\n\n/**\n * Converts a given timestamp to an ISO 8601 formatted string.\n *\n * @param {number} timestamp - The timestamp in milliseconds to be formatted.\n * @return {string} The ISO 8601 formatted date string.\n */\nexport function formatTimestamp(timestamp: number) {\n return new Date(timestamp).toISOString();\n}\n","import GraphRunner from \"./GraphRunner\";\nimport { AnyObject, ThrottleHandle } from \"../types/global\";\nimport Task from \"../graph/definition/Task\";\nimport GraphRoutine from \"../graph/definition/GraphRoutine\";\nimport Cadenza from \"../Cadenza\";\nimport { formatTimestamp } from \"../utils/tools\";\nimport { v4 as uuid } from \"uuid\";\n\n/**\n * This class manages signals and observers, enabling communication across different parts of an application.\n * It follows a singleton design pattern, allowing for centralized signal management.\n */\nexport default class SignalBroker {\n static instance_: SignalBroker;\n\n static get instance(): SignalBroker {\n if (!this.instance_) {\n this.instance_ = new SignalBroker();\n }\n return this.instance_;\n }\n\n debug: boolean = false;\n verbose: boolean = false;\n\n setDebug(value: boolean) {\n this.debug = value;\n }\n\n setVerbose(value: boolean) {\n this.verbose = value;\n }\n\n /**\n * Validates the provided signal name string to ensure it adheres to specific formatting rules.\n * Throws an error if any of the validation checks fail.\n *\n * @param {string} signalName - The signal name to be validated.\n * @return {void} - Returns nothing if the signal name is valid.\n * @throws {Error} - Throws an error if the signal name is longer than 100 characters, contains spaces,\n * contains backslashes, or contains uppercase letters in restricted parts of the name.\n */\n validateSignalName(signalName: string) {\n if (signalName.length > 100) {\n throw new Error(\n `Signal name must be less than 100 characters: ${signalName}`,\n );\n }\n\n if (signalName.includes(\" \")) {\n throw new Error(`Signal name must not contain spaces: ${signalName}\"`);\n }\n\n if (signalName.includes(\"\\\\\")) {\n throw new Error(\n `Signal name must not contain backslashes: ${signalName}`,\n );\n }\n\n if (/[A-Z]/.test(signalName.split(\":\")[0].split(\".\").slice(1).join(\".\"))) {\n throw new Error(\n `Signal name must not contain uppercase letters in the middle of the signal name. It is only allowed in the first part of the signal name: ${signalName}`,\n );\n }\n }\n\n runner: GraphRunner | undefined;\n metaRunner: GraphRunner | undefined;\n\n public clearSignalsTask: Task | undefined;\n public getSignalsTask: Task | undefined;\n public registerSignalTask: Task | undefined;\n\n // TODO: Signals should be a class with a the observers, registered flag and other data.\n signalObservers: Map<\n string,\n {\n fn: (\n runner: GraphRunner,\n tasks: (Task | GraphRoutine)[],\n context: AnyObject,\n ) => void;\n tasks: Set<Task | GraphRoutine>;\n registered: boolean;\n }\n > = new Map();\n\n emitStacks: Map<string, Map<string, AnyObject>> = new Map(); // execId -> emitted signals\n\n constructor() {\n this.addSignal(\"meta.signal_broker.added\");\n }\n\n /**\n * Initializes with runners.\n * @param runner Standard runner for user signals.\n * @param metaRunner Meta runner for 'meta.' signals (suppresses further meta-emits).\n */\n bootstrap(runner: GraphRunner, metaRunner: GraphRunner): void {\n this.runner = runner;\n this.metaRunner = metaRunner;\n }\n\n /**\n * Initializes and sets up the various tasks for managing and processing signals.\n *\n * @return {void} This method does not return a value.\n */\n init() {\n this.clearSignalsTask = Cadenza.createDebounceMetaTask(\n \"Execute and clear queued signals\",\n () => {\n for (const [id, signals] of this.emitStacks.entries()) {\n signals.forEach((context, signal) => {\n this.execute(signal, context);\n signals.delete(signal);\n });\n\n this.emitStacks.delete(id);\n }\n return true;\n },\n \"Executes queued signals and clears the stack\",\n )\n .doOn(\"meta.process_signal_queue_requested\")\n .emits(\"meta.signal_broker.queue_empty\");\n\n this.getSignalsTask = Cadenza.createMetaTask(\"Get signals\", (ctx) => {\n const uniqueSignals = Array.from(this.signalObservers.keys()).filter(\n (s) => !s.includes(\":\"),\n );\n\n const processedSignals = uniqueSignals.map((signal) => ({\n signal,\n data: {\n registered: this.signalObservers.get(signal)?.registered ?? false,\n },\n }));\n\n return {\n __signals: processedSignals,\n ...ctx,\n };\n });\n\n this.registerSignalTask = Cadenza.createMetaTask(\n \"Register signal\",\n (ctx) => {\n const { __signalName } = ctx;\n this.signalObservers.get(__signalName)!.registered = true;\n },\n ).doOn(\"meta.signal.registered\");\n }\n\n /**\n * Observes a signal with a routine/task.\n * @param signal The signal (e.g., 'domain.action', 'domain.*' for wildcards).\n * @param routineOrTask The observer.\n * @edge Duplicates ignored; supports wildcards for broad listening.\n */\n observe(signal: string, routineOrTask: Task | GraphRoutine): void {\n this.addSignal(signal);\n this.signalObservers.get(signal)!.tasks.add(routineOrTask);\n }\n\n /**\n * Unsubscribes a routine/task from a signal.\n * @param signal The signal.\n * @param routineOrTask The observer.\n * @edge Removes all instances if duplicate; deletes if empty.\n */\n unsubscribe(signal: string, routineOrTask: Task | GraphRoutine): void {\n const obs = this.signalObservers.get(signal);\n if (obs) {\n obs.tasks.delete(routineOrTask);\n if (obs.tasks.size === 0) {\n this.signalObservers.delete(signal);\n }\n }\n }\n\n /**\n * Schedules a signal to be emitted after a specified delay or at an exact date and time.\n *\n * @param {string} signal - The name of the signal to be emitted.\n * @param {AnyObject} context - The context to be passed along with the signal.\n * @param {number} [timeoutMs=60000] - The delay in milliseconds before the signal is emitted. Defaults to 60,000 ms.\n * @param {Date} [exactDateTime] - An exact date and time at which to emit the signal. If provided, this overrides the `timeoutMs`.\n * @return {AbortController} An AbortController instance that can be used to cancel the scheduled signal emission.\n */\n schedule(\n signal: string,\n context: AnyObject,\n timeoutMs: number = 60_000,\n exactDateTime?: Date,\n ): AbortController {\n // 1. Compute the final delay\n let delay = timeoutMs;\n if (exactDateTime != null) {\n delay = exactDateTime.getTime() - Date.now();\n }\n delay = Math.max(0, timeoutMs);\n\n // 2. Create an AbortController so the caller can cancel\n const controller = new AbortController();\n const { signal: signalController } = controller;\n\n const tick = () => this.emit(signal, context);\n\n const timerId = setTimeout(() => {\n if (!signalController.aborted) tick();\n }, delay);\n\n // 3. Cleanup on abort\n signalController.addEventListener(\"abort\", () => clearTimeout(timerId));\n\n return controller; // caller can do `const ac = obj.schedule(...); ac.abort();`\n }\n\n /**\n * Emits `signal` repeatedly with a fixed interval.\n *\n * @param signal\n * @param context\n * @param intervalMs\n * @param leading If true, emits immediately (unless a startDateTime is given and we are before it).\n * @param startDateTime Optional absolute Date when the *first* emission after `leading` should occur.\n * @returns a handle with `clear()` to stop the loop.\n */\n throttle(\n signal: string,\n context: AnyObject,\n intervalMs: number = 60_000,\n leading = false,\n startDateTime?: Date,\n ): ThrottleHandle {\n if (intervalMs <= 0) {\n throw new Error(\"intervalMs must be a positive number\");\n }\n\n const emit = () => this.emit(signal, context);\n\n if (leading) {\n const now = Date.now();\n const start = startDateTime?.getTime();\n\n // If we have a startDateTime and we are already past it → fire now\n if (!start || start <= now) {\n emit();\n }\n }\n\n let firstDelay = intervalMs;\n if (startDateTime) {\n // Find the *next* slot that is >= now\n let slot = startDateTime.getTime();\n const now = Date.now();\n\n while (slot < now) {\n slot += intervalMs;\n }\n firstDelay = slot - now;\n }\n\n let timer: NodeJS.Timeout | null = null;\n let stopped = false;\n\n const scheduleNext = () => {\n if (stopped) return;\n emit();\n timer = setTimeout(scheduleNext, intervalMs);\n };\n\n timer = setTimeout(scheduleNext, firstDelay);\n\n return {\n clear() {\n stopped = true;\n if (timer !== null) clearTimeout(timer);\n },\n };\n }\n\n /**\n * Emits a signal with the specified context, triggering any associated handlers for that signal.\n *\n * @param {string} signal - The name of the signal to emit.\n * @param {AnyObject} [context={}] - An optional context object containing additional information or metadata\n * associated with the signal. If the context includes a `__routineExecId`, it will be handled accordingly.\n * @return {void} This method does not return a value.\n */\n emit(signal: string, context: AnyObject = {}): void {\n const execId = context.__routineExecId || \"global\"; // Assume from metadata\n delete context.__routineExecId;\n\n if (!this.emitStacks.has(execId)) this.emitStacks.set(execId, new Map());\n const stack = this.emitStacks.get(execId)!;\n stack.set(signal, context);\n\n this.addSignal(signal);\n\n let executed = false;\n try {\n executed = this.execute(signal, context);\n } finally {\n if (executed) stack.delete(signal);\n if (stack.size === 0) this.emitStacks.delete(execId);\n }\n }\n\n /**\n * Executes a signal by emitting events, updating context, and invoking listeners.\n * Creates a new execution trace if necessary and updates the context with relevant metadata.\n * Handles specific, hierarchy-based, and wildcard signals.\n *\n * @param {string} signal - The signal name to be executed, potentially including namespaces or tags (e.g., \"meta.*\" or \"signal:type\").\n * @param {AnyObject} context - An object containing relevant metadata and execution details used for handling the signal.\n * @return {boolean} Returns true if any listeners were successfully executed, otherwise false.\n */\n execute(signal: string, context: AnyObject): boolean {\n const isMeta = signal.includes(\"meta.\");\n const isSubMeta = signal.includes(\"sub_meta.\") || context.__isSubMeta;\n const isMetric = context.__signalEmission?.isMetric;\n\n const executionTraceId =\n context.__signalEmission?.executionTraceId ??\n context.__metadata?.__executionTraceId ??\n context.__executionTraceId ??\n uuid();\n\n if (!isSubMeta && (!isMeta || this.debug)) {\n const isNewTrace =\n !context.__signalEmission?.executionTraceId &&\n !context.__metadata?.__executionTraceId &&\n !context.__executionTraceId;\n\n if (isNewTrace) {\n this.emit(\"sub_meta.signal_broker.new_trace\", {\n data: {\n uuid: executionTraceId,\n issuer_type: \"service\", // TODO: Add issuer type\n issuer_id:\n context.__metadata?.__issuerId ?? context.__issuerId ?? null,\n issued_at: formatTimestamp(Date.now()),\n intent: context.__metadata?.__intent ?? context.__intent ?? null,\n context: {\n id: uuid(),\n context: context,\n },\n is_meta: isMeta,\n },\n metadata: {\n __executionTraceId: executionTraceId,\n },\n });\n }\n\n context.__metadata = {\n ...context.__metadata,\n __executionTraceId: executionTraceId,\n };\n\n const emittedAt = Date.now();\n\n const signalParts = signal.split(\":\");\n const signalName = signalParts[0];\n const signalTag = signalParts.length > 1 ? signalParts[1] : null;\n context.__signalEmission = {\n ...(context.__signalEmission ?? {}),\n uuid: uuid(),\n executionTraceId,\n signalName,\n signalTag,\n emittedAt: formatTimestamp(emittedAt),\n consumed: false,\n consumedBy: null,\n isMeta,\n };\n\n this.emit(\"sub_meta.signal_broker.emitting_signal\", { ...context });\n } else if (isSubMeta) {\n context.__isSubMeta = true;\n }\n\n context.__metadata = {\n ...context.__metadata,\n __executionTraceId: executionTraceId,\n };\n\n if (this.debug && ((!isMetric && !isSubMeta) || this.verbose)) {\n console.log(\n `EMITTING ${signal} to listeners ${this.signalObservers.get(signal)?.tasks.size ?? 0} with context ${this.verbose ? JSON.stringify(context) : JSON.stringify(context).slice(0, 100)}`,\n );\n }\n\n let executed;\n executed = this.executeListener(signal, context); // Exact signal\n\n if (!isSubMeta) {\n const parts = signal\n .slice(0, Math.max(signal.lastIndexOf(\":\"), signal.lastIndexOf(\".\")))\n .split(\".\");\n for (let i = parts.length; i > -1; i--) {\n const parent = parts.slice(0, i).join(\".\");\n executed = this.executeListener(parent + \".*\", context) || executed; // Wildcard\n }\n }\n\n return executed;\n }\n\n /**\n * Executes the tasks associated with a given signal and context.\n * It processes both normal and meta tasks depending on the signal type\n * and the availability of the appropriate runner.\n *\n * @param {string} signal - The signal identifier that determines which tasks to execute.\n * @param {AnyObject} context - The context object passed to the task execution function.\n * @return {boolean} - Returns true if tasks were executed; otherwise, false.\n */\n executeListener(signal: string, context: AnyObject): boolean {\n const obs = this.signalObservers.get(signal);\n if (!obs || obs.tasks.size === 0) {\n return false;\n }\n\n const isMeta = signal.startsWith(\"meta\");\n if (!isMeta) {\n const tasks: Task[] = [];\n const metaTasks: Task[] = [];\n\n obs.tasks.forEach(\n (\n task, // @ts-ignore\n ) => (task.isMeta ? metaTasks.push(task) : tasks.push(task)),\n );\n\n if (tasks.length && this.runner) {\n obs.fn(this.runner, tasks, context);\n }\n\n if (metaTasks.length && this.metaRunner) {\n obs.fn(this.metaRunner, metaTasks, context);\n }\n\n return true;\n } else if (this.metaRunner) {\n obs.fn(this.metaRunner, Array.from(obs.tasks), context);\n return true;\n }\n\n return false;\n }\n\n /**\n * Adds a signal to the signalObservers for tracking and execution.\n * Performs validation on the signal name and emits a meta signal event when added.\n * If the signal contains a namespace (denoted by a colon \":\"), its base signal is\n * also added if it doesn't already exist.\n *\n * @param {string} signal - The name of the signal to be added.\n * @return {void} This method does not return any value.\n */\n addSignal(signal: string): void {\n let _signal = signal;\n if (!this.signalObservers.has(_signal)) {\n this.validateSignalName(_signal);\n this.signalObservers.set(_signal, {\n fn: (\n runner: GraphRunner,\n tasks: (Task | GraphRoutine)[],\n context: AnyObject,\n ) => runner.run(tasks, context),\n tasks: new Set(),\n registered: false,\n });\n\n const sections = _signal.split(\":\");\n if (sections.length === 2) {\n _signal = sections[0];\n\n if (!this.signalObservers.has(sections[0])) {\n this.signalObservers.set(_signal, {\n fn: (\n runner: GraphRunner,\n tasks: (Task | GraphRoutine)[],\n context: AnyObject,\n ) => runner.run(tasks, context),\n tasks: new Set(),\n registered: false,\n });\n } else {\n return;\n }\n }\n\n this.emit(\"meta.signal_broker.added\", { __signalName: _signal });\n }\n }\n\n /**\n * Lists all observed signals.\n * @returns Array of signals.\n */\n listObservedSignals(): string[] {\n return Array.from(this.signalObservers.keys());\n }\n\n reset() {\n this.emitStacks.clear();\n this.signalObservers.clear();\n }\n}\n","import { v4 as uuid } from \"uuid\";\nimport Task from \"../graph/definition/Task\";\nimport GraphRun from \"./GraphRun\";\nimport GraphNode from \"../graph/execution/GraphNode\";\nimport GraphRunStrategy from \"../interfaces/GraphRunStrategy\";\nimport { AnyObject } from \"../types/global\";\nimport GraphRoutine from \"../graph/definition/GraphRoutine\";\nimport SignalEmitter from \"../interfaces/SignalEmitter\";\nimport Cadenza from \"../Cadenza\";\nimport GraphRegistry from \"../registry/GraphRegistry\";\nimport GraphContext from \"../graph/context/GraphContext\";\nimport { formatTimestamp } from \"../utils/tools\";\n\n/**\n * Represents a runner for managing and executing tasks or routines within a graph.\n * The `GraphRunner` extends `SignalEmitter` to include signal-based event-driven mechanisms.\n */\nexport default class GraphRunner extends SignalEmitter {\n currentRun: GraphRun;\n debug: boolean = false;\n verbose: boolean = false;\n isRunning: boolean = false;\n readonly isMeta: boolean = false;\n\n strategy: GraphRunStrategy;\n\n /**\n * Constructs a runner.\n * @param isMeta Meta flag (default false).\n * @edge Creates 'Start run' meta-task chained to registry gets.\n */\n constructor(isMeta: boolean = false) {\n super(isMeta);\n this.isMeta = isMeta;\n this.strategy = Cadenza.runStrategy.PARALLEL;\n this.currentRun = new GraphRun(this.strategy);\n }\n\n init() {\n if (this.isMeta) return;\n\n Cadenza.createMetaTask(\n \"Start run\",\n this.startRun.bind(this),\n \"Starts a run\",\n ).doAfter(\n GraphRegistry.instance.getTaskByName,\n GraphRegistry.instance.getRoutineByName,\n );\n }\n\n /**\n * Adds tasks or routines to the current execution pipeline. Supports both individual tasks,\n * routines, or arrays of tasks and routines. Handles metadata and execution context management.\n *\n * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} tasks - The task(s) or routine(s) to be added.\n * It can be a single task, a single routine, or an array of tasks and routines.\n * @param {AnyObject} [context={}] - Optional context object to provide execution trace and metadata.\n * Used to propagate information across task or routine executions.\n * @return {void} - This method does not return a value.\n */\n addTasks(\n tasks: Task | GraphRoutine | (Task | GraphRoutine)[],\n context: AnyObject = {},\n ): void {\n let _tasks = Array.isArray(tasks) ? tasks : [tasks];\n if (_tasks.length === 0) {\n console.warn(\"No tasks/routines to add.\");\n return;\n }\n\n let routineName = _tasks.map((t) => t.name).join(\" | \");\n let routineVersion = null;\n let isMeta = _tasks.every((t) => t.isMeta);\n\n const allTasks = _tasks.flatMap((t) => {\n if (t instanceof GraphRoutine) {\n routineName = t.name;\n routineVersion = t.version;\n isMeta = t.isMeta;\n const routineTasks: Task[] = [];\n t.forEachTask((task: Task) => routineTasks.push(task));\n return routineTasks;\n }\n return t;\n });\n\n const isSubMeta =\n allTasks.some((t) => t.isSubMeta) || !!context.__isSubMeta;\n context.__isSubMeta = isSubMeta;\n\n const isNewTrace =\n !context.__routineExecId &&\n !context.__metadata?.__executionTraceId &&\n !context.__executionTraceId;\n\n const executionTraceId =\n context.__metadata?.__executionTraceId ??\n context.__executionTraceId ??\n uuid();\n\n context.__executionTraceId = executionTraceId;\n\n const routineExecId = context.__routineExecId ?? uuid();\n context.__routineExecId = routineExecId;\n\n const ctx = new GraphContext(context || {});\n\n if (!isSubMeta) {\n const contextData = ctx.export();\n if (isNewTrace) {\n this.emitMetrics(\"meta.runner.new_trace\", {\n data: {\n uuid: executionTraceId,\n issuer_type: \"service\", // TODO: Add issuer type\n issuer_id:\n context.__metadata?.__issuerId ?? context.__issuerId ?? null,\n issued_at: formatTimestamp(Date.now()),\n intent: context.__metadata?.__intent ?? context.__intent ?? null,\n context: contextData,\n is_meta: isMeta,\n },\n __metadata: {\n __executionTraceId: executionTraceId,\n },\n });\n }\n\n this.emitMetrics(\"meta.runner.added_tasks\", {\n data: {\n uuid: routineExecId,\n name: routineName,\n routineVersion,\n isMeta,\n executionTraceId,\n context: isNewTrace ? contextData.id : contextData,\n previousRoutineExecution:\n context.__localRoutineExecId ??\n context.__metadata?.__routineExecId ??\n null, // TODO: There is a chance this is not added to the database yet...\n created: formatTimestamp(Date.now()),\n },\n __metadata: {\n __executionTraceId: executionTraceId,\n },\n });\n }\n\n allTasks.forEach((task) =>\n this.currentRun.addNode(\n new GraphNode(task, ctx, routineExecId, [], this.debug, this.verbose),\n ),\n );\n }\n\n /**\n * Executes the provided tasks or routines. Maintains the execution state\n * and handles synchronous or asynchronous processing.\n *\n * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} [tasks] - A single task, a single routine, or an array of tasks or routines to execute. Optional.\n * @param {AnyObject} [context] - An optional context object to be used during task execution.\n * @return {GraphRun|Promise<GraphRun>} - Returns a `GraphRun` instance if the execution is synchronous, or a `Promise` resolving to a `GraphRun` for asynchronous execution.\n */\n public run(\n tasks?: Task | GraphRoutine | (Task | GraphRoutine)[],\n context?: AnyObject,\n ): GraphRun | Promise<GraphRun> {\n if (tasks) {\n this.addTasks(tasks, context ?? {});\n }\n\n if (this.isRunning) {\n return this.currentRun;\n }\n\n if (this.currentRun) {\n this.isRunning = true;\n const runResult = this.currentRun.run();\n\n if (runResult instanceof Promise) {\n return this.runAsync(runResult);\n }\n }\n\n return this.reset();\n }\n\n /**\n * Executes the provided asynchronous operation and resets the state afterwards.\n *\n * @param {Promise<void>} run - A promise representing the asynchronous operation to execute.\n * @return {Promise<GraphRun>} A promise that resolves to the result of the reset operation after the asynchronous operation completes.\n */\n async runAsync(run: Promise<void>): Promise<GraphRun> {\n await run;\n return this.reset();\n }\n\n /**\n * Resets the current state of the graph, creating a new GraphRun instance\n * and returning the previous run instance.\n * If the debug mode is not enabled, it will destroy the existing resources.\n *\n * @return {GraphRun} The last GraphRun instance before the reset.\n */\n reset(): GraphRun {\n this.isRunning = false;\n\n const lastRun = this.currentRun;\n\n if (!this.debug) {\n this.destroy();\n }\n\n this.currentRun = new GraphRun(this.strategy);\n\n return lastRun;\n }\n\n public setDebug(value: boolean): void {\n this.debug = value;\n }\n\n public setVerbose(value: boolean): void {\n this.verbose = value;\n }\n\n public destroy(): void {\n this.currentRun.destroy();\n }\n\n /**\n * Sets the strategy to be used for running the graph and initializes\n * the current run with the provided strategy if no process is currently running.\n *\n * @param {GraphRunStrategy} strategy - The strategy to use for running the graph.\n * @return {void}\n */\n public setStrategy(strategy: GraphRunStrategy): void {\n this.strategy = strategy;\n if (!this.isRunning) {\n this.currentRun = new GraphRun(this.strategy);\n }\n }\n\n // TODO This should not live here. This is deputy related.\n startRun(\n context: AnyObject,\n emit: (signal: string, ctx: AnyObject) => void,\n ): boolean {\n if (context.task || context.routine) {\n const routine = context.task ?? context.routine;\n delete context.task;\n delete context.routine;\n context.__routineExecId = context.__metadata?.__deputyExecId ?? null;\n context.__isDeputy = true;\n this.run(routine, context);\n return true;\n } else {\n context.errored = true;\n context.__error = \"No routine or task defined.\";\n emit(\"meta.runner.failed\", context);\n return false;\n }\n }\n}\n","import { v4 as uuid } from \"uuid\";\nimport GraphNode from \"../graph/execution/GraphNode\";\nimport GraphExporter from \"../interfaces/GraphExporter\";\nimport SyncGraphLayer from \"../graph/execution/SyncGraphLayer\";\nimport GraphRunStrategy from \"../interfaces/GraphRunStrategy\";\nimport GraphLayer from \"../interfaces/GraphLayer\";\nimport VueFlowExporter from \"./exporters/vue-flow/VueFlowExporter\";\n\nexport interface RunJson {\n __id: string;\n __label: string;\n __graph: any;\n __data: any;\n}\n\n/**\n * Represents a GraphRun instance which manages the execution of a graph-based workflow.\n * It utilizes a specific strategy and export mechanism to manage, execute, and export the graph data.\n */\nexport default class GraphRun {\n readonly id: string;\n graph: GraphLayer | undefined;\n // @ts-ignore\n strategy: GraphRunStrategy;\n exporter: GraphExporter | undefined;\n\n constructor(strategy: GraphRunStrategy) {\n this.id = uuid();\n this.strategy = strategy;\n this.strategy.setRunInstance(this);\n this.exporter = new VueFlowExporter();\n }\n\n setGraph(graph: GraphLayer) {\n this.graph = graph;\n }\n\n addNode(node: GraphNode) {\n this.strategy.addNode(node);\n }\n\n // Composite function / Command execution\n run(): void | Promise<void> {\n return this.strategy.run();\n }\n\n // Composite function\n destroy() {\n this.graph?.destroy();\n this.graph = undefined;\n this.exporter = undefined;\n }\n\n // Composite function\n log() {\n console.log(\"vvvvvvvvvvvvvvvvv\");\n console.log(\"GraphRun\");\n console.log(\"vvvvvvvvvvvvvvvvv\");\n this.graph?.log();\n console.log(\"=================\");\n }\n\n // Memento\n export(): RunJson {\n if (this.exporter && this.graph) {\n const data = this.strategy.export();\n return {\n __id: this.id,\n __label: data.__startTime ?? this.id,\n __graph: this.exporter?.exportGraph(this.graph as SyncGraphLayer),\n __data: data,\n };\n }\n\n return {\n __id: this.id,\n __label: this.id,\n __graph: undefined,\n __data: {},\n };\n }\n\n // Export Strategy\n setExporter(exporter: GraphExporter) {\n this.exporter = exporter;\n }\n}\n","export default class ColorRandomizer {\n numberOfSteps: number;\n stepCounter = 0;\n spread: number;\n range: number;\n\n constructor(numberOfSteps: number = 200, spread: number = 30) {\n this.numberOfSteps = numberOfSteps;\n this.spread = spread;\n this.range = Math.floor(numberOfSteps / this.spread);\n }\n\n rainbow(numOfSteps: number, step: number) {\n // This function generates vibrant, \"evenly spaced\" colours (i.e. no clustering). This is ideal for creating easily distinguishable vibrant markers in Google Maps and other apps.\n // Adam Cole, 2011-Sept-14\n // HSV to RBG adapted from: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript\n let r, g, b;\n const h = step / numOfSteps;\n const i = ~~(h * 6);\n const f = h * 6 - i;\n const q = 1 - f;\n switch (i % 6) {\n case 0:\n r = 1;\n g = f;\n b = 0;\n break;\n case 1:\n r = q;\n g = 1;\n b = 0;\n break;\n case 2:\n r = 0;\n g = 1;\n b = f;\n break;\n case 3:\n r = 0;\n g = q;\n b = 1;\n break;\n case 4:\n r = f;\n g = 0;\n b = 1;\n break;\n case 5:\n r = 1;\n g = 0;\n b = q;\n break;\n default:\n r = 0;\n g = 0;\n b = 0;\n break;\n }\n // @ts-ignore\n const c =\n \"#\" +\n (\"00\" + (~~(r * 255)).toString(16)).slice(-2) +\n (\"00\" + (~~(g * 255)).toString(16)).slice(-2) +\n (\"00\" + (~~(b * 255)).toString(16)).slice(-2);\n return c;\n }\n\n getRandomColor() {\n this.stepCounter++;\n\n if (this.stepCounter > this.numberOfSteps) {\n this.stepCounter = 1;\n }\n\n const randomStep =\n ((this.stepCounter * this.range) % this.numberOfSteps) -\n this.range +\n Math.floor(this.stepCounter / this.spread);\n\n return this.rainbow(this.numberOfSteps, randomStep);\n }\n}\n","import GraphVisitor from \"../../../interfaces/GraphVisitor\";\nimport SyncGraphLayer from \"../../../graph/execution/SyncGraphLayer\";\nimport GraphNode from \"../../../graph/execution/GraphNode\";\nimport Task from \"../../../graph/definition/Task\";\nimport ColorRandomizer from \"../../../utils/ColorRandomizer\";\n\nexport default class VueFlowExportVisitor implements GraphVisitor {\n nodeCount = 0;\n elements: any[] = [];\n index = 0;\n numberOfLayerNodes = 0;\n contextToColor: { [id: string]: string } = {};\n colorRandomizer = new ColorRandomizer();\n\n visitLayer(layer: SyncGraphLayer): any {\n const snapshot = layer.export();\n\n this.numberOfLayerNodes = snapshot.__numberOfNodes;\n this.index = 0;\n }\n\n visitNode(node: GraphNode): any {\n const snapshot = node.export();\n\n if (!this.contextToColor[snapshot.__context.id]) {\n this.contextToColor[snapshot.__context.id] =\n this.colorRandomizer.getRandomColor();\n }\n\n const color = this.contextToColor[snapshot.__context.id];\n\n this.elements.push({\n id: snapshot.__id.slice(0, 8),\n label: snapshot.__task.__name,\n position: {\n x: snapshot.__task.__layerIndex * 500,\n y: -50 * this.numberOfLayerNodes * 0.5 + (this.index * 60 + 30),\n },\n sourcePosition: \"right\",\n targetPosition: \"left\",\n style: { backgroundColor: `${color}`, width: \"180px\" },\n data: {\n executionTime: snapshot.__executionTime,\n executionStart: snapshot.__executionStart,\n executionEnd: snapshot.__executionEnd,\n description: snapshot.__task.__description,\n functionString: snapshot.__task.__functionString,\n context: snapshot.__context.context,\n layerIndex: snapshot.__task.__layerIndex,\n },\n });\n\n for (const [index, nextNodeId] of snapshot.__nextNodes.entries()) {\n this.elements.push({\n id: `${snapshot.__id.slice(0, 8)}-${index}`,\n source: snapshot.__id.slice(0, 8),\n target: nextNodeId.slice(0, 8),\n });\n }\n\n this.index++;\n this.nodeCount++;\n }\n\n visitTask(task: Task) {\n const snapshot = task.export();\n\n this.elements.push({\n id: snapshot.__id.slice(0, 8),\n label: snapshot.__name,\n position: { x: snapshot.__layerIndex * 300, y: this.index * 50 + 30 },\n sourcePosition: \"right\",\n targetPosition: \"left\",\n data: {\n description: snapshot.__description,\n functionString: snapshot.__functionString,\n layerIndex: snapshot.__layerIndex,\n },\n });\n\n for (const [index, nextTaskId] of snapshot.__nextTasks.entries()) {\n this.elements.push({\n id: `${snapshot.__id.slice(0, 8)}-${index}`,\n source: snapshot.__id.slice(0, 8),\n target: nextTaskId.slice(0, 8),\n });\n }\n\n this.index++;\n this.nodeCount++;\n }\n\n getElements() {\n return this.elements;\n }\n\n getNodeCount() {\n return this.nodeCount;\n }\n}\n","import GraphExporter from \"../../../interfaces/GraphExporter\";\nimport SyncGraphLayer from \"../../../graph/execution/SyncGraphLayer\";\nimport VueFlowExportVisitor from \"./VueFlowExportVisitor\";\nimport Task from \"../../../graph/definition/Task\";\n\nexport default class VueFlowExporter implements GraphExporter {\n exportGraph(graph: SyncGraphLayer): any {\n const exporterVisitor = new VueFlowExportVisitor();\n const layers = graph.getIterator();\n while (layers.hasNext()) {\n const layer = layers.next();\n layer.accept(exporterVisitor);\n }\n\n return {\n elements: exporterVisitor.getElements(),\n numberOfNodes: exporterVisitor.getNodeCount(),\n };\n }\n\n exportStaticGraph(graph: Task[]) {\n const exporterVisitor = new VueFlowExportVisitor();\n\n let prevTask = null;\n for (const task of graph) {\n if (task === prevTask) {\n continue;\n }\n\n const tasks = task.getIterator();\n const exportedTaskNames: string[] = [];\n\n while (tasks.hasNext()) {\n const task = tasks.next();\n if (task && !exportedTaskNames.includes(task.name)) {\n exportedTaskNames.push(task.name);\n task.accept(exporterVisitor);\n }\n }\n\n prevTask = task;\n }\n\n return {\n elements: exporterVisitor.getElements(),\n numberOfNodes: exporterVisitor.getNodeCount(),\n };\n }\n}\n","import { v4 as uuid } from \"uuid\";\nimport Task, { TaskResult } from \"../definition/Task\";\nimport GraphContext from \"../context/GraphContext\";\nimport Graph from \"../../interfaces/Graph\";\nimport GraphVisitor from \"../../interfaces/GraphVisitor\";\nimport GraphNodeIterator from \"../iterators/GraphNodeIterator\";\nimport SignalEmitter from \"../../interfaces/SignalEmitter\";\nimport GraphLayer from \"../../interfaces/GraphLayer\";\nimport { AnyObject } from \"../../types/global\";\nimport { sleep } from \"../../utils/promise\";\nimport { formatTimestamp } from \"../../utils/tools\";\n\n/**\n * Represents a node in a graph structure used for executing tasks.\n * A Node is a container for a task and its associated context, providing\n * methods for executing the task and managing its lifecycle.\n *\n * It extends the SignalEmitter class to emit and handle signals related to\n * the node's lifecycle, such as \"meta.node.started\" and \"meta.node.completed\".\n *\n * It also implements the Graph interface, allowing it to be used as a part of\n * a graph structure, such as a GraphLayer or GraphRoutine.\n *\n * @extends SignalEmitter\n * @implements Graph\n */\nexport default class GraphNode extends SignalEmitter implements Graph {\n id: string;\n routineExecId: string;\n executionTraceId: string;\n task: Task;\n context: GraphContext;\n layer: GraphLayer | undefined;\n divided: boolean = false;\n splitGroupId: string = \"\";\n processing: boolean = false;\n subgraphComplete: boolean = false;\n graphComplete: boolean = false;\n result: TaskResult = false;\n retryCount: number = 0;\n retryDelay: number = 0;\n retries: number = 0;\n previousNodes: GraphNode[] = [];\n nextNodes: GraphNode[] = [];\n executionTime: number = 0;\n executionStart: number = 0;\n failed: boolean = false;\n errored: boolean = false;\n destroyed: boolean = false;\n debug: boolean = false;\n verbose: boolean = false;\n\n constructor(\n task: Task,\n context: GraphContext,\n routineExecId: string,\n prevNodes: GraphNode[] = [],\n debug: boolean = false,\n verbose: boolean = false,\n ) {\n super(\n (task.isMeta && !debug) ||\n task.isSubMeta ||\n context?.getMetadata()?.__isSubMeta,\n );\n this.id = uuid();\n this.task = task;\n this.context = context;\n this.retryCount = task.retryCount;\n this.retryDelay = task.retryDelay;\n this.previousNodes = prevNodes;\n this.routineExecId = routineExecId;\n this.splitGroupId = routineExecId;\n this.debug = debug;\n this.verbose = verbose;\n const ctx = context.getMetadata();\n this.executionTraceId =\n ctx.__executionTraceId ?? ctx.__metadata?.__executionTraceId;\n\n if (!this.task || !this.task.validateInput) {\n console.log(\"task not found\", this.task, this.context);\n }\n }\n\n setDebug(value: boolean) {\n this.debug = value;\n }\n\n public isUnique() {\n return this.task.isUnique;\n }\n\n public isMeta() {\n return this.task.isMeta;\n }\n\n public isProcessed() {\n return this.divided;\n }\n\n public isProcessing() {\n return this.processing;\n }\n\n public subgraphDone() {\n return this.subgraphComplete;\n }\n\n public graphDone() {\n return this.graphComplete;\n }\n\n /**\n * Compares the current GraphNode instance with another GraphNode to determine if they are considered equal.\n *\n * @param {GraphNode} node - The GraphNode object to compare with the current instance.\n * @return {boolean} Returns true if the nodes share the same task, context, and belong to the same graph; otherwise, false.\n */\n public isEqualTo(node: GraphNode) {\n return (\n this.sharesTaskWith(node) &&\n this.sharesContextWith(node) &&\n this.isPartOfSameGraph(node)\n );\n }\n\n /**\n * Determines if the given node is part of the same graph as the current node.\n *\n * @param {GraphNode} node - The node to compare with the current node.\n * @return {boolean} Returns true if the provided node is part of the same graph\n * (i.e., has the same routineExecId), otherwise false.\n */\n public isPartOfSameGraph(node: GraphNode) {\n return this.routineExecId === node.routineExecId;\n }\n\n /**\n * Determines whether the current instance shares a task with the provided node.\n *\n * @param {GraphNode} node - The graph node to compare with the current instance.\n * @return {boolean} Returns true if the task names of both nodes match, otherwise false.\n */\n public sharesTaskWith(node: GraphNode) {\n return this.task.name === node.task.name;\n }\n\n /**\n * Determines whether the current node shares the same context as the specified node.\n *\n * @param {GraphNode} node - The graph node to compare with the current node's context.\n * @return {boolean} True if both nodes share the same context; otherwise, false.\n */\n public sharesContextWith(node: GraphNode) {\n return this.context.id === node.context.id;\n }\n\n public getLayerIndex() {\n return this.task.layerIndex;\n }\n\n public getConcurrency() {\n return this.task.concurrency;\n }\n\n /**\n * Retrieves the tag associated with the current task and context.\n *\n * @return {string} The tag retrieved from the task within the given context.\n */\n public getTag() {\n return this.task.getTag(this.context);\n }\n\n /**\n * Schedules the current node/task on the specified graph layer if applicable.\n *\n * This method assesses whether the current node/task should be scheduled\n * on the given graph layer. It ensures that tasks are only scheduled\n * under certain conditions, such as checking if the task shares\n * execution contexts or dependencies with other nodes, and handles\n * various metadata emissions and context updates during the scheduling process.\n *\n * @param {GraphLayer} layer - The graph layer on which the current task should be scheduled.\n * @returns {void} Does not return a value.\n */\n public scheduleOn(layer: GraphLayer) {\n let shouldSchedule = true;\n const nodes = layer.getNodesByRoutineExecId(this.routineExecId);\n for (const node of nodes) {\n if (node.isEqualTo(this)) {\n shouldSchedule = false;\n break;\n }\n\n if (node.sharesTaskWith(this) && node.isUnique()) {\n node.consume(this);\n shouldSchedule = false;\n break;\n }\n }\n\n if (shouldSchedule) {\n this.layer = layer;\n layer.add(this);\n\n const context = this.context.getFullContext();\n\n const scheduledAt = Date.now();\n this.emitMetricsWithMetadata(\"meta.node.scheduled\", {\n data: {\n uuid: this.id,\n routineExecutionId: this.routineExecId,\n executionTraceId: this.executionTraceId,\n context:\n this.previousNodes.length === 0\n ? this.context.id\n : this.context.export(),\n taskName: this.task.name,\n taskVersion: this.task.version,\n isMeta: this.isMeta(),\n isScheduled: true,\n splitGroupId: this.splitGroupId,\n created: formatTimestamp(scheduledAt),\n },\n });\n\n this.previousNodes.forEach((node) => {\n this.emitMetricsWithMetadata(\"meta.node.mapped\", {\n data: {\n taskExecutionId: this.id,\n previousTaskExecutionId: node.id,\n },\n filter: {\n taskName: this.task.name,\n taskVersion: this.task.version,\n predecessorTaskName: node.task.name,\n predecessorTaskVersion: node.task.version,\n },\n });\n });\n\n if (!this.silent && context.__previousTaskExecutionId) {\n this.emitMetricsWithMetadata(\n \"meta.node.detected_previous_task_execution\",\n {\n data: {\n taskExecutionId: this.id,\n previousTaskExecutionId: context.__previousTaskExecutionId,\n },\n filter: {\n taskName: this.task.name,\n taskVersion: this.task.version,\n },\n ...context,\n },\n );\n context.__previousTaskExecutionId = null;\n }\n\n if (\n context.__signalEmission?.consumed === false &&\n (!this.isMeta() || this.debug)\n ) {\n this.emitMetricsWithMetadata(\"meta.node.consumed_signal\", {\n data: {\n signalEmissionId: context.__signalEmission.uuid,\n signalName: context.__signalEmission.signalName,\n signalTag: context.__signalEmission.signalTag,\n taskName: this.task.name,\n taskVersion: this.task.version,\n taskExecutionId: this.id,\n routineExecutionId: this.routineExecId,\n executionTraceId: this.executionTraceId,\n consumedAt: formatTimestamp(scheduledAt),\n },\n });\n\n context.__signalEmission.consumed = true;\n context.__signalEmission.consumedBy = this.id;\n }\n }\n }\n\n /**\n * Starts the execution process by initializing the execution start timestamp,\n * emitting relevant metadata, and logging debug information if applicable.\n *\n * The method performs the following actions:\n * 1. Sets the execution start timestamp if it's not already initialized.\n * 2. Emits metrics with metadata about the routine execution starting, including additional data if there are no previous nodes.\n * 3. Optionally logs debug or verbose information based on the current settings.\n * 4. Emits additional metrics to indicate that the execution has started.\n *\n * @return {number} The timestamp indicating when the execution started.\n */\n public start() {\n if (this.executionStart === 0) {\n this.executionStart = Date.now();\n }\n\n if (this.previousNodes.length === 0) {\n this.emitMetricsWithMetadata(\"meta.node.started_routine_execution\", {\n data: {\n isRunning: true,\n started: formatTimestamp(this.executionStart),\n },\n filter: { uuid: this.routineExecId },\n });\n }\n\n if (\n (this.debug &&\n !this.task.isSubMeta &&\n !this.context.getMetadata().__isSubMeta) ||\n this.verbose\n ) {\n this.log();\n }\n\n this.emitMetricsWithMetadata(\"meta.node.started\", {\n data: {\n isRunning: true,\n started: formatTimestamp(this.executionStart),\n },\n filter: { uuid: this.id },\n });\n\n return this.executionStart;\n }\n\n /**\n * Marks the end of an execution process, performs necessary cleanup, emits\n * metrics with associated metadata, and signals the completion of execution.\n * Also handles specific cases when the graph completes.\n *\n * @return {number} The timestamp corresponding to the end of execution. If execution\n * was not started, it returns 0.\n */\n public end() {\n if (this.executionStart === 0) {\n return 0;\n }\n\n this.processing = false;\n const end = Date.now();\n this.executionTime = end - this.executionStart;\n\n const context = this.context.getFullContext();\n\n if (this.errored || this.failed) {\n this.emitMetricsWithMetadata(\"meta.node.errored\", {\n data: {\n isRunning: false,\n errored: this.errored,\n failed: this.failed,\n errorMessage: context.__error,\n },\n filter: { uuid: this.id },\n });\n }\n\n this.emitMetricsWithMetadata(\"meta.node.ended\", {\n data: {\n isRunning: false,\n isComplete: true,\n resultContext: this.context.export(),\n errored: this.errored,\n failed: this.failed,\n errorMessage: context.__error,\n progress: 1.0,\n ended: formatTimestamp(end),\n },\n filter: { uuid: this.id },\n });\n\n if (this.graphDone()) {\n const context = this.context.export();\n if (context.context.__isDeputy)\n this.emitWithMetadata(\n `meta.node.graph_completed:${this.routineExecId}`,\n context.context,\n );\n\n // TODO Reminder, Service registry should be listening to this event, (updateSelf)\n this.emitMetricsWithMetadata(\"meta.node.ended_routine_execution\", {\n data: {\n isRunning: false,\n isComplete: true,\n resultContext: this.context.id,\n progress: 1.0,\n ended: formatTimestamp(end),\n },\n filter: { uuid: this.routineExecId },\n });\n }\n\n return end;\n }\n\n /**\n * Executes the main logic of the task, including input validation, processing, and post-processing.\n * Handles both synchronous and asynchronous workflows.\n *\n * @return {Array|Promise|undefined} Returns the next nodes to process if available.\n * If asynchronous processing is required, it returns a Promise that resolves to the next nodes.\n * Returns undefined in case of an error during input validation or preconditions that prevent processing.\n */\n public execute() {\n if (!this.divided && !this.processing) {\n this.processing = true;\n\n const inputValidation = this.task.validateInput(\n this.isMeta() ? this.context.getMetadata() : this.context.getContext(),\n );\n if (inputValidation !== true) {\n this.onError(inputValidation.__validationErrors);\n this.postProcess();\n return this.nextNodes;\n }\n\n this.result = this.work();\n\n if (this.result instanceof Promise) {\n return this.executeAsync();\n }\n\n const nextNodes = this.postProcess();\n if (nextNodes instanceof Promise) {\n return nextNodes;\n }\n\n this.nextNodes = nextNodes;\n }\n\n return this.nextNodes;\n }\n\n /**\n * Executes an asynchronous workflow that processes a result and retries on errors.\n * The method handles different result states, checks for error properties, and invokes\n * error handling when necessary.\n *\n * @return {Promise<void>} A promise that resolves when the operation completes successfully,\n * or rejects if an unhandled error occurs.\n */\n async workAsync() {\n try {\n this.result = await this.result;\n if (\n typeof this.result === \"object\" &&\n (this.result.hasOwnProperty(\"errored\") ||\n this.result.hasOwnProperty(\"failed\"))\n ) {\n const result = await this.retryAsync((this.result as any).__error);\n if (\n typeof result === \"object\" &&\n (result.hasOwnProperty(\"errored\") || result.hasOwnProperty(\"failed\"))\n ) {\n this.onError(result.__error);\n }\n }\n } catch (e: unknown) {\n const result = await this.retryAsync(e);\n if (result === e) {\n this.onError(e);\n }\n }\n }\n\n /**\n * Executes an asynchronous operation, processes the result, and determines the next nodes to execute.\n * This method will manage asynchronous work, handle post-processing of results, and ensure proper handling of both synchronous and asynchronous next node configurations.\n *\n * @return {Promise<any>} A promise resolving to the next nodes to be executed. Can be the result of post-processing or a directly resolved next nodes object.\n */\n async executeAsync() {\n await this.workAsync();\n const nextNodes = this.postProcess();\n if (nextNodes instanceof Promise) {\n return nextNodes;\n }\n this.nextNodes = nextNodes;\n return this.nextNodes;\n }\n\n /**\n * Executes the task associated with the current instance, using the given context,\n * progress callback, and metadata. If the task fails or an error occurs, it attempts\n * to retry the execution. If the retry is not successful, it propagates the error and\n * returns the result.\n *\n * @return {TaskResult | Promise<TaskResult>} The result of the task execution, or a\n * promise that resolves to the task result. This includes handling for retries on\n * failure and error propagation.\n */\n work(): TaskResult | Promise<TaskResult> {\n try {\n const result = this.task.execute(\n this.context,\n this.emitWithMetadata.bind(this),\n this.onProgress.bind(this),\n { nodeId: this.id, routineExecId: this.routineExecId },\n );\n\n if ((result as any)?.errored || (result as any)?.failed) {\n return this.retry(result);\n }\n\n return result;\n } catch (e: unknown) {\n const result = this.retry(e);\n return result.then((result) => {\n if (result !== e) {\n return result;\n }\n\n this.onError(e);\n return this.result;\n });\n }\n }\n\n /**\n * Emits a signal along with its associated metadata. The metadata includes\n * task-specific information such as task name, version, execution ID, and\n * additional context metadata like routine execution ID and execution trace ID.\n * This method is designed to enrich emitted signals with relevant details\n * before broadcasting them.\n *\n * @param {string} signal - The name of the signal to be emitted.\n * @param {AnyObject} data - The data object to be sent along with the signal. Metadata\n * will be injected into this object before being emitted.\n * @return {void} No return value.\n */\n emitWithMetadata(signal: string, data: AnyObject) {\n if (!this.task?.isHidden) {\n data.__signalEmission = {\n fullSignalName: signal,\n taskName: this.task.name,\n taskVersion: this.task.version,\n taskExecutionId: this.id,\n routineExecutionId: this.routineExecId,\n executionTraceId: this.executionTraceId,\n isMetric: false,\n };\n data.__metadata = {\n ...data.__metadata,\n __routineExecId: this.routineExecId,\n __executionTraceId: this.executionTraceId,\n };\n }\n\n this.emit(signal, data);\n\n if (!this.task.emitsSignals.has(signal)) {\n this.task.emitsSignals.add(signal);\n }\n }\n\n /**\n * Emits metrics with additional metadata describing the task execution and context.\n *\n * @param {string} signal - The signal name being emitted.\n * @param {AnyObject} data - The data associated with the signal emission, enriched with metadata.\n * @return {void} Emits the signal with enriched data and does not return a value.\n */\n emitMetricsWithMetadata(signal: string, data: AnyObject) {\n if (!this.task?.isHidden) {\n data.__signalEmission = {\n taskName: this.task.name,\n taskVersion: this.task.version,\n taskExecutionId: this.id,\n routineExecutionId: this.routineExecId,\n executionTraceId: this.executionTraceId,\n isMetric: true,\n };\n data.__metadata = {\n ...data.__metadata,\n __routineExecId: this.routineExecId,\n __executionTraceId: this.executionTraceId,\n };\n }\n\n this.emitMetrics(signal, data);\n\n if (!this.task.emitsSignals.has(signal)) {\n this.task.emitsSignals.add(signal);\n }\n }\n\n /**\n * Updates the progress of a task and emits metrics with associated metadata.\n *\n * @param {number} progress - A number representing the progress value, which will be clamped between 0 and 1.\n * @return {void} This method does not return a value.\n */\n onProgress(progress: number) {\n progress = Math.min(Math.max(0, progress), 1);\n\n this.emitMetricsWithMetadata(\"meta.node.progress\", {\n data: {\n progress,\n },\n filter: {\n uuid: this.id,\n },\n });\n\n this.emitMetricsWithMetadata(\n `meta.node.routine_execution_progress:${this.routineExecId}`,\n {\n data: {\n progress:\n (progress * this.task.progressWeight) /\n (this.layer?.getIdenticalNodes(this).length ?? 1),\n },\n filter: {\n uuid: this.routineExecId,\n },\n },\n );\n }\n\n /**\n * Processes the result of the current operation, validates it, and determines the next set of nodes.\n *\n * This method ensures that results of certain types such as strings or arrays\n * are flagged as errors. It divides the current context into subsequent nodes\n * for further processing. If the division returns a promise, it delegates the\n * processing to `postProcessAsync`. For synchronous division, it sets the\n * `nextNodes` and finalizes the operation.\n *\n * @return {(Array|undefined)} Returns an array of next nodes for further processing,\n * or undefined if no further processing is required.\n */\n postProcess() {\n if (typeof this.result === \"string\") {\n this.onError(\n `Returning strings is not allowed. Returned: ${this.result}`,\n );\n }\n\n if (Array.isArray(this.result)) {\n this.onError(`Returning arrays is not allowed. Returned: ${this.result}`);\n }\n\n const nextNodes = this.divide();\n\n if (nextNodes instanceof Promise) {\n return this.postProcessAsync(nextNodes);\n }\n\n this.nextNodes = nextNodes;\n this.finalize();\n return this.nextNodes;\n }\n\n /**\n * Asynchronously processes and finalizes the provided graph nodes.\n *\n * @param {Promise<GraphNode[]>} nextNodes A promise that resolves to an array of graph nodes to be processed.\n * @return {Promise<GraphNode[]>} A promise that resolves to the processed array of graph nodes.\n */\n async postProcessAsync(nextNodes: Promise<GraphNode[]>) {\n this.nextNodes = await nextNodes;\n this.finalize();\n return this.nextNodes;\n }\n\n /**\n * Finalizes the current task execution by determining if the task is complete, handles any errors or failures,\n * emits relevant signals based on the task outcomes, and ensures proper end of the task lifecycle.\n *\n * @return {void} Does not return a value.\n */\n finalize() {\n if (this.nextNodes.length === 0) {\n this.completeSubgraph();\n }\n\n if (this.errored || this.failed) {\n this.task.mapOnFailSignals((signal: string) =>\n this.emitWithMetadata(signal, this.context.getFullContext()),\n );\n } else if (this.result !== undefined && this.result !== false) {\n this.task.mapSignals((signal: string) =>\n this.emitWithMetadata(signal, this.context.getFullContext()),\n );\n }\n\n this.end();\n }\n\n /**\n * Handles an error event, processes the error, and updates the state accordingly.\n *\n * @param {unknown} error - The error object or message that occurred.\n * @param {AnyObject} [errorData={}] - Additional error data to include in the result.\n * @return {void} This method does not return any value.\n */\n onError(error: unknown, errorData: AnyObject = {}) {\n this.result = {\n ...this.context.getFullContext(),\n __error: `Node error: ${error}`,\n __retries: this.retries,\n error: `Node error: ${error}`,\n errored: true,\n returnedValue: this.result,\n ...errorData,\n };\n this.migrate(this.result);\n this.errored = true;\n }\n\n /**\n * Retries a task based on the defined retry count and delay time. If the retry count is 0, it immediately resolves with the provided previous result.\n *\n * @param {any} [prevResult] - The result from a previous attempt, if any, to return when no retries are performed.\n * @return {Promise<TaskResult>} - A promise that resolves with the result of the retried task or the previous result if no retries occur.\n */\n async retry(prevResult?: any): Promise<TaskResult> {\n if (this.retryCount === 0) {\n return prevResult;\n }\n\n await this.delayRetry();\n return this.work();\n }\n\n /**\n * Retries an asynchronous operation and returns its result.\n * If the retry count is zero, the method immediately returns the provided previous result.\n *\n * @param {any} [prevResult] - The optional result from a previous operation attempt, if applicable.\n * @return {Promise<TaskResult>} A promise that resolves to the result of the retried operation.\n */\n async retryAsync(prevResult?: any): Promise<TaskResult> {\n if (this.retryCount === 0) {\n return prevResult;\n }\n\n await this.delayRetry();\n this.result = this.work();\n return this.workAsync();\n }\n\n async delayRetry() {\n this.retryCount--;\n this.retries++;\n await sleep(this.retryDelay);\n this.retryDelay *= this.task.retryDelayFactor;\n if (\n this.task.retryDelayMax > 0 &&\n this.retryDelay > this.task.retryDelayMax\n ) {\n this.retryDelay = this.task.retryDelayMax;\n }\n }\n\n /**\n * Processes the result of a task by generating new nodes based on the task output.\n * The method handles synchronous and asynchronous generators, validates task output,\n * and creates new nodes accordingly. If errors occur, the method attempts to handle them\n * by generating alternative task nodes.\n *\n * @return {GraphNode[] | Promise<GraphNode[]>} Returns an array of generated GraphNode objects\n * (synchronously or wrapped in a Promise) based on the task result, or propagates errors if validation fails.\n */\n divide(): GraphNode[] | Promise<GraphNode[]> {\n const newNodes: GraphNode[] = [];\n\n if (\n (this.result as Generator)?.next &&\n typeof (this.result as Generator).next === \"function\"\n ) {\n const generator = this.result as Generator;\n let current = generator.next();\n if (current instanceof Promise) {\n return this.divideAsync(current);\n }\n\n while (!current.done && current.value !== undefined) {\n const outputValidation = this.task.validateOutput(current.value as any);\n if (outputValidation !== true) {\n this.onError(outputValidation.__validationErrors);\n break;\n } else {\n newNodes.push(...this.generateNewNodes(current.value));\n current = generator.next();\n }\n }\n } else if (this.result !== undefined && !this.errored) {\n newNodes.push(...this.generateNewNodes(this.result));\n\n if (typeof this.result !== \"boolean\") {\n const outputValidation = this.task.validateOutput(this.result as any);\n if (outputValidation !== true) {\n this.onError(outputValidation.__validationErrors);\n }\n\n this.divided = true;\n this.migrate({\n ...this.result,\n ...this.context.getMetadata(),\n __nextNodes: newNodes.map((n) => n.id),\n __retries: this.retries,\n });\n\n return newNodes;\n }\n }\n\n if (this.errored) {\n newNodes.push(\n ...this.task.mapNext(\n (t: Task) =>\n this.clone()\n .split(uuid())\n .differentiate(t)\n .migrate({ ...(this.result as any) }),\n true,\n ),\n );\n }\n\n this.divided = true;\n this.migrate({\n ...this.context.getFullContext(),\n __nextNodes: newNodes.map((n) => n.id),\n __retries: this.retries,\n });\n\n return newNodes;\n }\n\n /**\n * Processes an asynchronous iterator result, validates its output, and generates new graph nodes accordingly.\n * Additionally, continues to process and validate results from an asynchronous generator.\n *\n * @param {Promise<IteratorResult<any>>} current - A promise resolving to the current step result from an asynchronous iterator.\n * @return {Promise<GraphNode[]>} A promise resolving to an array of generated GraphNode objects based on validated outputs.\n */\n async divideAsync(\n current: Promise<IteratorResult<any>>,\n ): Promise<GraphNode[]> {\n const nextNodes: GraphNode[] = [];\n const _current = await current;\n\n const outputValidation = this.task.validateOutput(_current.value as any);\n if (outputValidation !== true) {\n this.onError(outputValidation.__validationErrors);\n return nextNodes;\n } else {\n nextNodes.push(...this.generateNewNodes(_current.value));\n }\n\n for await (const result of this.result as AsyncGenerator<any>) {\n const outputValidation = this.task.validateOutput(result);\n if (outputValidation !== true) {\n this.onError(outputValidation.__validationErrors);\n return [];\n } else {\n nextNodes.push(...this.generateNewNodes(result));\n }\n }\n\n this.divided = true;\n\n return nextNodes;\n }\n\n /**\n * Generates new nodes based on the provided result and task configuration.\n *\n * @param {any} result - The result of the previous operation, which determines the configuration and context for new nodes. It can be a boolean or an object containing details like failure, errors, or metadata.\n * @return {GraphNode[]} An array of newly generated graph nodes configured based on the task and context.\n */\n generateNewNodes(result: any) {\n const groupId = uuid();\n const newNodes = [];\n if (typeof result !== \"boolean\") {\n const failed =\n (result.failed !== undefined && result.failed) ||\n result.error !== undefined;\n newNodes.push(\n ...(this.task.mapNext((t: Task) => {\n const context = t.isUnique\n ? {\n joinedContexts: [\n { ...result, taskName: this.task.name, __nodeId: this.id },\n ],\n ...this.context.getMetadata(),\n }\n : { ...result, ...this.context.getMetadata() };\n return this.clone().split(groupId).differentiate(t).migrate(context);\n }, failed) as GraphNode[]),\n );\n\n this.failed = failed;\n } else {\n const shouldContinue = result;\n if (shouldContinue) {\n newNodes.push(\n ...(this.task.mapNext((t: Task) => {\n const newNode = this.clone().split(groupId).differentiate(t);\n if (t.isUnique) {\n newNode.migrate({\n joinedContexts: [\n {\n ...this.context.getContext(),\n taskName: this.task.name,\n __nodeId: this.id,\n },\n ],\n ...this.context.getMetadata(),\n });\n }\n\n return newNode;\n }) as GraphNode[]),\n );\n }\n }\n\n return newNodes;\n }\n\n /**\n * Executes the differentiation process based on a given task and updates the instance properties accordingly.\n *\n * @param {Task} task - The task object containing information such as retry count, retry delay, and metadata status.\n * @return {GraphNode} The updated instance after processing the task.\n */\n differentiate(task: Task): GraphNode {\n this.task = task;\n this.retryCount = task.retryCount;\n this.retryDelay = task.retryDelay;\n this.silent =\n (task.isMeta && !this.debug) ||\n task.isSubMeta ||\n this.context?.getMetadata()?.__isSubMeta;\n return this;\n }\n\n /**\n * Migrates the current instance to a new context and returns the updated instance.\n *\n * @param {any} ctx - The context data to be used for migration.\n * @return {GraphNode} The updated instance after migration.\n */\n migrate(ctx: any): GraphNode {\n this.context = new GraphContext(ctx);\n return this;\n }\n\n /**\n * Splits the current node into a new group identified by the provided ID.\n *\n * @param {string} id - The unique identifier for the new split group.\n * @return {GraphNode} The current instance of the GraphNode with the updated split group ID.\n */\n split(id: string): GraphNode {\n this.splitGroupId = id;\n return this;\n }\n\n /**\n * Creates a new instance of the GraphNode with the current node's properties.\n * This method allows for duplicating the existing graph node.\n *\n * @return {GraphNode} A new instance of GraphNode that is a copy of the current node.\n */\n public clone(): GraphNode {\n return new GraphNode(\n this.task,\n this.context,\n this.routineExecId,\n [this],\n this.debug,\n this.verbose,\n );\n }\n\n /**\n * Consumes the given graph node by combining contexts, merging previous nodes,\n * and performing associated operations on the provided node.\n *\n * @param {GraphNode} node - The graph node to be consumed.\n * @return {void} This method does not return a value.\n */\n public consume(node: GraphNode) {\n this.context = this.context.combine(node.context);\n this.previousNodes = this.previousNodes.concat(node.previousNodes);\n node.completeSubgraph();\n node.changeIdentity(this.id);\n node.destroy();\n }\n\n /**\n * Changes the identity of the current instance by updating the `id` property.\n *\n * @param {string} id - The new identity value to be assigned.\n * @return {void} Does not return a value.\n */\n changeIdentity(id: string) {\n this.id = id;\n }\n\n /**\n * Completes the subgraph for the current node and recursively for its previous nodes\n * once all next nodes have their subgraphs marked as done. If there are no previous nodes,\n * it completes the entire graph.\n *\n * @return {void} Does not return a value.\n */\n completeSubgraph() {\n for (const node of this.nextNodes) {\n if (!node.subgraphDone()) {\n return;\n }\n }\n\n this.subgraphComplete = true;\n\n if (this.previousNodes.length === 0) {\n this.completeGraph();\n return;\n }\n\n this.previousNodes.forEach((n) => n.completeSubgraph());\n }\n\n /**\n * Completes the current graph by setting a flag indicating the graph has been completed\n * and recursively completes all subsequent nodes in the graph.\n *\n * @return {void} Does not return a value.\n */\n completeGraph() {\n this.graphComplete = true;\n this.nextNodes.forEach((n) => n.completeGraph());\n }\n\n /**\n * Destroys the current instance by releasing resources, breaking references,\n * and resetting properties to ensure proper cleanup.\n *\n * @return {void} No return value.\n */\n public destroy() {\n // @ts-ignore\n this.context = null;\n // @ts-ignore\n this.task = null;\n this.nextNodes = [];\n this.previousNodes.forEach((n) =>\n n.nextNodes.splice(n.nextNodes.indexOf(this), 1),\n );\n this.previousNodes = [];\n this.result = undefined;\n this.layer = undefined;\n this.destroyed = true;\n }\n\n /**\n * Retrieves an iterator for traversing through the graph nodes.\n *\n * @return {GraphNodeIterator} An iterator instance specific to this graph node.\n */\n public getIterator() {\n return new GraphNodeIterator(this);\n }\n\n /**\n * Applies a callback function to each node in the `nextNodes` array and returns\n * the resulting array from the map operation.\n *\n * @param {function} callback - A function to execute on each `GraphNode` in the `nextNodes` array.\n * The function receives a `GraphNode` as its argument.\n * @return {Array} The resulting array after applying the callback function to each node in `nextNodes`.\n */\n public mapNext(callback: (node: GraphNode) => any) {\n return this.nextNodes.map(callback);\n }\n\n /**\n * Accepts a visitor object and calls its visitNode method with the current instance.\n *\n * @param {GraphVisitor} visitor - The visitor instance implementing the GraphVisitor interface.\n * @return {void} This method does not return a value.\n */\n public accept(visitor: GraphVisitor) {\n visitor.visitNode(this);\n }\n\n /**\n * Exports the current object's state and returns it in a serialized format.\n * The exported object contains metadata, task details, context information, execution times, node relationships, routine execution status, and other state information.\n *\n * @return {Object} An object representing the current state.\n */\n public export() {\n return {\n __id: this.id,\n __task: this.task.export(),\n __context: this.context.export(),\n __result: this.result,\n __executionTime: this.executionTime,\n __executionStart: this.executionStart,\n __executionEnd: this.executionStart + this.executionTime,\n __nextNodes: this.nextNodes.map((node) => node.id),\n __previousNodes: this.previousNodes.map((node) => node.id),\n __routineExecId: this.routineExecId,\n __isProcessing: this.processing,\n __isMeta: this.isMeta(),\n __graphComplete: this.graphComplete,\n __failed: this.failed,\n __errored: this.errored,\n __isUnique: this.isUnique(),\n __splitGroupId: this.splitGroupId,\n __tag: this.getTag(),\n };\n }\n\n lightExport() {\n return {\n __id: this.id,\n __task: {\n __name: this.task.name,\n __version: this.task.version,\n },\n __context: this.context.export(),\n __executionTime: this.executionTime,\n __executionStart: this.executionStart,\n __nextNodes: this.nextNodes.map((node) => node.id),\n __previousNodes: this.previousNodes.map((node) => node.id),\n __routineExecId: this.routineExecId,\n __isProcessing: this.processing,\n __graphComplete: this.graphComplete,\n __isMeta: this.isMeta(),\n __failed: this.failed,\n __errored: this.errored,\n __isUnique: this.isUnique(),\n __splitGroupId: this.splitGroupId,\n __tag: this.getTag(),\n };\n }\n\n public log() {\n try {\n console.log(\n \"Node EXECUTION:\",\n this.task.name,\n JSON.stringify(this.context.getFullContext()),\n );\n } catch (e) {\n console.log(\"Node EXECUTION:\", this.task.name, \"[circular context]\");\n }\n }\n}\n","import { v4 as uuid } from \"uuid\";\nimport { deepCloneFilter } from \"../../utils/tools\";\nimport { AnyObject } from \"../../types/global\";\n\n/**\n * Represents a context object used within a graph system.\n * Contexts are essentially a container for data that is relevant to a specific task or routine.\n * They are passed down the graph and can be used to store and manipulate data during the execution process.\n * The context is divided into full context, user data, and metadata.\n * Provides methods for accessing, cloning, mutating, combining, and exporting the context data.\n */\nexport default class GraphContext {\n readonly id: string;\n readonly fullContext: AnyObject; // Raw (for internal)\n readonly userData: AnyObject; // Filtered, frozen\n readonly metadata: AnyObject; // __keys, frozen\n\n constructor(context: AnyObject) {\n if (Array.isArray(context)) {\n throw new Error(\"Array contexts not supported\"); // Per clarification\n }\n this.fullContext = context;\n this.userData = Object.fromEntries(\n Object.entries(this.fullContext).filter(([key]) => !key.startsWith(\"__\")),\n );\n this.metadata = Object.fromEntries(\n Object.entries(this.fullContext).filter(([key]) => key.startsWith(\"__\")),\n );\n this.id = uuid();\n }\n\n /**\n * Gets frozen user data (read-only, no clone).\n * @returns Frozen user context.\n */\n getContext(): AnyObject {\n return this.userData;\n }\n\n /**\n * Clones the current user context data and returns a deep-cloned copy of it.\n *\n * @return {AnyObject} A deep-cloned copy of the user context data.\n */\n getClonedContext(): AnyObject {\n return deepCloneFilter(this.userData);\n }\n\n /**\n * Gets full raw context (cloned for safety).\n * @returns Cloned full context.\n */\n getFullContext(): AnyObject {\n return this.fullContext;\n }\n\n /**\n * Creates and returns a deep-cloned version of the fullContext object.\n *\n * @return {AnyObject} A deep copy of the fullContext instance, preserving all nested structures and data.\n */\n getClonedFullContext(): AnyObject {\n return deepCloneFilter(this.fullContext);\n }\n\n /**\n * Gets frozen metadata (read-only).\n * @returns Frozen metadata object.\n */\n getMetadata(): AnyObject {\n return this.metadata;\n }\n\n /**\n * Clones this context (new instance).\n * @returns New GraphContext.\n */\n clone(): GraphContext {\n return this.mutate(this.fullContext);\n }\n\n /**\n * Creates new context from data (via registry).\n * @param context New data.\n * @returns New GraphContext.\n */\n mutate(context: AnyObject): GraphContext {\n return new GraphContext(context);\n }\n\n /**\n * Combines the current GraphContext with another GraphContext, merging their user data\n * and full context into a new GraphContext instance.\n *\n * @param {GraphContext} otherContext - The other GraphContext to combine with the current one.\n * @return {GraphContext} A new GraphContext instance containing merged data from both contexts.\n */\n combine(otherContext: GraphContext): GraphContext {\n const newUser = { ...this.userData };\n newUser.joinedContexts = this.userData.joinedContexts\n ? [...this.userData.joinedContexts]\n : [this.userData];\n\n const otherUser = otherContext.userData;\n if (Array.isArray(otherUser.joinedContexts)) {\n newUser.joinedContexts.push(...otherUser.joinedContexts);\n } else {\n newUser.joinedContexts.push(otherUser);\n }\n\n const newFull = {\n ...this.fullContext,\n ...otherContext.fullContext,\n ...newUser,\n };\n return new GraphContext(newFull);\n }\n\n /**\n * Exports the context.\n * @returns Exported object.\n */\n export(): { id: string; context: AnyObject } {\n return {\n id: this.id,\n context: this.getFullContext(),\n };\n }\n}\n","import Iterator from \"../../interfaces/Iterator\";\nimport GraphNode from \"../execution/GraphNode\";\n\n/**\n * Represents an iterator for traversing nodes in a graph structure.\n * Implements the Iterator interface and allows traversal of nodes layer by layer.\n */\nexport default class GraphNodeIterator implements Iterator {\n currentNode: GraphNode | undefined;\n currentLayer: GraphNode[] = [];\n nextLayer: GraphNode[] = [];\n index: number = 0;\n\n constructor(node: GraphNode) {\n this.currentNode = node;\n this.currentLayer = [node];\n }\n\n hasNext(): boolean {\n return !!this.currentNode;\n }\n\n next(): any {\n const nextNode = this.currentNode;\n\n if (!nextNode) {\n return undefined;\n }\n\n this.nextLayer.push(...nextNode.mapNext((n: GraphNode) => n));\n\n this.index++;\n\n if (this.index === this.currentLayer.length) {\n this.currentLayer = this.nextLayer;\n this.nextLayer = [];\n this.index = 0;\n }\n\n this.currentNode = this.currentLayer.length\n ? this.currentLayer[this.index]\n : undefined;\n\n return nextNode;\n }\n}\n","import Cadenza from \"../Cadenza\";\nimport { AnyObject } from \"../types/global\";\n\n/**\n * Abstract class representing a signal emitter.\n * Allows emitting events or signals, with the option to suppress emissions if desired.\n */\nexport default abstract class SignalEmitter {\n silent: boolean;\n\n /**\n * Constructor for signal emitters.\n * @param silent If true, suppresses all emissions (e.g., for meta-runners to avoid loops; affects all emits).\n */\n constructor(silent: boolean = false) {\n this.silent = silent;\n }\n\n /**\n * Emits a signal via the broker.\n * @param signal The signal name.\n * @param data Optional payload (defaults to empty object).\n */\n emit(signal: string, data: AnyObject = {}): void {\n Cadenza.broker.emit(signal, data);\n }\n\n /**\n * Emits a signal via the broker if not silent.\n * @param signal The signal name.\n * @param data Optional payload (defaults to empty object).\n */\n emitMetrics(signal: string, data: AnyObject = {}): void {\n if (this.silent) {\n return;\n }\n Cadenza.broker.emit(signal, data);\n }\n}\n","/**\n * Pauses the execution of the program for the specified duration.\n *\n * @param {number} ms - The number of milliseconds to pause execution.\n * @return {Promise<void>} A promise that resolves after the specified duration has elapsed.\n */\nexport function sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import Task from \"./Task\";\nimport Cadenza from \"../../Cadenza\";\nimport SignalEmitter from \"../../interfaces/SignalEmitter\";\n\n/**\n * Represents a routine in a graph structure with tasks and signal observation capabilities.\n * Routines are named entrypoint for a sub-graph, describing the purpose for the subsequent flow.\n * Since Task names are specific to the task it performs, it doesn't describe the overall flow.\n * Routines, therefore are used to assign names to sub-flows that can be referenced using that name instead of the name of the task(s).\n * Extends SignalEmitter to emit and handle signals related to the routine's lifecycle and tasks.\n */\nexport default class GraphRoutine extends SignalEmitter {\n readonly name: string;\n version: number = 1;\n readonly description: string;\n readonly isMeta: boolean = false;\n tasks: Set<Task> = new Set();\n registered: boolean = false;\n\n observedSignals: Set<string> = new Set();\n\n constructor(\n name: string,\n tasks: Task[],\n description: string,\n isMeta: boolean = false,\n ) {\n super();\n this.name = name;\n this.description = description;\n this.isMeta = isMeta;\n this.emit(\"meta.routine.created\", {\n data: {\n name: this.name,\n version: this.version,\n description: this.description,\n isMeta: this.isMeta,\n },\n routineInstance: this,\n });\n tasks.forEach((t) => {\n this.tasks.add(t);\n\n const tasks = t.getIterator();\n\n while (tasks.hasNext()) {\n const task = tasks.next();\n if (!task) break;\n this.emit(\"meta.routine.task_added\", {\n data: {\n taskName: task.name,\n taskVersion: task.version,\n routineName: this.name,\n routineVersion: this.version,\n },\n });\n }\n });\n }\n\n /**\n * Iterates over each task in the `tasks` collection and applies the provided callback function.\n * If the callback returns a Promise, resolves all Promises concurrently.\n *\n * @param {function} callBack - A function to be executed on each task from the `tasks` collection.\n * The callback receives the current task as its argument.\n * @return {Promise<void>} A Promise that resolves once all callback executions, including asynchronous ones, are complete.\n */\n public async forEachTask(callBack: (task: Task) => any): Promise<void> {\n const promises = [];\n for (const task of this.tasks) {\n const res = callBack(task);\n if (res instanceof Promise) promises.push(res);\n }\n await Promise.all(promises);\n }\n\n /**\n * Sets global Version.\n * @param version The Version.\n */\n public setVersion(version: number): void {\n this.version = version;\n this.emit(\"meta.routine.global_version_set\", { version: this.version });\n }\n\n /**\n * Subscribes the current instance to the specified signals, enabling it to observe them.\n *\n * @param {...string} signals - The names of the signals to observe.\n * @return {this} Returns the instance to allow for method chaining.\n */\n doOn(...signals: string[]): this {\n signals.forEach((signal) => {\n if (this.observedSignals.has(signal)) return;\n Cadenza.broker.observe(signal, this as any);\n this.observedSignals.add(signal);\n });\n return this;\n }\n\n /**\n * Unsubscribes from all observed signals and clears the internal collection\n * of observed signals. This ensures that the instance is no longer listening\n * or reacting to any previously subscribed signals.\n *\n * @return {this} Returns the current instance for chaining purposes.\n */\n unsubscribeAll(): this {\n this.observedSignals.forEach((signal) =>\n Cadenza.broker.unsubscribe(signal, this as any),\n );\n this.observedSignals.clear();\n return this;\n }\n\n /**\n * Unsubscribes the current instance from the specified signals.\n *\n * @param {...string} signals - The signals to unsubscribe from.\n * @return {this} The current instance for method chaining.\n */\n unsubscribe(...signals: string[]): this {\n signals.forEach((signal) => {\n if (this.observedSignals.has(signal)) {\n Cadenza.broker.unsubscribe(signal, this as any);\n this.observedSignals.delete(signal);\n }\n });\n return this;\n }\n\n /**\n * Cleans up resources and emits an event indicating the destruction of the routine.\n *\n * This method unsubscribes from all events, clears the tasks list,\n * and emits a \"meta.routine.destroyed\" event with details of the destruction.\n *\n * @return {void}\n */\n public destroy(): void {\n this.unsubscribeAll();\n this.tasks.clear();\n this.emit(\"meta.routine.destroyed\", {\n data: { deleted: true },\n filter: { name: this.name, version: this.version },\n });\n }\n}\n","import { v4 as uuid } from \"uuid\";\nimport GraphContext from \"../context/GraphContext\";\nimport GraphVisitor from \"../../interfaces/GraphVisitor\";\nimport TaskIterator from \"../iterators/TaskIterator\";\nimport Graph from \"../../interfaces/Graph\";\nimport { AnyObject } from \"../../types/global\";\nimport { SchemaDefinition } from \"../../types/schema\";\nimport SignalEmitter from \"../../interfaces/SignalEmitter\";\nimport Cadenza from \"../../Cadenza\";\n\nexport type TaskFunction = (\n context: AnyObject,\n emit: (signal: string, context: AnyObject) => void,\n progressCallback: (progress: number) => void,\n) => TaskResult;\nexport type TaskResult = boolean | AnyObject | Generator | Promise<any> | void;\nexport type ThrottleTagGetter = (context?: AnyObject, task?: Task) => string;\n\n/**\n * Represents a task with a specific behavior, configuration, and lifecycle management.\n * Tasks are used to define units of work that can be executed and orchestrated.\n * Tasks can specify input/output validation, concurrency, retry policies, and more.\n * This class extends SignalEmitter and implements Graph, allowing tasks to emit and observe signals.\n */\nexport default class Task extends SignalEmitter implements Graph {\n readonly name: string;\n readonly description: string;\n version: number = 1;\n concurrency: number;\n timeout: number;\n readonly isMeta: boolean = false;\n readonly isSubMeta: boolean = false;\n readonly isHidden: boolean = false;\n readonly isUnique: boolean = false;\n readonly throttled: boolean = false;\n\n readonly isSignal: boolean = false;\n readonly isDeputy: boolean = false;\n readonly isEphemeral: boolean = false;\n readonly isDebounce: boolean = false;\n\n inputContextSchema: SchemaDefinition | undefined = undefined;\n validateInputContext: boolean = false;\n outputContextSchema: SchemaDefinition | undefined = undefined;\n validateOutputContext: boolean = false;\n\n readonly retryCount: number = 0;\n readonly retryDelay: number = 0;\n readonly retryDelayMax: number = 0;\n readonly retryDelayFactor: number = 1;\n\n layerIndex: number = 0;\n progressWeight: number = 0;\n nextTasks: Set<Task> = new Set();\n onFailTasks: Set<Task> = new Set();\n predecessorTasks: Set<Task> = new Set();\n destroyed: boolean = false;\n register: boolean = true;\n registered: boolean = false;\n registeredSignals: Set<string> = new Set();\n taskMapRegistration: Set<string> = new Set();\n\n emitsSignals: Set<string> = new Set();\n signalsToEmitAfter: Set<string> = new Set();\n signalsToEmitOnFail: Set<string> = new Set();\n observedSignals: Set<string> = new Set();\n\n readonly taskFunction: TaskFunction;\n\n /**\n * Constructs an instance of the task with the specified properties and configuration options.\n *\n * @param {string} name - The name of the task.\n * @param {TaskFunction} task - The function that represents the task logic.\n * @param {string} [description=\"\"] - A description of the task.\n * @param {number} [concurrency=0] - The number of concurrent executions allowed for the task.\n * @param {number} [timeout=0] - The maximum execution time for the task in milliseconds.\n * @param {boolean} [register=true] - Indicates if the task should be registered or not.\n * @param {boolean} [isUnique=false] - Specifies if the task should only allow one instance to exist at any time.\n * @param {boolean} [isMeta=false] - Indicates if the task is a meta-task.\n * @param {boolean} [isSubMeta=false] - Indicates if the task is a sub-meta-task.\n * @param {boolean} [isHidden=false] - Determines if the task is hidden and not exposed publicly.\n * @param {ThrottleTagGetter} [getTagCallback=undefined] - A callback to generate a throttle tag for the task.\n * @param {SchemaDefinition} [inputSchema=undefined] - The input schema for validating the task's input context.\n * @param {boolean} [validateInputContext=false] - Specifies if the input context should be validated against the input schema.\n * @param {SchemaDefinition} [outputSchema=undefined] - The output schema for validating the task's output context.\n * @param {boolean} [validateOutputContext=false] - Specifies if the output context should be validated against the output schema.\n * @param {number} [retryCount=0] - The number of retry attempts allowed for the task in case of failure.\n * @param {number} [retryDelay=0] - The initial delay (in milliseconds) between retry attempts.\n * @param {number} [retryDelayMax=0] - The maximum delay (in milliseconds) allowed between retries.\n * @param {number} [retryDelayFactor=1] - The factor by which the retry delay increases after each attempt.\n */\n constructor(\n name: string,\n task: TaskFunction,\n description: string = \"\",\n concurrency: number = 0,\n timeout: number = 0,\n register: boolean = true,\n isUnique: boolean = false,\n isMeta: boolean = false,\n isSubMeta: boolean = false,\n isHidden: boolean = false,\n getTagCallback: ThrottleTagGetter | undefined = undefined,\n inputSchema: SchemaDefinition | undefined = undefined,\n validateInputContext: boolean = false,\n outputSchema: SchemaDefinition | undefined = undefined,\n validateOutputContext: boolean = false,\n retryCount: number = 0,\n retryDelay: number = 0,\n retryDelayMax: number = 0,\n retryDelayFactor: number = 1,\n ) {\n super(isSubMeta || isHidden);\n this.name = name;\n this.taskFunction = task;\n this.description = description;\n this.concurrency = concurrency;\n this.timeout = timeout;\n this.isUnique = isUnique;\n this.isMeta = isMeta;\n this.isSubMeta = isSubMeta;\n this.isHidden = isHidden;\n this.inputContextSchema = inputSchema;\n this.validateInputContext = validateInputContext;\n this.outputContextSchema = outputSchema;\n this.validateOutputContext = validateOutputContext;\n this.retryCount = retryCount;\n this.retryDelay = retryDelay;\n this.retryDelayMax = retryDelayMax;\n this.retryDelayFactor = retryDelayFactor;\n this.register = register;\n\n if (getTagCallback) {\n this.getTag = (context?: AnyObject) => getTagCallback(context, this);\n this.throttled = true;\n }\n\n if (register && !this.isHidden) {\n const { __functionString, __getTagCallback } = this.export();\n this.emitWithMetadata(\"meta.task.created\", {\n data: {\n name: this.name,\n version: this.version,\n description: this.description,\n functionString: __functionString,\n tagIdGetter: __getTagCallback,\n layerIndex: this.layerIndex,\n concurrency: this.concurrency,\n retryCount: this.retryCount,\n retryDelay: this.retryDelay,\n retryDelayMax: this.retryDelayMax,\n retryDelayFactor: this.retryDelayFactor,\n timeout: this.timeout,\n isUnique: this.isUnique,\n isSignal: this.isSignal,\n isThrottled: this.throttled,\n isDebounce: this.isDebounce,\n isEphemeral: this.isEphemeral,\n isMeta: this.isMeta,\n isSubMeta: this.isSubMeta,\n validateInputContext: this.validateInputContext,\n validateOutputContext: this.validateOutputContext,\n // inputContextSchemaId: this.inputContextSchema,\n // outputContextSchemaId: this.outputContextSchema,\n },\n taskInstance: this,\n __isSubMeta: this.isSubMeta,\n });\n }\n }\n\n clone(traverse: boolean = false, includeSignals: boolean = false) {\n const clonedTask = new Task(\n `${this.name} (clone ${uuid().slice(0, 8)})`,\n this.taskFunction,\n this.description,\n this.concurrency,\n this.timeout,\n this.register,\n this.isUnique,\n this.isMeta,\n this.isSubMeta,\n this.isHidden,\n this.getTag,\n this.inputContextSchema,\n this.validateInputContext,\n this.outputContextSchema,\n this.validateOutputContext,\n this.retryCount,\n this.retryDelay,\n this.retryDelayMax,\n this.retryDelayFactor,\n );\n\n if (includeSignals) {\n clonedTask.doOn(...this.observedSignals);\n clonedTask.emits(...this.signalsToEmitAfter);\n clonedTask.emitsOnFail(...this.signalsToEmitOnFail);\n clonedTask.emitsSignals = new Set(Array.from(this.emitsSignals));\n }\n\n if (traverse) {\n this.mapNext((t: Task) => {\n clonedTask.then(t.clone(traverse, includeSignals));\n });\n }\n\n return clonedTask;\n }\n\n /**\n * Retrieves the tag associated with the instance.\n * Can be overridden by subclasses.\n *\n * @param {AnyObject} [context] - Optional context parameter that can be provided.\n * @return {string} The tag value of the instance.\n */\n public getTag(context?: AnyObject): string {\n return this.name;\n }\n\n public setVersion(version: number): void {\n this.version = version;\n this.emitWithMetadata(\"meta.task.version_set\", {\n __version: this.version,\n });\n }\n\n public setTimeout(timeout: number): void {\n this.timeout = timeout;\n }\n\n public setConcurrency(concurrency: number): void {\n this.concurrency = concurrency;\n }\n\n public setProgressWeight(weight: number): void {\n this.progressWeight = weight;\n }\n\n public setInputContextSchema(schema: SchemaDefinition): void {\n this.inputContextSchema = schema;\n }\n\n public setOutputContextSchema(schema: SchemaDefinition): void {\n this.outputContextSchema = schema;\n }\n\n public setValidateInputContext(value: boolean): void {\n this.validateInputContext = value;\n }\n\n public setValidateOutputContext(value: boolean): void {\n this.validateOutputContext = value;\n }\n\n /**\n * Emits a signal along with metadata if certain conditions are met.\n *\n * This method sends a signal with optional context data and adds metadata\n * to the emitted data if the instance is not hidden and not a subordinate metadata object.\n *\n * @param {string} signal - The name of the signal to emit.\n * @param {AnyObject} [ctx={}] - Additional context data to include with the emitted signal.\n * @return {void} Does not return a value.\n */\n emitWithMetadata(signal: string, ctx: AnyObject = {}) {\n const data = { ...ctx };\n if (!this.isHidden && !this.isSubMeta) {\n data.__signalEmission = {\n taskName: this.name,\n taskVersion: this.version,\n isMetric: false,\n };\n }\n\n this.emit(signal, data);\n }\n\n /**\n * Emits metrics with additional metadata enhancement based on the context and the state of the instance.\n * This is used to prevent loops on the meta layer in debug mode.\n *\n * @param {string} signal - The signal identifier for the metric being emitted.\n * @param {AnyObject} [ctx={}] - Optional context object to provide additional information with the metric.\n * @return {void} This method does not return any value.\n */\n emitMetricsWithMetadata(signal: string, ctx: AnyObject = {}) {\n const data = { ...ctx };\n if (!this.isHidden && !this.isSubMeta) {\n data.__signalEmission = {\n taskName: this.name,\n taskVersion: this.version,\n isMetric: true,\n };\n }\n\n this.emitMetrics(signal, data);\n }\n\n /**\n * Validates a data object against a specified schema definition and returns validation results.\n *\n * @param {any} data - The target object to validate against the schema.\n * @param {SchemaDefinition | undefined} schema - The schema definition describing the expected structure and constraints of the data.\n * @param {string} [path=\"context\"] - The base path or context for traversing the data, used in generating error messages.\n * @return {{ valid: boolean, errors: Record<string, string> }} - An object containing a validity flag (`valid`)\n * and a map (`errors`) of validation error messages keyed by property paths.\n */\n validateSchema(\n data: any,\n schema: SchemaDefinition | undefined,\n path: string = \"context\",\n ): { valid: boolean; errors: Record<string, string> } {\n const errors: Record<string, string> = {};\n\n if (!schema || typeof schema !== \"object\") return { valid: true, errors };\n\n // Check required fields\n const required = schema.required || [];\n for (const key of required) {\n if (!(key in data)) {\n errors[`${path}.${key}`] = `Required field '${key}' is missing`;\n }\n }\n\n // Validate defined properties (ignore extras)\n const properties = schema.properties || {};\n for (const [key, value] of Object.entries(data)) {\n if (key in properties) {\n const prop = properties[key];\n const propType = prop.type;\n\n if (propType === \"any\") {\n continue;\n }\n\n if ((value === undefined || value === null) && !prop.strict) {\n continue;\n }\n\n if (propType === \"string\" && typeof value !== \"string\") {\n errors[`${path}.${key}`] =\n `Expected 'string' for '${key}', got '${typeof value}'`;\n } else if (propType === \"number\" && typeof value !== \"number\") {\n errors[`${path}.${key}`] =\n `Expected 'number' for '${key}', got '${typeof value}'`;\n } else if (propType === \"boolean\" && typeof value !== \"boolean\") {\n errors[`${path}.${key}`] =\n `Expected 'boolean' for '${key}', got '${typeof value}'`;\n } else if (propType === \"array\" && !Array.isArray(value)) {\n errors[`${path}.${key}`] =\n `Expected 'array' for '${key}', got '${typeof value}'`;\n } else if (\n propType === \"object\" &&\n (typeof value !== \"object\" || value === null || Array.isArray(value))\n ) {\n errors[`${path}.${key}`] =\n `Expected 'object' for '${key}', got '${typeof value}'`;\n } else if (propType === \"array\" && prop.items) {\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n const subValidation = this.validateSchema(\n item,\n prop.items,\n `${path}.${key}[${index}]`,\n );\n if (!subValidation.valid) {\n Object.assign(errors, subValidation.errors);\n }\n });\n }\n } else if (\n propType === \"object\" &&\n !Array.isArray(value) &&\n value !== null\n ) {\n const subValidation = this.validateSchema(\n value,\n prop,\n `${path}.${key}`,\n );\n if (!subValidation.valid) {\n Object.assign(errors, subValidation.errors);\n }\n }\n\n // Check constraints (extended as discussed)\n const constraints = prop.constraints || {};\n if (typeof value === \"string\") {\n if (constraints.minLength && value.length < constraints.minLength) {\n errors[`${path}.${key}`] =\n `String '${key}' shorter than minLength ${constraints.minLength}`;\n }\n if (constraints.maxLength && value.length > constraints.maxLength) {\n errors[`${path}.${key}`] =\n `String '${key}' exceeds maxLength ${constraints.maxLength}`;\n }\n if (\n constraints.pattern &&\n !new RegExp(constraints.pattern).test(value)\n ) {\n errors[`${path}.${key}`] =\n `String '${key}' does not match pattern ${constraints.pattern}`;\n }\n } else if (typeof value === \"number\") {\n if (constraints.min && value < constraints.min) {\n errors[`${path}.${key}`] =\n `Number '${key}' below min ${constraints.min}`;\n }\n if (constraints.max && value > constraints.max) {\n errors[`${path}.${key}`] =\n `Number '${key}' exceeds max ${constraints.max}`;\n }\n if (constraints.multipleOf && value % constraints.multipleOf !== 0) {\n errors[`${path}.${key}`] =\n `Number '${key}' not multiple of ${constraints.multipleOf}`;\n }\n } else if (constraints.enum && !constraints.enum.includes(value)) {\n errors[`${path}.${key}`] =\n `Value '${value}' for '${key}' not in enum ${JSON.stringify(constraints.enum)}`;\n } else if (constraints.format) {\n const formats = {\n email: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/,\n url: /^(https?|ftp):\\/\\/[^\\s/$.?#].[^\\s]*$/,\n \"date-time\":\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})?$/,\n uuid: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n custom: /.*/, // Placeholder; override with prop.constraints.pattern if present\n } as any;\n const regex =\n formats[constraints.format] ||\n new RegExp(constraints.pattern || \".*\");\n if (typeof value === \"string\" && !regex.test(value)) {\n errors[`${path}.${key}`] =\n `Value '${value}' for '${key}' does not match format '${constraints.format}'`;\n }\n } else if (constraints.oneOf && !constraints.oneOf.includes(value)) {\n errors[`${path}.${key}`] =\n `Value '${value}' for '${key}' not in oneOf ${JSON.stringify(constraints.oneOf)}`;\n }\n } else if (schema.strict) {\n errors[`${path}.${key}`] = `Key '${key}' is not allowed`;\n }\n }\n\n if (Object.keys(errors).length > 0) {\n return { valid: false, errors };\n }\n return { valid: true, errors: {} };\n }\n\n /**\n * Validates the input context against the predefined schema and emits metadata if validation fails.\n *\n * @param {AnyObject} context - The input context to validate.\n * @return {true | AnyObject} - Returns `true` if validation succeeds, otherwise returns an error object containing details of the validation failure.\n */\n public validateInput(context: AnyObject): true | AnyObject {\n if (this.validateInputContext) {\n const validationResult = this.validateSchema(\n context,\n this.inputContextSchema,\n );\n if (!validationResult.valid) {\n this.emitWithMetadata(\"meta.task.input_validation_failed\", {\n __taskName: this.name,\n __taskVersion: this.version,\n __context: context,\n __errors: validationResult.errors,\n });\n return {\n errored: true,\n __error: \"Input context validation failed\",\n __validationErrors: JSON.stringify(validationResult.errors),\n };\n }\n }\n return true;\n }\n\n /**\n * Validates the output context using the provided schema and emits metadata if validation fails.\n *\n * @param {AnyObject} context - The output context to validate.\n * @return {true | AnyObject} Returns `true` if the output context is valid; otherwise, returns an object\n * containing error information when validation fails.\n */\n public validateOutput(context: AnyObject): true | AnyObject {\n if (this.validateOutputContext) {\n const validationResult = this.validateSchema(\n context,\n this.outputContextSchema,\n );\n if (!validationResult.valid) {\n this.emitWithMetadata(\"meta.task.output_validation_failed\", {\n __taskName: this.name,\n __taskVersion: this.version,\n __result: context,\n __errors: validationResult.errors,\n });\n return {\n errored: true,\n __error: \"Output context validation failed\",\n __validationErrors: JSON.stringify(validationResult.errors),\n };\n }\n }\n return true;\n }\n\n /**\n * Executes a task within a given context, optionally emitting signals and reporting progress.\n *\n * @param {GraphContext} context The execution context which provides data and functions necessary for the task.\n * @param {function(string, AnyObject): void} emit A function to emit signals and communicate intermediate results or states.\n * @param {function(number): void} progressCallback A callback function used to report task progress as a percentage (0 to 100).\n * @param {{ nodeId: string; routineExecId: string }} nodeData An object containing identifiers related to the node and execution routine.\n * @return {TaskResult} The result of the executed task.\n */\n public execute(\n context: GraphContext,\n emit: (signal: string, context: AnyObject) => void,\n progressCallback: (progress: number) => void,\n nodeData: { nodeId: string; routineExecId: string },\n ): TaskResult {\n return this.taskFunction(\n this.isMeta ? context.getClonedFullContext() : context.getClonedContext(),\n emit,\n progressCallback,\n );\n }\n\n /**\n * Adds tasks as predecessors to the current task and establishes dependencies between them.\n * Ensures that adding predecessors does not create cyclic dependencies.\n * Updates task relationships, progress weights, and emits relevant metrics after operations.\n *\n * @param {Task[]} tasks - An array of tasks to be added as predecessors to the current task.\n * @return {this} The current task instance for method chaining.\n * @throws {Error} Throws an error if adding a predecessor creates a cycle in the task structure.\n */\n public doAfter(...tasks: Task[]): this {\n for (const pred of tasks) {\n if (this.predecessorTasks.has(pred)) continue;\n\n pred.nextTasks.add(this);\n this.predecessorTasks.add(pred);\n this.updateLayerFromPredecessors();\n\n if (this.hasCycle()) {\n this.decouple(pred);\n throw new Error(`Cycle adding pred ${pred.name} to ${this.name}`);\n }\n\n this.emitMetricsWithMetadata(\"meta.task.relationship_added\", {\n data: {\n taskName: this.name,\n taskVersion: this.version,\n predecessorTaskName: pred.name,\n predecessorTaskVersion: pred.version,\n },\n });\n }\n\n this.updateProgressWeights();\n return this;\n }\n\n /**\n * Adds a sequence of tasks as successors to the current task, ensuring no cyclic dependencies are introduced.\n * Metrics are emitted when a relationship is successfully added.\n *\n * @param {...Task} tasks - The tasks to be added as successors to the current task.\n * @return {this} Returns the current task instance for method chaining.\n * @throws {Error} Throws an error if adding a task causes a cyclic dependency.\n */\n public then(...tasks: Task[]): this {\n for (const next of tasks) {\n if (this.nextTasks.has(next)) continue;\n\n this.nextTasks.add(next);\n next.predecessorTasks.add(this);\n next.updateLayerFromPredecessors();\n\n if (next.hasCycle()) {\n this.decouple(next);\n throw new Error(`Cycle adding next ${next.name} to ${this.name}`);\n }\n\n this.emitMetricsWithMetadata(\"meta.task.relationship_added\", {\n data: {\n taskName: next.name,\n taskVersion: next.version,\n predecessorTaskName: this.name,\n predecessorTaskVersion: this.version,\n },\n });\n }\n\n this.updateProgressWeights();\n return this;\n }\n\n /**\n * Decouples the current task from the provided task by removing mutual references.\n *\n * @param {Task} task - The task to decouple from the current task.\n * @return {void} This method does not return a value.\n */\n public decouple(task: Task): void {\n if (task.nextTasks.has(this)) {\n task.nextTasks.delete(this);\n this.predecessorTasks.delete(task);\n }\n\n if (task.onFailTasks.has(this)) {\n task.onFailTasks.delete(this);\n this.predecessorTasks.delete(task);\n }\n\n // TODO: Delete task map instances\n\n this.updateLayerFromPredecessors();\n }\n\n /**\n * Updates the progress weights for tasks within each layer of the subgraph.\n * The progress weight for each task is calculated based on the inverse proportion\n * of the number of layers and the number of tasks in each layer. This ensures an\n * even distribution of progress weight across the tasks in the layers.\n *\n * @return {void} Does not return a value.\n */\n updateProgressWeights(): void {\n const layers = this.getSubgraphLayers();\n const numLayers = layers.size;\n if (numLayers === 0) return;\n\n const weightPerLayer = 1 / numLayers;\n\n layers.forEach((tasksInLayer) => {\n const numTasks = tasksInLayer.size;\n if (numTasks === 0) return;\n tasksInLayer.forEach(\n (task) => (task.progressWeight = weightPerLayer / numTasks),\n );\n });\n }\n\n /**\n * Retrieves a mapping of layer indices to sets of tasks within each layer of a subgraph.\n * This method traverses the task dependencies and organizes tasks by their respective layer indices.\n *\n * @return {Map<number, Set<Task>>} A map where the key is the layer index (number) and the value is a set of tasks (Set<Task>) belonging to that layer.\n */\n getSubgraphLayers(): Map<number, Set<Task>> {\n const layers = new Map<number, Set<Task>>();\n const queue = [this as Task];\n const visited = new Set<Task>();\n\n while (queue.length) {\n const task = queue.shift()!;\n if (visited.has(task)) continue;\n visited.add(task);\n\n if (!layers.has(task.layerIndex)) layers.set(task.layerIndex, new Set());\n layers.get(task.layerIndex)!.add(task);\n\n task.nextTasks.forEach((next) => queue.push(next));\n }\n\n return layers;\n }\n\n /**\n * Updates the `layerIndex` of the current task based on the maximum layer index of its predecessors\n * and propagates the update recursively to all subsequent tasks. If the `layerIndex` changes,\n * emits a metric event with metadata about the change.\n *\n * @return {void} This method does not return a value.\n */\n updateLayerFromPredecessors(): void {\n const prevLayerIndex = this.layerIndex;\n let maxPred = 0;\n this.predecessorTasks.forEach(\n (pred) => (maxPred = Math.max(maxPred, pred.layerIndex)),\n );\n this.layerIndex = maxPred + 1;\n\n if (prevLayerIndex !== this.layerIndex) {\n this.emitMetricsWithMetadata(\"meta.task.layer_index_changed\", {\n data: {\n layerIndex: this.layerIndex,\n },\n filter: { name: this.name, version: this.version },\n });\n }\n\n const queue = Array.from(this.nextTasks);\n while (queue.length) {\n const next = queue.shift()!;\n next.updateLayerFromPredecessors();\n next.nextTasks.forEach((n) => queue.push(n));\n }\n }\n\n /**\n * Determines whether there is a cycle in the tasks graph.\n * This method performs a depth-first search (DFS) to detect cycles.\n *\n * @return {boolean} - Returns true if a cycle is found in the graph, otherwise false.\n */\n hasCycle(): boolean {\n const visited = new Set<Task>();\n const recStack = new Set<Task>();\n\n const dfs = (task: Task): boolean => {\n if (recStack.has(task)) return true;\n if (visited.has(task)) return false;\n\n visited.add(task);\n recStack.add(task);\n\n for (const next of task.nextTasks) {\n if (dfs(next)) return true;\n }\n\n recStack.delete(task);\n return false;\n };\n\n return dfs(this);\n }\n\n /**\n * Maps over the next set of tasks or failed tasks if specified, applying the provided callback function.\n *\n * @param {Function} callback A function that will be called with each task, transforming the task as needed. It receives a single parameter of type Task.\n * @param {boolean} [failed=false] A boolean that determines whether to map over the failed tasks (true) or the next tasks (false).\n * @return {any[]} An array of transformed tasks resulting from applying the callback function.\n */\n public mapNext(\n callback: (task: Task) => any,\n failed: boolean = false,\n ): any[] {\n const tasks = failed\n ? Array.from(this.onFailTasks)\n : Array.from(this.nextTasks);\n return tasks.map(callback);\n }\n\n /**\n * Maps through each task in the set of predecessor tasks and applies the provided callback function.\n *\n * @param {function} callback - A function to execute on each task in the predecessor tasks. The function receives a `Task` object as its argument and returns any value.\n * @return {any[]} An array containing the results of applying the callback function to each predecessor task.\n */\n public mapPrevious(callback: (task: Task) => any): any[] {\n return Array.from(this.predecessorTasks).map(callback);\n }\n\n /**\n * Adds the specified signals to the current instance, making it observe them.\n * If the instance is already observing a signal, it will be skipped.\n * The method also emits metadata information if the `register` property is set.\n *\n * @param {...string[]} signals - The array of signal names to observe.\n * @return {this} The current instance after adding the specified signals.\n */\n doOn(...signals: string[]): this {\n signals.forEach((signal) => {\n if (this.observedSignals.has(signal)) return;\n if (this.emitsSignals.has(signal))\n throw new Error(\n `Detected signal loop for task ${this.name}. Signal name: ${signal}`,\n );\n Cadenza.broker.observe(signal, this as any);\n this.observedSignals.add(signal);\n if (this.register) {\n this.emitWithMetadata(\"meta.task.observed_signal\", {\n data: {\n signalName: signal.split(\":\")[0],\n taskName: this.name,\n taskVersion: this.version,\n },\n });\n }\n });\n return this;\n }\n\n /**\n * Registers the specified signals to be emitted after the Task executes successfully and attaches them for further processing.\n *\n * @param {...string} signals - The list of signals to be registered for emission.\n * @return {this} The current instance for method chaining.\n */\n emits(...signals: string[]): this {\n signals.forEach((signal) => {\n if (this.observedSignals.has(signal))\n throw new Error(\n `Detected signal loop for task ${this.name}. Signal name: ${signal}`,\n );\n this.signalsToEmitAfter.add(signal);\n this.attachSignal(signal);\n });\n return this;\n }\n\n /**\n * Configures the instance to emit specified signals when the task execution fails.\n * A failure is defined as anything that does not return a successful result.\n *\n * @param {...string} signals - The names of the signals to emit upon failure.\n * @return {this} Returns the current instance for chaining.\n */\n emitsOnFail(...signals: string[]): this {\n signals.forEach((signal) => {\n this.signalsToEmitOnFail.add(signal);\n this.attachSignal(signal, true);\n });\n return this;\n }\n\n /**\n * Attaches a signal to the current context and emits metadata if the register flag is set.\n *\n * @param {string} signal - The name of the signal to attach.\n * @param {boolean} [isOnFail=false] - Indicates if the signal should be marked as \"on fail\".\n * @return {void} This method does not return a value.\n */\n attachSignal(signal: string, isOnFail: boolean = false) {\n this.emitsSignals.add(signal);\n if (this.register) {\n this.emitWithMetadata(\"meta.task.attached_signal\", {\n data: {\n signalName: signal.split(\":\")[0],\n taskName: this.name,\n taskVersion: this.version,\n isOnFail,\n },\n });\n }\n }\n\n /**\n * Unsubscribes the current instance from the specified signals.\n * This method removes the signals from the observedSignals set, unsubscribes\n * from the underlying broker, and emits metadata for the unsubscription if applicable.\n *\n * @param {string[]} signals - The list of signal names to unsubscribe from.\n * @return {this} Returns the current instance for method chaining.\n */\n unsubscribe(...signals: string[]): this {\n signals.forEach((signal) => {\n if (this.observedSignals.has(signal)) {\n Cadenza.broker.unsubscribe(signal, this as any);\n this.observedSignals.delete(signal);\n\n if (this.register) {\n signal = signal.split(\":\")[0];\n this.emitWithMetadata(\"meta.task.unsubscribed_signal\", {\n filter: {\n signalName: signal,\n taskName: this.name,\n taskVersion: this.version,\n },\n });\n }\n }\n });\n return this;\n }\n\n /**\n * Unsubscribes from all currently observed signals and clears the list of observed signals.\n *\n * @return {this} The instance of the class to allow method chaining.\n */\n unsubscribeAll(): this {\n this.unsubscribe(...this.observedSignals);\n this.observedSignals.clear();\n return this;\n }\n\n /**\n * Detaches the specified signals from being emitted after execution and optionally emits metadata for each detached signal.\n *\n * @param {...string} signals - The list of signal names to be detached. Signals can be in the format \"namespace:signalName\".\n * @return {this} Returns the current instance of the object for method chaining.\n */\n detachSignals(...signals: string[]): this {\n signals.forEach((signal) => {\n this.signalsToEmitAfter.delete(signal);\n if (this.register) {\n signal = signal.split(\":\")[0];\n this.emitWithMetadata(\"meta.task.detached_signal\", {\n filter: {\n signalName: signal,\n taskName: this.name,\n taskVersion: this.version,\n },\n });\n }\n });\n return this;\n }\n\n /**\n * Detaches all signals associated with the object by invoking the `detachSignals` method\n * and clearing the `signalsToEmitAfter` collection.\n *\n * @return {this} Returns the current instance to allow method chaining.\n */\n detachAllSignals(): this {\n this.detachSignals(...this.signalsToEmitAfter);\n this.signalsToEmitAfter.clear();\n return this;\n }\n\n /**\n * Maps over the signals in the `signalsToEmitAfter` set and applies a callback function to each signal.\n *\n * @param {function(string): void} callback - A function that is called with each signal\n * in the `signalsToEmitAfter` set, providing the signal as an argument.\n * @return {Array<any>} An array containing the results of applying the callback\n * function to each signal.\n */\n mapSignals(callback: (signal: string) => void) {\n return Array.from(this.signalsToEmitAfter).map(callback);\n }\n\n /**\n * Maps over the signals in `signalsToEmitOnFail` and applies the provided callback to each signal.\n *\n * @param {function(string): void} callback - A function that receives each signal as a string and performs an operation or transformation on it.\n * @return {Array} The array resulting from applying the callback to each signal in `signalsToEmitOnFail`.\n */\n mapOnFailSignals(callback: (signal: string) => void) {\n return Array.from(this.signalsToEmitOnFail).map(callback);\n }\n\n /**\n * Maps over the observed signals with the provided callback function.\n *\n * @param {function(string): void} callback - A function to execute on each signal in the observed signals array.\n * @return {Array} A new array containing the results of calling the callback function on each observed signal.\n */\n mapObservedSignals(callback: (signal: string) => void) {\n return Array.from(this.observedSignals).map(callback);\n }\n\n /**\n * Emits a collection of signals stored in the `signalsToEmitAfter` array.\n *\n * @param {GraphContext} context - The context object containing data or state to be passed to the emitted signals.\n * @return {void} This method does not return a value.\n */\n emitSignals(context: GraphContext): void {\n this.signalsToEmitAfter.forEach((signal) => {\n this.emit(signal, context.getFullContext());\n });\n }\n\n /**\n * Emits registered signals when an operation fails.\n *\n * @param {GraphContext} context - The context from which the full context is derived and passed to the signals being emitted.\n * @return {void} This method does not return any value.\n */\n emitOnFailSignals(context: GraphContext): void {\n this.signalsToEmitOnFail.forEach((signal) => {\n this.emit(signal, context.getFullContext());\n });\n }\n\n /**\n * Cleans up and destroys the task instance, detaching it from other tasks and\n * performing necessary cleanup operations.\n *\n * This method:\n * - Unsubscribes from all signals and events.\n * - Detaches all associated signal handlers.\n * - Removes the task from successor and predecessor task mappings.\n * - Clears all task relationships and marks the task as destroyed.\n * - Emits destruction metrics, if applicable.\n *\n * @return {void} No value is returned because the function performs clean-up operations.\n */\n public destroy(): void {\n this.unsubscribeAll();\n this.detachAllSignals();\n\n this.predecessorTasks.forEach((pred) => pred.nextTasks.delete(this));\n this.nextTasks.forEach((next) => next.predecessorTasks.delete(this));\n this.onFailTasks.forEach((fail) => fail.predecessorTasks.delete(this));\n\n this.nextTasks.clear();\n this.predecessorTasks.clear();\n this.onFailTasks.clear();\n\n this.destroyed = true;\n\n if (this.register) {\n this.emitMetricsWithMetadata(\"meta.task.destroyed\", {\n data: { deleted: true },\n filter: { name: this.name, version: this.version },\n });\n }\n\n // TODO: Delete task map instances\n }\n\n /**\n * Exports the current state of the object as a structured plain object.\n *\n * @return {AnyObject} An object containing the serialized properties of the current instance. The exported object includes various metadata, schema information, task attributes, and related tasks, such as:\n * - Name and description of the task.\n * - Layer index, uniqueness, meta, and signal-related flags.\n * - Event triggers and attached signals.\n * - Throttling, concurrency, timeout settings, and ephemeral flag.\n * - Task function as a string.\n * - Serialization of getter callbacks and schemas for input/output validation.\n * - Relationships such as next tasks, failure tasks, and predecessor tasks.\n */\n public export(): AnyObject {\n return {\n __name: this.name,\n __description: this.description,\n __layerIndex: this.layerIndex,\n __isUnique: this.isUnique,\n __isMeta: this.isMeta,\n __isSignal: this.isSignal,\n __eventTriggers: this.observedSignals,\n __attachedEvents: this.signalsToEmitAfter,\n __isDeputy: this.isDeputy,\n __throttled: this.throttled,\n __isEphemeral: this.isEphemeral,\n __concurrency: this.concurrency,\n __timeout: this.timeout,\n __functionString: this.taskFunction.toString(),\n __getTagCallback: this.getTag.toString(),\n __inputSchema: this.inputContextSchema,\n __validateInputContext: this.validateInputContext,\n __outputSchema: this.outputContextSchema,\n __validateOutputContext: this.validateOutputContext,\n __nextTasks: Array.from(this.nextTasks).map((t) => t.name),\n __onFailTasks: Array.from(this.onFailTasks).map((t) => t.name),\n __previousTasks: Array.from(this.predecessorTasks).map((t) => t.name),\n };\n }\n\n /**\n * Returns an iterator for iterating over tasks associated with this instance.\n *\n * @return {TaskIterator} An iterator instance for tasks.\n */\n public getIterator(): TaskIterator {\n return new TaskIterator(this);\n }\n\n /**\n * Accepts a visitor object to perform operations on the current instance.\n *\n * @param {GraphVisitor} visitor - The visitor object implementing operations for this instance.\n * @return {void} This method does not return a value.\n */\n public accept(visitor: GraphVisitor): void {\n visitor.visitTask(this);\n }\n\n public log(): void {\n console.log(this.name);\n }\n}\n","import Iterator from \"../../interfaces/Iterator\";\nimport Task from \"../definition/Task\";\n\n/**\n * TaskIterator is a custom iterator for traversing over a set of tasks.\n * It provides mechanisms to iterate through tasks in a layered manner,\n * where each task can branch out to other tasks forming multiple layers.\n */\nexport default class TaskIterator implements Iterator {\n currentTask: Task | undefined;\n currentLayer: Set<Task> = new Set();\n nextLayer: Set<Task> = new Set();\n iterator: { next: () => { value: Task | undefined } } =\n this.currentLayer[Symbol.iterator]();\n\n constructor(task: Task) {\n this.currentTask = task;\n this.currentLayer.add(task);\n }\n hasNext(): boolean {\n return !!this.currentTask;\n }\n\n next(): Task | undefined {\n const nextTask = this.currentTask;\n\n if (!nextTask) {\n return undefined;\n }\n\n nextTask.mapNext((t: Task) => this.nextLayer.add(t));\n\n let next = this.iterator.next();\n\n if (next.value === undefined) {\n this.currentLayer.clear();\n this.currentLayer = this.nextLayer;\n this.nextLayer = new Set();\n this.iterator = this.currentLayer[Symbol.iterator]();\n next = this.iterator.next();\n }\n\n this.currentTask = next.value;\n\n return nextTask;\n }\n}\n","import Cadenza from \"../Cadenza\";\nimport Task from \"../graph/definition/Task\";\nimport GraphRoutine from \"../graph/definition/GraphRoutine\";\nimport { AnyObject } from \"../types/global\";\n\n/**\n * This class serves as a registry for managing tasks and routines within a graph-based execution model.\n * It provides functionalities to register, update, retrieve, delete, and iterate over tasks and routines.\n */\nexport default class GraphRegistry {\n static _instance: GraphRegistry;\n public static get instance(): GraphRegistry {\n if (!this._instance) this._instance = new GraphRegistry();\n return this._instance;\n }\n\n tasks: Map<string, Task> = new Map();\n routines: Map<string, GraphRoutine> = new Map();\n\n registerTask: Task;\n updateTaskInputSchema: Task;\n updateTaskOutputSchema: Task;\n getTaskByName: Task;\n getTasksByLayer: Task;\n getAllTasks: Task;\n doForEachTask: Task;\n deleteTask: Task;\n registerRoutine: Task;\n getRoutineByName: Task;\n getAllRoutines: Task;\n doForEachRoutine: Task;\n deleteRoutine: Task;\n\n /**\n * Constructs a new instance and sets up various meta tasks and routines.\n *\n * This constructor initializes several predefined tasks for managing operations\n * like registering tasks, updating schemas for tasks, fetching tasks or routines,\n * and performing actions on all tasks or routines. It also initializes routines\n * to handle similar operations and hardcodes the initial meta tasks and routines.\n *\n * It initializes the instance state by setting up tasks and routines.\n */\n constructor() {\n // Hardcode seed MetaTask (observes on existing broker)\n this.registerTask = new Task(\n \"Register task\",\n (context: AnyObject) => {\n const { taskInstance } = context;\n if (taskInstance && !this.tasks.has(taskInstance.name)) {\n this.tasks.set(taskInstance.name, taskInstance);\n }\n delete context.taskInstance;\n return true;\n },\n \"Registers tasks. Seed for meta.taskCreated\",\n 0,\n 0,\n true,\n false,\n true,\n ).doOn(\"meta.task.created\");\n\n // Manual seed register\n this.tasks.set(this.registerTask.name, this.registerTask);\n\n this.updateTaskInputSchema = Cadenza.createMetaTask(\n \"Update task input schema\",\n (context) => {\n const { __id, __schema } = context;\n const task = this.tasks.get(__id);\n if (!task) return true;\n task.setInputContextSchema(__schema);\n return true;\n },\n \"Updates task input schema.\",\n ).doOn(\"meta.task.input_schema_updated\");\n\n this.updateTaskOutputSchema = Cadenza.createMetaTask(\n \"Update task input schema\",\n (context) => {\n const { __id, __schema } = context;\n const task = this.tasks.get(__id);\n if (!task) return true;\n task.setOutputContextSchema(__schema);\n return true;\n },\n \"Updates task input schema.\",\n ).doOn(\"meta.task.output_schema_updated\");\n\n this.getTaskByName = Cadenza.createMetaTask(\n \"Get task by name\",\n (context) => {\n const { __name } = context;\n for (const task of this.tasks.values()) {\n if (task.name === __name) {\n return { ...context, task };\n }\n }\n return false;\n },\n \"Gets task by name (first match).\",\n );\n\n this.getTasksByLayer = Cadenza.createMetaTask(\n \"Get tasks by layer\",\n (context) => {\n const { __layerIndex } = context;\n const layerTasks = Array.from(this.tasks.values()).filter(\n (task) => task.layerIndex === __layerIndex,\n );\n return { ...context, tasks: layerTasks };\n },\n \"Gets tasks by layer index.\",\n );\n\n this.getAllTasks = Cadenza.createMetaTask(\n \"Get all tasks\",\n (context) => ({ ...context, tasks: Array.from(this.tasks.values()) }), // Use arrow to capture this\n \"Gets all tasks.\",\n );\n\n this.doForEachTask = Cadenza.createMetaTask(\n \"Do for each task\",\n function* (context: AnyObject) {\n // @ts-ignore\n for (const task of this.tasks.values()) {\n yield { ...context, task };\n }\n }.bind(this), // Bind to capture this in generator\n \"Yields each task for branching.\",\n );\n\n this.deleteTask = Cadenza.createMetaTask(\n \"Delete task\",\n (context) => {\n const { filter } = context;\n this.tasks.delete(filter.name);\n return context;\n },\n \"Deletes task.\",\n ).doOn(\"meta.task.destroyed\");\n\n this.registerRoutine = Cadenza.createMetaTask(\n \"Register routine\",\n (context) => {\n const { routineInstance } = context;\n if (routineInstance && !this.routines.has(routineInstance.name)) {\n this.routines.set(routineInstance.name, routineInstance);\n }\n delete context.routineInstance;\n return true;\n },\n \"Registers routine.\",\n ).doOn(\"meta.routine.created\");\n\n this.getRoutineByName = Cadenza.createMetaTask(\n \"Get routine by name\",\n (context) => {\n const { __name } = context;\n for (const routine of this.routines.values()) {\n if (routine.name === __name) {\n return { ...context, routine };\n }\n }\n return false;\n },\n \"Gets routine by name.\",\n );\n\n this.getAllRoutines = Cadenza.createMetaTask(\n \"Get all routines\",\n (context) => ({\n ...context,\n routines: Array.from(this.routines.values()),\n }), // Use arrow to capture this\n \"Gets all routines.\",\n );\n\n this.doForEachRoutine = Cadenza.createMetaTask(\n \"Do for each routine\",\n function* (context: AnyObject) {\n // @ts-ignore\n for (const routine of this.routines.values()) {\n yield { ...context, routine: routine };\n }\n }.bind(this),\n \"Yields each routine.\",\n );\n\n this.deleteRoutine = Cadenza.createMetaTask(\n \"Delete routine\",\n (context) => {\n const { __name } = context;\n this.routines.delete(__name);\n return context;\n },\n \"Deletes routine.\",\n );\n }\n\n reset() {\n this.tasks.clear();\n this.routines.clear();\n }\n}\n","import Task, { TaskFunction, TaskResult } from \"./Task\";\nimport GraphContext from \"../context/GraphContext\";\nimport { SchemaDefinition } from \"../../types/schema\";\n\nexport interface DebounceOptions {\n leading?: boolean;\n trailing?: boolean;\n maxWait?: number;\n}\n\n/**\n * Class representing a debounced task, inheriting from the `Task` class.\n * This class allows tasks to be executed with debounce behavior, controlling\n * the frequency at which the task function is triggered.\n */\nexport default class DebounceTask extends Task {\n readonly debounceTime: number;\n leading: boolean;\n trailing: boolean;\n maxWait: number;\n timer: NodeJS.Timeout | null = null;\n maxTimer: NodeJS.Timeout | null = null;\n hasLaterCall: boolean = false;\n lastResolve: ((value: unknown) => void) | null = null;\n lastReject: ((reason?: any) => void) | null = null;\n lastContext: GraphContext | null = null;\n lastTimeout: NodeJS.Timeout | null = null;\n lastProgressCallback: ((progress: number) => void) | null = null;\n lastEmitFunction: ((signal: string, context: any) => void) | null = null;\n\n constructor(\n name: string,\n task: TaskFunction,\n description: string = \"\",\n debounceTime: number = 1000,\n leading: boolean = false,\n trailing: boolean = true,\n maxWait: number = 0,\n concurrency: number = 0,\n timeout: number = 0,\n register: boolean = true,\n isUnique: boolean = false,\n isMeta: boolean = false,\n isSubMeta: boolean = false,\n isHidden: boolean = false,\n inputSchema: SchemaDefinition | undefined = undefined,\n validateInputSchema: boolean = false,\n outputSchema: SchemaDefinition | undefined = undefined,\n validateOutputSchema: boolean = false,\n ) {\n super(\n name,\n task,\n description,\n concurrency,\n timeout,\n register,\n isUnique,\n isMeta,\n isSubMeta,\n isHidden,\n undefined,\n inputSchema,\n validateInputSchema,\n outputSchema,\n validateOutputSchema,\n );\n this.debounceTime = debounceTime;\n this.leading = leading;\n this.trailing = trailing;\n this.maxWait = maxWait;\n }\n\n /**\n * Executes the taskFunction with the provided context, emit function, and progress callback.\n * It clears any existing timeout before execution.\n * Handles synchronous and asynchronous results from taskFunction.\n * If an error occurs during execution, it resolves with the error.\n *\n * @return {void} This method does not return any value.\n */\n executeFunction(): void {\n if (this.lastTimeout) {\n clearTimeout(this.lastTimeout);\n }\n\n let result;\n try {\n result = this.taskFunction(\n this.lastContext!.getClonedContext(),\n this.lastEmitFunction!,\n this.lastProgressCallback!,\n );\n } catch (error) {\n if (this.lastResolve) {\n this.lastResolve(error);\n }\n return;\n }\n\n if (result instanceof Promise) {\n result.then(this.lastResolve!).catch(this.lastReject!);\n } else {\n if (this.lastResolve) {\n this.lastResolve(result);\n }\n }\n }\n\n /**\n * Executes a debounced operation, ensuring controlled execution of functions\n * over a specified debounce time and maximum wait time. This method handles\n * both leading and trailing edge executions and invokes callbacks accordingly.\n *\n * @param {Function} resolve - The function to call when the operation is successfully resolved.\n * @param {Function} reject - The function to call with an error or reason if the operation fails.\n * @param {GraphContext} context - The execution context for the operation.\n * @param {NodeJS.Timeout} timeout - A timeout object for managing execution delays.\n * @param {Function} emit - A callback function to emit signals with a specific context.\n * @param {Function} progressCallback - A callback function to report progress during operation execution.\n * @return {void} Does not return a value but sets internal timers and invokes provided callbacks.\n */\n debouncedTrigger(\n resolve: (value: unknown) => void,\n reject: (reason?: any) => void,\n context: GraphContext,\n timeout: NodeJS.Timeout,\n emit: (signal: string, context: any) => void,\n progressCallback: (progress: number) => void,\n ): void {\n const callNow = this.leading && this.timer === null;\n const isNewBurst = this.timer === null;\n\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n this.lastResolve = resolve;\n this.lastReject = reject;\n this.lastContext = context;\n this.lastTimeout = timeout;\n this.lastProgressCallback = progressCallback;\n this.lastEmitFunction = emit;\n\n if (!callNow) {\n this.hasLaterCall = true;\n }\n\n this.timer = setTimeout(() => {\n this.timer = null;\n if (this.trailing && this.hasLaterCall) {\n this.executeFunction();\n this.hasLaterCall = false;\n }\n if (this.maxTimer) {\n clearTimeout(this.maxTimer);\n this.maxTimer = null;\n }\n }, this.debounceTime);\n\n if (callNow) {\n this.executeFunction();\n this.hasLaterCall = false;\n }\n\n if (this.maxWait > 0 && isNewBurst) {\n this.maxTimer = setTimeout(() => {\n this.maxTimer = null;\n if (this.trailing && this.hasLaterCall) {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n this.executeFunction();\n this.hasLaterCall = false;\n }\n }, this.maxWait);\n }\n }\n\n /**\n * Executes a task with a debounced trigger mechanism.\n *\n * @param {GraphContext} context - The context containing relevant graph data for the execution.\n * @param {function(string, any): void} emit - A function used to emit signals with associated context.\n * @param {function(number): void} progressCallback - A callback function to report the progress of the task as a number between 0 and 1.\n * @return {Promise<TaskResult>} A promise that resolves with the task result upon completion or rejects on failure.\n */\n execute(\n context: GraphContext,\n emit: (signal: string, context: any) => void,\n progressCallback: (progress: number) => void,\n ): TaskResult {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n resolve(false);\n }, this.debounceTime + 1);\n\n this.debouncedTrigger(\n resolve,\n reject,\n context,\n timeout,\n emit,\n progressCallback,\n );\n });\n }\n}\n","import Task, { TaskFunction, ThrottleTagGetter } from \"./Task\";\nimport { SchemaDefinition } from \"../../types/schema\";\nimport { AnyObject } from \"../../types/global\";\n\nexport type EphemeralTaskOptions = {\n once?: boolean;\n destroyCondition?: (context: any) => boolean;\n};\n\n/**\n * Represents a transient task that executes and may optionally self-destruct\n * based on given conditions.\n *\n * EphemeralTask extends the standard Task class and introduces additional\n * features for managing tasks that are intended to run only once, or under\n * certain conditions. This class is particularly useful when you want a task\n * to clean up after itself and not persist within the system indefinitely.\n */\nexport default class EphemeralTask extends Task {\n readonly once: boolean;\n readonly condition: (context: any) => boolean;\n readonly isEphemeral: boolean = true;\n\n constructor(\n name: string,\n task: TaskFunction,\n description: string = \"\",\n once: boolean = true,\n condition: (context: any) => boolean = () => true,\n concurrency: number = 0,\n timeout: number = 0,\n register: boolean = false,\n isUnique: boolean = false,\n isMeta: boolean = false,\n isSubMeta: boolean = false,\n isHidden: boolean = false,\n getTagCallback: ThrottleTagGetter | undefined = undefined,\n inputSchema: SchemaDefinition | undefined = undefined,\n validateInputContext: boolean = false,\n outputSchema: SchemaDefinition | undefined = undefined,\n validateOutputContext: boolean = false,\n retryCount: number = 0,\n retryDelay: number = 0,\n retryDelayMax: number = 0,\n retryDelayFactor: number = 1,\n ) {\n super(\n name,\n task,\n description,\n concurrency,\n timeout,\n register,\n isUnique,\n isMeta,\n isSubMeta,\n isHidden,\n getTagCallback,\n inputSchema,\n validateInputContext,\n outputSchema,\n validateOutputContext,\n retryCount,\n retryDelay,\n retryDelayMax,\n retryDelayFactor,\n );\n this.once = once;\n this.condition = condition;\n }\n\n /**\n * Executes the process logic with the provided context, emit function, progress callback, and node data.\n *\n * @param {any} context - The execution context, carrying necessary parameters or states for the operation.\n * @param {function(string, AnyObject): void} emit - A function to emit signals with a string identifier and associated context.\n * @param {function(number): void} progressCallback - A callback function to report the progress of the execution as a numerical value.\n * @param {{ nodeId: string, routineExecId: string }} nodeData - An object containing details about the node ID and routine execution ID.\n * @return {any} The result of the execution, returned from the base implementation or processed internally.\n */\n public execute(\n context: any,\n emit: (signal: string, context: AnyObject) => void,\n progressCallback: (progress: number) => void,\n nodeData: { nodeId: string; routineExecId: string },\n ) {\n const result = super.execute(context, emit, progressCallback, nodeData);\n\n if (this.once || this.condition(result)) {\n this.destroy();\n }\n\n return result;\n }\n}\n","/**\n * Represents an abstract chain of execution, where each instance can be\n * connected to a succeeding or preceding instance to form a chain of steps.\n * Provides methods to manage the links between instances in the chain.\n */\nexport default abstract class ExecutionChain {\n next: ExecutionChain | undefined;\n previous: ExecutionChain | undefined;\n\n public setNext(next: ExecutionChain): void {\n if (this.hasNext) {\n return;\n }\n\n next.previous = this;\n this.next = next;\n }\n\n get hasNext() {\n return !!this.next;\n }\n\n get hasPreceding() {\n return !!this.previous;\n }\n\n getNext() {\n return this.next;\n }\n\n getPreceding() {\n return this.previous;\n }\n\n decouple() {\n this.next = undefined;\n this.previous = undefined;\n }\n}\n","import Iterator from \"../../interfaces/Iterator\";\nimport SyncGraphLayer from \"../execution/SyncGraphLayer\";\nimport GraphLayer from \"../../interfaces/GraphLayer\";\n\n/**\n * The `GraphLayerIterator` class provides an iterator for traversing through\n * layers of a `GraphLayer` data structure. It allows sequential and bi-directional\n * iteration, as well as access to the first and last layers in the graph.\n *\n * @implements {Iterator}\n */\nexport default class GraphLayerIterator implements Iterator {\n graph: GraphLayer;\n currentLayer: GraphLayer | undefined;\n\n constructor(graph: GraphLayer) {\n this.graph = graph;\n }\n hasNext() {\n return !this.currentLayer || this.currentLayer.hasNext;\n }\n\n hasPrevious(): boolean {\n return !this.currentLayer || this.currentLayer.hasPreceding;\n }\n\n next(): GraphLayer {\n if (!this.currentLayer) {\n return this.getFirst();\n } else if (this.hasNext()) {\n this.currentLayer = this.currentLayer.getNext() as GraphLayer;\n }\n\n // @ts-ignore\n return this.currentLayer;\n }\n\n previous(): GraphLayer {\n if (!this.currentLayer) {\n this.currentLayer = this.graph;\n } else if (this.hasPrevious()) {\n this.currentLayer = this.currentLayer.getPreceding() as SyncGraphLayer;\n }\n\n // @ts-ignore\n return this.currentLayer;\n }\n\n getFirst(): GraphLayer {\n if (!this.currentLayer) {\n this.currentLayer = this.graph;\n }\n\n while (this.hasPrevious()) {\n this.currentLayer = this.currentLayer?.getPreceding() as SyncGraphLayer;\n }\n\n return this.currentLayer;\n }\n\n getLast(): GraphLayer {\n if (!this.currentLayer) {\n this.currentLayer = this.graph;\n }\n\n while (this.hasNext()) {\n this.currentLayer = this.currentLayer?.getNext() as GraphLayer;\n }\n\n return this.currentLayer as GraphLayer;\n }\n}\n","import ExecutionChain from \"./ExecutionChain\";\nimport Graph from \"./Graph\";\nimport GraphNode from \"../graph/execution/GraphNode\";\nimport GraphLayerIterator from \"../graph/iterators/GraphLayerIterator\";\nimport GraphVisitor from \"./GraphVisitor\";\nimport GraphContext from \"../graph/context/GraphContext\";\n\n/**\n * Represents an abstract layer in a graph, handling nodes and their execution.\n * A `GraphLayer` can manage execution states, debug states, and relationships with other layers in the graph.\n * This class is designed to be extended and requires the implementation of the `execute` method.\n *\n * @abstract\n * @class GraphLayer\n * @extends ExecutionChain\n * @implements Graph\n */\nexport default abstract class GraphLayer\n extends ExecutionChain\n implements Graph\n{\n readonly index: number;\n nodes: GraphNode[] = [];\n executionTime: number = 0;\n executionStart: number = 0;\n debug: boolean = false;\n\n constructor(index: number) {\n super();\n this.index = index;\n }\n\n /**\n * Sets the debug mode for the current instance and all associated nodes.\n *\n * @param {boolean} value - A boolean value to enable (true) or disable (false) debug mode.\n * @return {void} No return value.\n */\n setDebug(value: boolean) {\n this.debug = value;\n for (const node of this.nodes) {\n node.setDebug(value);\n }\n }\n\n /**\n * Abstract method to execute a specific operation given a context.\n *\n * @param {GraphContext} [context] - Optional parameter representing the execution context, which contains relevant data for performing the operation.\n * @return {unknown} - Returns the result of the operation, its type may vary depending on the implementation.\n */\n abstract execute(context?: GraphContext): unknown;\n\n /**\n * Checks if the current layer has a preceding layer.\n *\n * @return {boolean} True if the current layer has a preceding layer that is an instance of GraphLayer; otherwise, false.\n */\n get hasPreceding() {\n return !!this.previous && this.previous instanceof GraphLayer;\n }\n\n getNumberOfNodes() {\n return this.nodes.length;\n }\n\n /**\n * Retrieves a list of nodes that match the given routine execution ID.\n *\n * @param {string} routineExecId - The ID of the routine execution to filter nodes by.\n * @return {Array} An array of nodes that have the specified routine execution ID.\n */\n getNodesByRoutineExecId(routineExecId: string) {\n return this.nodes.filter((node) => node.routineExecId === routineExecId);\n }\n\n /**\n * Finds and returns all nodes in the graph that are identical to the given node.\n * Two nodes are considered identical if they share the same routine execution ID\n * and share a task with each other.\n *\n * @param {GraphNode} node - The reference node to compare against other nodes in the graph.\n * @return {GraphNode[]} An array of nodes that are identical to the given node.\n */\n getIdenticalNodes(node: GraphNode) {\n return this.nodes.filter(\n (n) => node.routineExecId === n.routineExecId && node.sharesTaskWith(n),\n );\n }\n\n /**\n * Checks whether all nodes in the collection have been processed.\n *\n * @return {boolean} Returns true if all nodes are processed, otherwise false.\n */\n isProcessed() {\n for (const node of this.nodes) {\n if (!node.isProcessed()) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Checks whether all layers in the graph have been processed.\n *\n * @return {boolean} Returns true if all graph layers are processed; otherwise, returns false.\n */\n graphDone() {\n let done = true;\n\n let layer: GraphLayer | undefined = this;\n while (layer) {\n if (!layer.isProcessed()) {\n done = false;\n break;\n }\n layer = layer.getNext() as GraphLayer;\n }\n\n return done;\n }\n\n /**\n * Sets the next GraphLayer in the sequence if it has a higher index than the current layer.\n * Updates the previous property if the given next layer has an existing previous layer.\n *\n * @param {GraphLayer} next - The next GraphLayer to be linked in the sequence.\n * @return {void} Does not return a value. Modifies the current layer's state.\n */\n setNext(next: GraphLayer) {\n if (next.index <= this.index) {\n return;\n }\n\n if (next.previous !== undefined) {\n this.previous = next.previous;\n }\n\n super.setNext(next);\n }\n\n /**\n * Adds a node to the graph.\n *\n * @param {GraphNode} node - The node to be added to the graph.\n * @return {void}\n */\n add(node: GraphNode) {\n this.nodes.push(node);\n }\n\n /**\n * Starts the execution timer if it has not been started already.\n * Records the current timestamp as the start time.\n *\n * @return {number} The timestamp representing the start time in milliseconds.\n */\n start() {\n if (!this.executionStart) {\n this.executionStart = Date.now();\n }\n return this.executionStart;\n }\n\n /**\n * Marks the end of a process by capturing the current timestamp and calculating the execution time if a start time exists.\n *\n * @return {number} The timestamp at which the process ended, or 0 if the start time is not defined.\n */\n end() {\n if (!this.executionStart) {\n return 0;\n }\n\n const end = Date.now();\n this.executionTime = end - this.executionStart;\n return end;\n }\n\n /**\n * Destroys the current graph layer and its associated resources.\n * This method recursively destroys all nodes in the current layer, clears the node list,\n * and ensures that any connected subsequent graph layers are also destroyed.\n * Additionally, it calls the decoupling logic to disconnect the current layer from its dependencies.\n *\n * @return {void} Does not return any value.\n */\n destroy() {\n for (const node of this.nodes) {\n node.destroy();\n }\n\n this.nodes = [];\n\n if (this.hasNext) {\n const layer = this.getNext() as GraphLayer;\n layer?.destroy();\n }\n\n this.decouple();\n }\n\n /**\n * Returns an iterator for traversing through the graph layers.\n *\n * @return {GraphLayerIterator} An instance of GraphLayerIterator to traverse graph layers.\n */\n getIterator(): GraphLayerIterator {\n return new GraphLayerIterator(this);\n }\n\n /**\n * Accepts a visitor object to traverse or perform operations on the current graph layer and its nodes.\n *\n * @param {GraphVisitor} visitor - The visitor instance implementing the visitLayer and visitNode behavior.\n * @return {void} Returns nothing.\n */\n accept(visitor: GraphVisitor) {\n visitor.visitLayer(this);\n\n for (const node of this.nodes) {\n node.accept(visitor);\n }\n }\n\n export() {\n return {\n __index: this.index,\n __executionTime: this.executionTime,\n __numberOfNodes: this.getNumberOfNodes(),\n __hasNextLayer: this.hasNext,\n __hasPrecedingLayer: this.hasPreceding,\n __nodes: this.nodes.map((node) => node.id),\n };\n }\n\n log() {\n console.log(`---Layer ${this.index}---`);\n console.log(\"Execution time:\", this.executionTime);\n let prevNode;\n for (const node of this.nodes) {\n if (!prevNode || !prevNode.sharesContextWith(node)) {\n console.log(\"**********\");\n }\n node.log();\n prevNode = node;\n }\n console.log(\"***********\");\n if (this.hasNext) {\n (this.getNext() as GraphLayer).log();\n }\n }\n}\n","import GraphNode from \"./GraphNode\";\nimport GraphLayer from \"../../interfaces/GraphLayer\";\n\n/**\n * Represents a synchronous graph layer derived from the GraphLayer base class.\n * This class is designed to execute graph nodes in a strictly synchronous manner.\n * Asynchronous functions are explicitly disallowed, ensuring consistency and predictability.\n */\nexport default class SyncGraphLayer extends GraphLayer {\n /**\n * Executes the processing logic of the current set of graph nodes. Iterates through all\n * nodes, skipping any that have already been processed, and executes their respective\n * logic to generate new nodes. Asynchronous functions are not supported and will\n * trigger an error log.\n *\n * @return {GraphNode[]} An array of newly generated graph nodes after executing the logic of each unprocessed node.\n */\n execute(): GraphNode[] {\n this.start();\n\n const result: GraphNode[] = [];\n for (const node of this.nodes) {\n if (node.isProcessed()) {\n continue;\n }\n\n const newNodes = node.execute();\n\n if (newNodes instanceof Promise) {\n console.error(\"Asynchronous functions are not allowed in sync mode!\");\n continue;\n }\n\n result.push(...(newNodes as GraphNode[]));\n }\n\n this.end();\n\n return result;\n }\n}\n","import SyncGraphLayer from \"../graph/execution/SyncGraphLayer\";\nimport GraphNode from \"../graph/execution/GraphNode\";\nimport GraphLayer from \"./GraphLayer\";\n\n/**\n * GraphBuilder is an abstract base class designed to construct and manage a graph structure\n * composed of multiple layers. Subclasses are expected to implement the `compose` method\n * based on specific requirements. This class provides methods for adding nodes, managing\n * layers, and resetting the graph construction process.\n *\n * This class supports creating layered graph structures, dynamically adding layers and nodes,\n * and debugging graph-building operations.\n */\nexport default abstract class GraphBuilder {\n graph: GraphLayer | undefined;\n topLayerIndex: number = 0;\n layers: GraphLayer[] = [];\n debug: boolean = false;\n\n setDebug(value: boolean) {\n this.debug = value;\n }\n\n getResult(): GraphLayer {\n return this.graph as GraphLayer;\n }\n\n /**\n * Composes a series of functions or operations.\n * This method should be implemented in the child class\n * to define custom composition logic.\n *\n * @return {any} The result of the composed operations or functions\n * when implemented in the child class.\n */\n compose() {\n throw \"Implement this in child class...\";\n }\n\n /**\n * Adds a node to the appropriate layer of the graph.\n *\n * @param {GraphNode} node - The node to be added to the graph. The node contains\n * layer information that determines which layer it belongs to.\n * @return {void} Does not return a value.\n */\n addNode(node: GraphNode) {\n const index = node.getLayerIndex();\n\n this.addLayer(index);\n const layer = this.getLayer(index);\n\n node.scheduleOn(layer);\n }\n\n /**\n * Adds multiple nodes to the graph.\n *\n * @param {GraphNode[]} nodes - An array of nodes to be added to the graph.\n * @return {void} This method does not return a value.\n */\n addNodes(nodes: GraphNode[]) {\n for (const node of nodes) {\n this.addNode(node);\n }\n }\n\n /**\n * Adds a new layer to the graph at the specified index. If the graph does not exist,\n * it creates the graph using the specified index. Updates the graph's top layer index\n * and maintains the order of layers.\n *\n * @param {number} index - The index at which the new layer should be added to the graph.\n * @return {void} This method does not return a value.\n */\n addLayer(index: number) {\n if (!this.graph) {\n const layer = this.createLayer(index);\n this.graph = layer;\n this.layers.push(layer);\n this.topLayerIndex = index;\n return;\n }\n\n const lastLayerIndex = this.topLayerIndex + this.layers.length - 1;\n\n if (index >= this.topLayerIndex && index <= lastLayerIndex) {\n return;\n }\n\n if (this.topLayerIndex > index) {\n const layer = this.createLayer(this.topLayerIndex - 1);\n layer.setNext(this.layers[0]);\n this.graph = layer;\n this.layers.unshift(layer);\n this.topLayerIndex = this.topLayerIndex - 1;\n this.addLayer(index);\n } else {\n const layer = this.createLayer(lastLayerIndex + 1);\n this.layers[this.layers.length - 1].setNext(layer);\n this.layers.push(layer);\n this.addLayer(index);\n }\n }\n\n /**\n * Creates a new layer for the graph at the specified index.\n *\n * @param {number} index - The index of the layer to be created.\n * @return {GraphLayer} A new instance of the graph layer corresponding to the provided index.\n */\n createLayer(index: number): GraphLayer {\n const layer = new SyncGraphLayer(index);\n layer.setDebug(this.debug);\n return layer;\n }\n\n /**\n * Retrieves a specific layer from the current set of layers.\n *\n * @param {number} layerIndex - The index of the layer to retrieve.\n * @return {*} The layer corresponding to the given index.\n */\n getLayer(layerIndex: number) {\n return this.layers[layerIndex - this.topLayerIndex];\n }\n\n public reset() {\n this.graph = undefined;\n this.topLayerIndex = 0;\n this.layers = [];\n }\n}\n","import GraphBuilder from \"../../interfaces/GraphBuilder\";\nimport GraphNode from \"../../graph/execution/GraphNode\";\n\n/**\n * A builder class for constructing graphs using a breadth-first approach. Extends the\n * functionality of the `GraphBuilder` class to iterate through graph layers and execute\n * operations on each layer in a breadth-first manner.\n *\n * This class is designed to process a graph layer by layer, executing specific logic\n * on nodes of the current layer and adding newly created or discovered nodes to the graph.\n */\nexport default class GraphBreadthFirstBuilder extends GraphBuilder {\n /**\n * Composes layers of a graph by iterating through them, executing their logic,\n * and adding the resulting nodes to the current graph.\n *\n * @return {void} This method does not return a value.\n */\n compose() {\n if (!this.graph) {\n return;\n }\n\n const layers = this.graph.getIterator();\n while (layers.hasNext()) {\n const layer = layers.next();\n const newNodes = layer.execute() as GraphNode[];\n this.addNodes(newNodes);\n }\n }\n}\n","import GraphNode from \"../graph/execution/GraphNode\";\nimport GraphBuilder from \"./GraphBuilder\";\nimport GraphRun from \"../engine/GraphRun\";\nimport GraphBreadthFirstBuilder from \"../engine/builders/GraphBreadthFirstBuilder\";\n\n/**\n * Abstract class representing a strategy for configuring and executing graph operations.\n * Provides a structure for managing graph builders, altering strategies, and updating the execution context.\n *\n * This class cannot be instantiated directly and must be extended by concrete implementations.\n */\nexport default abstract class GraphRunStrategy {\n graphBuilder: GraphBuilder;\n runInstance?: GraphRun;\n\n constructor() {\n this.graphBuilder = new GraphBreadthFirstBuilder();\n }\n\n setRunInstance(runInstance: GraphRun) {\n this.runInstance = runInstance;\n }\n\n changeStrategy(builder: GraphBuilder) {\n this.graphBuilder = builder;\n }\n\n reset() {\n this.graphBuilder.reset();\n }\n\n addNode(node: GraphNode) {\n this.graphBuilder.addNode(node);\n }\n\n updateRunInstance() {\n this.runInstance?.setGraph(this.graphBuilder.getResult());\n }\n\n abstract run(): void;\n abstract export(): any;\n}\n","import GraphNode from \"../graph/execution/GraphNode\";\n\ntype ProcessFunction = (node: GraphNode) => Promise<GraphNode[]> | GraphNode[];\n\n/**\n * The ThrottleEngine class provides a mechanism for controlling the concurrency level\n * of function execution, grouped by tags. It ensures that no more than the specified\n * maximum number of functions per tag run concurrently.\n */\nexport default class ThrottleEngine {\n static instance_: ThrottleEngine;\n\n static get instance() {\n if (!this.instance_) {\n this.instance_ = new ThrottleEngine();\n }\n return this.instance_;\n }\n\n queues: { [tag: string]: [ProcessFunction, GraphNode][] } = {};\n runningCounts: { [tag: string]: number } = {};\n maxConcurrencyPerTag: { [tag: string]: number } = {};\n\n functionIdToPromiseResolve: {\n [functionInstanceId: string]: (value: GraphNode[]) => void;\n } = {};\n\n /**\n * Set a custom concurrency limit for a specific tag\n */\n setConcurrencyLimit(tag: string, limit: number) {\n this.maxConcurrencyPerTag[tag] = limit;\n }\n\n /**\n * Manages the execution of a function `fn` applied on a specified node `node` with controlled concurrency for a given tag.\n * The method ensures that processes are executed in a throttled manner, respecting the maximum concurrency for each tag.\n *\n * @param {ProcessFunction} fn - The function to be executed on the provided node.\n * @param {GraphNode} node - The graph node on which the function `fn` will be applied.\n * @param {string} [tag=\"default\"] - The concurrency grouping tag used to control and group the throttling behavior.\n * @return {Promise<GraphNode[]>} A promise resolving to an array of GraphNode objects once the throttled function execution completes.\n */\n throttle(\n fn: ProcessFunction,\n node: GraphNode,\n tag: string = \"default\",\n ): Promise<GraphNode[]> {\n const functionPromise = new Promise((resolve) => {\n this.functionIdToPromiseResolve[node.id] = resolve as (\n value: GraphNode[],\n ) => void;\n }) as Promise<GraphNode[]>;\n\n this.queues[tag] ??= [];\n this.queues[tag].push([fn, node]);\n\n // Default to 1 if not set\n this.maxConcurrencyPerTag[tag] ??= 1;\n\n this.processQueue(tag);\n\n return functionPromise;\n }\n\n /**\n * Processes the tasks in the queue for a given tag while respecting concurrency limits.\n *\n * @param {string} tag - The identifier for the queue to be processed, used to group tasks and manage concurrency controls.\n * @return {void} Does not return a value; it processes tasks asynchronously and manages state internally.\n */\n processQueue(tag: string) {\n const maxAllowed = this.maxConcurrencyPerTag[tag];\n\n while (\n (this.queues[tag]?.length ?? 0) > 0 &&\n (this.runningCounts[tag] ?? 0) < maxAllowed\n ) {\n this.runningCounts[tag] = (this.runningCounts[tag] || 0) + 1;\n const item = this.queues[tag].shift()!;\n this.process(item).then(() => {\n this.runningCounts[tag]--;\n this.processQueue(tag); // Re-check queue\n });\n }\n\n // Clean up if done\n if (\n (this.queues[tag]?.length ?? 0) === 0 &&\n this.runningCounts[tag] === 0\n ) {\n delete this.queues[tag];\n delete this.runningCounts[tag];\n }\n }\n\n /**\n * Processes a given item consisting of a function and a graph node.\n *\n * @param {Array} item - An array where the first element is a processing function and the second element is a graph node.\n * @param {Function} item[0] - The function to process the graph node.\n * @param {GraphNode} item[1] - The graph node to be processed.\n * @return {Promise<void>} A promise that resolves when the processing and cleanup are complete.\n */\n async process(item: [ProcessFunction, GraphNode]) {\n const fn = item[0];\n const node = item[1];\n\n const context = await fn(node);\n\n this.functionIdToPromiseResolve[node.id](context);\n delete this.functionIdToPromiseResolve[node.id];\n }\n}\n","import GraphNode from \"./GraphNode\";\nimport GraphLayer from \"../../interfaces/GraphLayer\";\nimport ThrottleEngine from \"../../engine/ThrottleEngine\";\n\n/**\n * Represents an asynchronous layer of graph nodes within a graph execution framework.\n * Extends the functionality of the base `GraphLayer` class to handle asynchronous node processing.\n */\nexport default class AsyncGraphLayer extends GraphLayer {\n waitingNodes: GraphNode[] = [];\n processingNodes: Set<GraphNode> = new Set();\n\n constructor(index: number) {\n super(index);\n }\n\n /**\n * Adds a node to the graph and tracks it as a waiting node.\n *\n * @param {GraphNode} node - The graph node to be added.\n * @return {void}\n */\n add(node: GraphNode) {\n this.nodes.push(node);\n this.waitingNodes.push(node);\n }\n\n /**\n * Executes the processing of nodes by iterating over the queued `waitingNodes`,\n * processing each node, and managing concurrency limits where applicable.\n * The method returns a mapping of routine execution IDs to arrays of processed nodes or promises.\n *\n * @return {Object} An object where the keys are routine execution IDs and the values\n * represent arrays of processed nodes or promises resolving to processed nodes.\n */\n execute() {\n if (this.waitingNodes.length === 0) {\n return {};\n }\n\n this.start();\n\n const result: {\n [routineExecId: string]: (GraphNode[] | Promise<GraphNode[]>)[];\n } = {};\n\n while (this.waitingNodes.length > 0) {\n const node = this.waitingNodes.shift();\n if (!node) {\n break;\n }\n\n this.processingNodes.add(node);\n\n result[node.routineExecId] ??= [];\n\n let nextNodes;\n if (node?.getConcurrency()) {\n const tag = node.getTag();\n ThrottleEngine.instance.setConcurrencyLimit(tag, node.getConcurrency());\n nextNodes = ThrottleEngine.instance.throttle(\n this.processNode.bind(this),\n node,\n tag,\n );\n } else {\n nextNodes = this.processNode(node);\n }\n\n result[node.routineExecId].push(nextNodes);\n }\n\n if (this.processingNodes.size === 0) {\n this.end();\n }\n\n return result;\n }\n\n /**\n * Processes the given graph node, executes its logic, and handles synchronous or asynchronous outcomes.\n *\n * @param {GraphNode} node - The graph node to be processed.\n * @return {Promise<GraphNode[]> | GraphNode[]} A promise that resolves to an array of next graph nodes if asynchronous,\n * or an array of next graph nodes if synchronous.\n */\n processNode(node: GraphNode): Promise<GraphNode[]> | GraphNode[] {\n node.start();\n\n const nextNodes = node.execute();\n\n if (nextNodes instanceof Promise) {\n return this.processAsync(node, nextNodes);\n }\n\n this.processingNodes.delete(node);\n\n return nextNodes;\n }\n\n /**\n * Processes the given graph node asynchronously and removes it from the processing nodes set.\n *\n * @param {GraphNode} node - The current graph node being processed.\n * @param {Promise<GraphNode[]>} nextNodes - A promise that resolves to an array of the next graph nodes to process.\n * @return {Promise<GraphNode[]>} A promise that resolves to an array of the next graph nodes.\n */\n async processAsync(node: GraphNode, nextNodes: Promise<GraphNode[]>) {\n const result = await nextNodes;\n this.processingNodes.delete(node);\n return result;\n }\n\n /**\n * Cleans up resources used by the instance by resetting relevant properties and invoking the parent class's destroy method.\n *\n * @return {void} No value is returned as the method performs cleanup operations.\n */\n destroy() {\n super.destroy();\n this.waitingNodes = [];\n this.processingNodes = new Set();\n }\n}\n","import GraphBuilder from \"../../interfaces/GraphBuilder\";\nimport { sleep } from \"../../utils/promise\";\nimport AsyncGraphLayer from \"../../graph/execution/AsyncGraphLayer\";\nimport GraphNode from \"../../graph/execution/GraphNode\";\n\n/**\n * The GraphAsyncQueueBuilder class extends the GraphBuilder class and provides functionality\n * for processing a directed acyclic graph (DAG) asynchronously layer by layer. This class\n * is designed to handle asynchronous execution of graph nodes and manage processing for\n * each layer in an iterative manner.\n *\n * The primary responsibility of this class is to compose the graph by processing its layers,\n * executing asynchronous operations (if any), and managing the dependencies between nodes.\n */\nexport default class GraphAsyncQueueBuilder extends GraphBuilder {\n /**\n * This method iterates over a graph structure and processes its layers sequentially.\n * It continues processing each layer until all layers in the graph are completed.\n * The asynchronous behavior ensures the operation provides breathing room for other\n * tasks/processes to execute during its operation.\n *\n * @return {Promise<void>} A promise that resolves when all layers of the graph are processed or rejects if an error occurs.\n */\n async compose() {\n if (!this.graph) {\n return;\n }\n\n const layers = this.graph.getIterator();\n\n while (true) {\n let layer = layers.getFirst();\n if (layer.graphDone()) {\n return;\n }\n\n this.processLayer(layer as AsyncGraphLayer);\n\n while (layers.hasNext()) {\n layer = layers.next();\n this.processLayer(layer as AsyncGraphLayer);\n }\n\n await sleep(0); // Take a breath\n }\n }\n\n /**\n * Processes a given asynchronous graph layer and executes its nodes.\n * Handles promises within the nodes and adds the resolved or processed\n * nodes to the graph.\n *\n * @param {AsyncGraphLayer} layer - The asynchronous graph layer to be processed.\n * @return {void} - This method does not return a value.\n */\n processLayer(layer: AsyncGraphLayer) {\n const nextNodes = layer.execute();\n for (const routineExecId of Object.keys(nextNodes)) {\n const group = nextNodes[routineExecId];\n if (group.some((nodes) => nodes instanceof Promise)) {\n Promise.all(group).then((result) =>\n this.addNodes(result.flat() as GraphNode[]),\n );\n } else {\n this.addNodes(group.flat() as GraphNode[]);\n }\n }\n }\n\n /**\n * Creates a new instance of AsyncGraphLayer, sets its debug configuration,\n * and returns the created layer.\n *\n * @param {number} index - The index to associate with the new AsyncGraphLayer.\n * @return {AsyncGraphLayer} A new instance of AsyncGraphLayer with the specified index and debug configuration.\n */\n createLayer(index: number) {\n const layer = new AsyncGraphLayer(index);\n layer.setDebug(this.debug);\n return layer;\n }\n}\n","import GraphRunStrategy from \"../../interfaces/GraphRunStrategy\";\nimport GraphAsyncQueueBuilder from \"../builders/GraphAsyncQueueBuilder\";\n\n/**\n * The GraphAsyncRun class extends GraphRunStrategy to implement an asynchronous\n * graph execution strategy. It utilizes a GraphAsyncQueueBuilder for building\n * and composing the graph asynchronously before execution.\n */\nexport default class GraphAsyncRun extends GraphRunStrategy {\n constructor() {\n super();\n this.graphBuilder = new GraphAsyncQueueBuilder();\n }\n\n /**\n * Executes the run operation, which involves composing the graph builder,\n * updating the run instance, and resetting the state.\n *\n * @return {Promise<void>} A promise that resolves when the operation completes.\n */\n async run() {\n await this.graphBuilder.compose();\n this.updateRunInstance();\n this.reset();\n }\n\n reset() {\n super.reset();\n }\n\n export(): any {\n return {};\n }\n}\n","import GraphRunStrategy from \"../../interfaces/GraphRunStrategy\";\n\n/**\n * The GraphStandardRun class extends the GraphRunStrategy and provides\n * a concrete implementation of methods to manage and execute a graph run.\n * This class is responsible for orchestrating the graph composition,\n * updating the run instance, and resetting its state after execution.\n */\nexport default class GraphStandardRun extends GraphRunStrategy {\n /**\n * Executes the sequence of operations involving graph composition,\n * instance updating, and reset mechanisms.\n *\n * @return {void} Does not return a value.\n */\n run() {\n this.graphBuilder.compose();\n this.updateRunInstance();\n this.reset();\n }\n\n export(): any {\n return {};\n }\n}\n","import SignalBroker from \"./engine/SignalBroker\";\nimport GraphRunner from \"./engine/GraphRunner\";\nimport GraphRegistry from \"./registry/GraphRegistry\";\nimport Task, { TaskFunction, ThrottleTagGetter } from \"./graph/definition/Task\";\nimport DebounceTask, { DebounceOptions } from \"./graph/definition/DebounceTask\";\nimport EphemeralTask, {\n EphemeralTaskOptions,\n} from \"./graph/definition/EphemeralTask\";\nimport GraphRoutine from \"./graph/definition/GraphRoutine\";\nimport GraphAsyncRun from \"./engine/strategy/GraphAsyncRun\";\nimport GraphStandardRun from \"./engine/strategy/GraphStandardRun\";\nimport { SchemaDefinition } from \"./types/schema\";\nimport { AnyObject } from \"./types/global\";\n\nexport interface TaskOptions {\n concurrency?: number;\n timeout?: number;\n register?: boolean;\n isUnique?: boolean;\n isMeta?: boolean;\n isSubMeta?: boolean;\n isHidden?: boolean;\n getTagCallback?: ThrottleTagGetter;\n inputSchema?: SchemaDefinition;\n validateInputContext?: boolean;\n outputSchema?: SchemaDefinition;\n validateOutputContext?: boolean;\n retryCount?: number;\n retryDelay?: number;\n retryDelayMax?: number;\n retryDelayFactor?: number;\n}\n\nexport type CadenzaMode = \"dev\" | \"debug\" | \"verbose\" | \"production\";\n\n/**\n * Represents the core class of the Cadenza framework managing tasks, meta-tasks, signal emissions, and execution strategies.\n * All core components such as SignalBroker, GraphRunner, and GraphRegistry are initialized through this class, and it provides\n * utility methods to create, register, and manage various task types.\n */\nexport default class Cadenza {\n public static broker: SignalBroker;\n public static runner: GraphRunner;\n public static metaRunner: GraphRunner;\n public static registry: GraphRegistry;\n static isBootstrapped = false;\n static mode: CadenzaMode = \"production\";\n\n /**\n * Initializes the system by setting up the required components such as the\n * signal broker, runners, and graph registry. Ensures the initialization\n * happens only once. Configures debug settings if applicable.\n *\n * @return {void} No value is returned.\n */\n public static bootstrap(): void {\n if (this.isBootstrapped) return;\n this.isBootstrapped = true;\n\n // 1. SignalBroker (empty, for observations)\n this.broker = SignalBroker.instance;\n\n // 2. Runners (now init broker with them)\n this.runner = new GraphRunner();\n this.metaRunner = new GraphRunner(true);\n this.broker.bootstrap(this.runner, this.metaRunner);\n\n if (this.mode === \"debug\" || this.mode === \"dev\") {\n this.broker.setDebug(true);\n this.runner.setDebug(true);\n this.metaRunner.setDebug(true);\n }\n\n // 3. GraphRegistry (seed observes on broker)\n this.registry = GraphRegistry.instance;\n\n // 4. Runners (create meta tasks)\n this.broker.init();\n this.runner.init();\n this.metaRunner.init();\n }\n\n /**\n * Retrieves the available strategies for running graphs.\n *\n * @return {Object} An object containing the available run strategies, where:\n * - PARALLEL: Executes graph runs asynchronously.\n * - SEQUENTIAL: Executes graph runs in a sequential order.\n */\n public static get runStrategy() {\n return {\n PARALLEL: new GraphAsyncRun(),\n SEQUENTIAL: new GraphStandardRun(),\n };\n }\n\n /**\n * Sets the mode for the application and configures the broker and runner settings accordingly.\n *\n * @param {CadenzaMode} mode - The mode to set. It can be one of the following:\n * \"debug\", \"dev\", \"verbose\", or \"production\".\n * Each mode adjusts debug and verbosity settings.\n * @return {void} This method does not return a value.\n */\n public static setMode(mode: CadenzaMode) {\n this.mode = mode;\n\n this.bootstrap();\n\n if (mode === \"debug\" || mode === \"dev\") {\n this.broker.setDebug(true);\n this.runner.setDebug(true);\n }\n\n if (mode === \"verbose\") {\n this.broker.setDebug(true);\n this.broker.setVerbose(true);\n this.runner.setDebug(true);\n this.runner.setVerbose(true);\n }\n\n if (mode === \"production\") {\n this.broker.setDebug(false);\n this.broker.setVerbose(false);\n this.runner.setDebug(false);\n this.runner.setVerbose(false);\n }\n }\n\n /**\n * Validates the given name to ensure it is a non-empty string.\n * Throws an error if the validation fails.\n *\n * @param {string} name - The name to validate.\n * @return {void} This method does not return anything.\n * @throws {Error} If the name is not a non-empty string.\n */\n public static validateName(name: string): void {\n if (!name || typeof name !== \"string\") {\n throw new Error(\"Task or Routine name must be a non-empty string.\");\n }\n // Further uniqueness check delegated to GraphRegistry.register*\n }\n\n /**\n * Executes the specified task or GraphRoutine with the given context using an internal runner.\n *\n * @param {Task | GraphRoutine} task - The task or GraphRoutine to be executed.\n * @param {AnyObject} context - The context in which the task or GraphRoutine should be executed.\n * @return {void}\n *\n * @example\n * ```ts\n * const task = Cadenza.createTask('My task', (ctx) => {\n * console.log('My task executed with context:', ctx);\n * });\n *\n * Cadenza.run(task, { foo: 'bar' });\n *\n * const routine = Cadenza.createRoutine('My routine', [task], 'My routine description');\n *\n * Cadenza.run(routine, { foo: 'bar' });\n * ```\n */\n public static run(task: Task | GraphRoutine, context: AnyObject) {\n this.runner?.run(task, context);\n }\n\n /**\n * Emits an event with the specified name and data payload to the broker.\n *\n * @param {string} event - The name of the event to emit.\n * @param {AnyObject} [data={}] - The data payload associated with the event.\n * @return {void} - No return value.\n *\n * @example\n * This is meant to be used as a global event emitter.\n * If you want to emit an event from within a task, you can use the `emit` method provided to the task function. See {@link TaskFunction}.\n * ```ts\n * Cadenza.emit('main.my_event', { foo: 'bar' });\n * ```\n */\n public static emit(event: string, data: AnyObject = {}) {\n this.broker?.emit(event, data);\n }\n\n public static schedule(\n taskName: string,\n context: AnyObject,\n timeoutMs: number,\n exactDateTime?: Date,\n ) {\n this.broker?.schedule(taskName, context, timeoutMs, exactDateTime);\n }\n\n public static throttle(\n taskName: string,\n context: AnyObject,\n intervalMs: number,\n leading = false,\n startDateTime?: Date,\n ) {\n this.broker?.throttle(\n taskName,\n context,\n intervalMs,\n leading,\n startDateTime,\n );\n }\n\n public static get(taskName: string): Task | undefined {\n return this.registry?.tasks.get(taskName);\n }\n\n /**\n * Creates and registers a new task with the specified parameters and options.\n * Tasks are the basic building blocks of Cadenza graphs and are responsible for executing logic.\n * See {@link Task} for more information.\n *\n * @param {string} name - The unique name of the task.\n * @param {TaskFunction} func - The function to be executed by the task.\n * @param {string} [description] - An optional description for the task.\n * @param {TaskOptions} [options={}] - Configuration options for the task, such as concurrency, timeout, and retry settings.\n * @return {Task} The created task instance.\n *\n * @example\n * You can use arrow functions to create tasks.\n * ```ts\n * const task = Cadenza.createTask('My task', (ctx) => {\n * console.log('My task executed with context:', ctx);\n * }, 'My task description');\n * ```\n *\n * You can also use named functions to create tasks.\n * This is the preferred way to create tasks since it allows for code inspection in the CadenzaUI.\n * ```ts\n * function myTask(ctx) {\n * console.log('My task executed with context:', ctx);\n * }\n *\n * const task = Cadenza.createTask('My task', myTask);\n * ```\n *\n * ** Use the TaskOptions object to configure the task. **\n *\n * With concurrency limit, timeout limit and retry settings.\n * ```ts\n * Cadenza.createTask('My task', (ctx) => {\n * console.log('My task executed with context:', ctx);\n * }, 'My task description', {\n * concurrency: 10,\n * timeout: 10000,\n * retryCount: 3,\n * retryDelay: 1000,\n * retryDelayFactor: 1.5,\n * });\n * ```\n *\n * You can specify the input and output context schemas for the task.\n * ```ts\n * Cadenza.createTask('My task', (ctx) => {\n * return { bar: 'foo' + ctx.foo };\n * }, 'My task description', {\n * inputContextSchema: {\n * type: 'object',\n * properties: {\n * foo: {\n * type: 'string',\n * },\n * },\n * required: ['foo'],\n * },\n * validateInputContext: true, // default is false\n * outputContextSchema: {\n * type: 'object',\n * properties: {\n * bar: {\n * type: 'string',\n * },\n * },\n * required: ['bar'],\n * },\n * validateOutputContext: true, // default is false\n * });\n * ```\n */\n static createTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions = {},\n ): Task {\n this.bootstrap();\n this.validateName(name);\n\n options = {\n concurrency: 0,\n timeout: 0,\n register: true,\n isUnique: false,\n isMeta: false,\n isSubMeta: false,\n isHidden: false,\n getTagCallback: undefined,\n inputSchema: undefined,\n validateInputContext: false,\n outputSchema: undefined,\n validateOutputContext: false,\n retryCount: 0,\n retryDelay: 0,\n retryDelayMax: 0,\n retryDelayFactor: 1,\n ...options,\n };\n\n return new Task(\n name,\n func,\n description,\n options.concurrency,\n options.timeout,\n options.register,\n options.isUnique,\n options.isMeta,\n options.isSubMeta,\n options.isHidden,\n options.getTagCallback,\n options.inputSchema,\n options.validateInputContext,\n options.outputSchema,\n options.validateOutputContext,\n options.retryCount,\n options.retryDelay,\n options.retryDelayMax,\n options.retryDelayFactor,\n );\n }\n\n /**\n * Creates a meta task with the specified name, functionality, description, and options.\n * This is used for creating tasks that lives on the meta layer.\n * The meta layer is a special layer that is executed separately from the business logic layer and is used for extending Cadenzas core functionality.\n * See {@link Task} or {@link createTask} for more information.\n *\n * @param {string} name - The name of the meta task.\n * @param {TaskFunction} func - The function to be executed by the meta task.\n * @param {string} [description] - An optional description of the meta task.\n * @param {TaskOptions} [options={}] - Additional optional task configuration. Automatically sets `isMeta` to true.\n * @return {Task} A task instance configured as a meta task.\n */\n static createMetaTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions = {},\n ): Task {\n options.isMeta = true;\n return this.createTask(name, func, description, options);\n }\n\n /**\n * Creates a unique task by wrapping the provided task function with a uniqueness constraint.\n * Unique tasks are designed to execute once per execution ID, merging parents. This is useful for\n * tasks that require fan-in/joins after parallel branches.\n * See {@link Task} for more information.\n *\n * @param {string} name - The name of the task to be created.\n * @param {TaskFunction} func - The function that contains the logic for the task. It receives joinedContexts as a list in the context (context.joinedContexts).\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions} [options={}] - Optional configuration for the task, such as additional metadata or task options.\n * @return {Task} The task instance that was created with a uniqueness constraint.\n *\n * @example\n * ```ts\n * const splitTask = Cadenza.createTask('Split foos', function* (ctx) {\n * for (const foo of ctx.foos) {\n * yield { foo };\n * }\n * }, 'Splits a list of foos into multiple sub-branches');\n *\n * const processTask = Cadenza.createTask('Process foo', (ctx) => {\n * return { bar: 'foo' + ctx.foo };\n * }, 'Process a foo');\n *\n * const uniqueTask = Cadenza.createUniqueTask('Gather processed foos', (ctx) => {\n * // A unique task will always be provided with a list of contexts (ctx.joinedContexts) from its predecessors.\n * const processedFoos = ctx.joinedContexts.map((c) => c.bar);\n * return { foos: processedFoos };\n * }, 'Gathers together the processed foos.');\n *\n * splitTask.then(\n * processTask.then(\n * uniqueTask,\n * ),\n * );\n *\n * // Give the flow a name using a routine\n * Cadenza.createRoutine(\n * 'Process foos',\n * [splitTask],\n * 'Processes a list of foos'\n * ).doOn('main.received_foos'); // Subscribe to a signal\n *\n * // Trigger the flow from anywhere\n * Cadenza.emit('main.received_foos', { foos: ['foo1', 'foo2', 'foo3'] });\n * ```\n *\n */\n static createUniqueTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions = {},\n ): Task {\n options.isUnique = true;\n return this.createTask(name, func, description, options);\n }\n\n /**\n * Creates a unique meta task with the specified name, function, description, and options.\n * See {@link createUniqueTask} and {@link createMetaTask} for more information.\n *\n * @param {string} name - The name of the task to create.\n * @param {TaskFunction} func - The function to execute when the task is run.\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions} [options={}] - Optional settings for the task. Defaults to an empty object. Automatically sets `isMeta` and `isUnique` to true.\n * @return {Task} The created unique meta task.\n */\n static createUniqueMetaTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions = {},\n ): Task {\n options.isMeta = true;\n options.isUnique = true;\n return this.createUniqueTask(name, func, description, options);\n }\n\n /**\n * Creates a throttled task with a concurrency limit of 1, ensuring that only one instance of the task can run at a time for a specific throttle tag.\n * This is useful for ensuring execution order and preventing race conditions.\n * See {@link Task} for more information.\n *\n * @param {string} name - The name of the task.\n * @param {TaskFunction} func - The function to be executed when the task runs.\n * @param {ThrottleTagGetter} [throttledIdGetter=() => \"default\"] - A function that generates a throttle tag identifier to group tasks for throttling.\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions} [options={}] - Additional options to customize the task behavior.\n * @return {Task} The created throttled task.\n *\n * @example\n * ```ts\n * const task = Cadenza.createThrottledTask(\n * 'My task',\n * async (ctx) => {\n * await new Promise((resolve) => setTimeout(resolve, 1000));\n * console.log('My task executed with context:', ctx);\n * },\n * // Will throttle by the value of ctx.foo to make sure tasks with the same value are executed sequentially\n * (ctx) => ctx.foo,\n * );\n *\n * Cadenza.run(task, { foo: 'bar' }); // (First execution)\n * Cadenza.run(task, { foo: 'bar' }); // This will be executed after the first execution is finished\n * Cadenza.run(task, { foo: 'baz' }); // This will be executed in parallel with the first execution\n * ```\n */\n static createThrottledTask(\n name: string,\n func: TaskFunction,\n throttledIdGetter: ThrottleTagGetter = () => \"default\",\n description?: string,\n options: TaskOptions = {},\n ): Task {\n options.concurrency = 1;\n options.getTagCallback = throttledIdGetter;\n return this.createTask(name, func, description, options);\n }\n\n /**\n * Creates a throttled meta task with the specified configuration.\n * See {@link createThrottledTask} and {@link createMetaTask} for more information.\n *\n * @param {string} name - The name of the throttled meta task.\n * @param {TaskFunction} func - The task function to be executed.\n * @param {ThrottleTagGetter} throttledIdGetter - A function to retrieve the throttling identifier.\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions} [options={}] - Additional options for configuring the task.\n * @return {Task} The created throttled meta task.\n */\n static createThrottledMetaTask(\n name: string,\n func: TaskFunction,\n throttledIdGetter: ThrottleTagGetter,\n description?: string,\n options: TaskOptions = {},\n ): Task {\n options.isMeta = true;\n return this.createThrottledTask(\n name,\n func,\n throttledIdGetter,\n description,\n options,\n );\n }\n\n /**\n * Creates and returns a new debounced task with the specified parameters.\n * This is useful to prevent rapid execution of tasks that may be triggered by multiple events within a certain time frame.\n * See {@link DebounceTask} for more information.\n *\n * @param {string} name - The unique name of the task to be created.\n * @param {TaskFunction} func - The function to be executed by the task.\n * @param {string} [description] - An optional description of the task.\n * @param {number} [debounceTime=1000] - The debounce time in milliseconds to delay the execution of the task.\n * @param {TaskOptions & DebounceOptions} [options={}] - Additional configuration options for the task, including debounce behavior and other task properties.\n * @return {DebounceTask} A new instance of the DebounceTask with the specified configuration.\n *\n * @example\n * ```ts\n * const task = Cadenza.createDebounceTask(\n * 'My debounced task',\n * (ctx) => {\n * console.log('My task executed with context:', ctx);\n * },\n * 'My debounced task description',\n * 100, // Debounce time in milliseconds. Default is 1000\n * {\n * leading: false, // Should the first execution of a burst be executed immediately? Default is false\n * trailing: true, // Should the last execution of a burst be executed? Default is true\n * maxWait: 1000, // Maximum time in milliseconds to wait for the next execution. Default is 0\n * },\n * );\n *\n * Cadenza.run(task, { foo: 'bar' }); // This will not be executed\n * Cadenza.run(task, { foo: 'bar' }); // This will not be executed\n * Cadenza.run(task, { foo: 'baz' }); // This execution will be delayed by 100ms\n * ```\n */\n static createDebounceTask(\n name: string,\n func: TaskFunction,\n description?: string,\n debounceTime: number = 1000,\n options: TaskOptions & DebounceOptions = {},\n ): DebounceTask {\n this.bootstrap();\n this.validateName(name);\n\n options = {\n concurrency: 0,\n timeout: 0,\n register: true,\n leading: false,\n trailing: true,\n maxWait: 0,\n isUnique: false,\n isMeta: false,\n isSubMeta: false,\n isHidden: false,\n inputSchema: undefined,\n validateInputContext: false,\n outputSchema: undefined,\n validateOutputContext: false,\n ...options,\n };\n\n return new DebounceTask(\n name,\n func,\n description,\n debounceTime,\n options.leading,\n options.trailing,\n options.maxWait,\n options.concurrency,\n options.timeout,\n options.register,\n options.isUnique,\n options.isMeta,\n options.isSubMeta,\n options.isHidden,\n options.inputSchema,\n options.validateInputContext,\n options.outputSchema,\n options.validateOutputContext,\n );\n }\n\n /**\n * Creates a debounced meta task with the specified parameters.\n * See {@link createDebounceTask} and {@link createMetaTask} for more information.\n *\n * @param {string} name - The name of the task.\n * @param {TaskFunction} func - The function to be executed by the task.\n * @param {string} [description] - Optional description of the task.\n * @param {number} [debounceTime=1000] - The debounce delay in milliseconds.\n * @param {TaskOptions & DebounceOptions} [options={}] - Additional configuration options for the task.\n * @return {DebounceTask} Returns an instance of the debounced meta task.\n */\n static createDebounceMetaTask(\n name: string,\n func: TaskFunction,\n description?: string,\n debounceTime: number = 1000,\n options: TaskOptions & DebounceOptions = {},\n ): DebounceTask {\n options.isMeta = true;\n return this.createDebounceTask(\n name,\n func,\n description,\n debounceTime,\n options,\n );\n }\n\n /**\n * Creates an ephemeral task with the specified configuration.\n * Ephemeral tasks are designed to self-destruct after execution or a certain condition is met.\n * This is useful for transient tasks such as resolving promises or performing cleanup operations.\n * They are not registered by default.\n * See {@link EphemeralTask} for more information.\n *\n * @param {string} name - The name of the task to be created.\n * @param {TaskFunction} func - The function that defines the logic of the task.\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions & EphemeralTaskOptions} [options={}] - The configuration options for the task, including concurrency, timeouts, and retry policies.\n * @return {EphemeralTask} The created ephemeral task instance.\n *\n * @example\n * By default, ephemeral tasks are executed once and destroyed after execution.\n * ```ts\n * const task = Cadenza.createEphemeralTask('My ephemeral task', (ctx) => {\n * console.log('My task executed with context:', ctx);\n * });\n *\n * Cadenza.run(task); // Executes the task once and destroys it after execution\n * Cadenza.run(task); // Does nothing, since the task is destroyed\n * ```\n *\n * Use destroy condition to conditionally destroy the task\n * ```ts\n * const task = Cadenza.createEphemeralTask(\n * 'My ephemeral task',\n * (ctx) => {\n * console.log('My task executed with context:', ctx);\n * },\n * 'My ephemeral task description',\n * {\n * once: false, // Should the task be executed only once? Default is true\n * destroyCondition: (ctx) => ctx.foo > 10, // Should the task be destroyed after execution? Default is undefined\n * },\n * );\n *\n * Cadenza.run(task, { foo: 5 }); // The task will not be destroyed and can still be executed\n * Cadenza.run(task, { foo: 10 }); // The task will not be destroyed and can still be executed\n * Cadenza.run(task, { foo: 20 }); // The task will be destroyed after execution and cannot be executed anymore\n * Cadenza.run(task, { foo: 30 }); // This will not be executed\n * ```\n *\n * A practical use case for ephemeral tasks is to resolve a promise upon some external event.\n * ```ts\n * const task = Cadenza.createTask('Confirm something', (ctx, emit) => {\n * return new Promise((resolve) => {\n * ctx.foo = uuid();\n *\n * Cadenza.createEphemeralTask(`Resolve promise of ${ctx.foo}`, (c) => {\n * console.log('My task executed with context:', ctx);\n * resolve(c);\n * }).doOn(`socket.confirmation_received:${ctx.foo}`);\n *\n * emit('this_domain.confirmation_requested', ctx);\n * });\n * });\n * ```\n */\n static createEphemeralTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions & EphemeralTaskOptions = {},\n ): EphemeralTask {\n this.bootstrap();\n this.validateName(name);\n\n options = {\n concurrency: 0,\n timeout: 0,\n register: true,\n isUnique: false,\n isMeta: false,\n isSubMeta: false,\n isHidden: false,\n once: true,\n destroyCondition: () => true,\n getTagCallback: undefined,\n inputSchema: undefined,\n validateInputContext: false,\n outputSchema: undefined,\n validateOutputContext: false,\n retryCount: 0,\n retryDelay: 0,\n retryDelayMax: 0,\n retryDelayFactor: 1,\n ...options,\n };\n\n return new EphemeralTask(\n name,\n func,\n description,\n options.once,\n options.destroyCondition,\n options.concurrency,\n options.timeout,\n options.register,\n options.isUnique,\n options.isMeta,\n options.isSubMeta,\n options.isHidden,\n options.getTagCallback,\n options.inputSchema,\n options.validateInputContext,\n options.outputSchema,\n options.validateOutputContext,\n options.retryCount,\n options.retryDelay,\n options.retryDelayMax,\n options.retryDelayFactor,\n );\n }\n\n /**\n * Creates an ephemeral meta task with the specified name, function, description, and options.\n * See {@link createEphemeralTask} and {@link createMetaTask} for more details.\n *\n * @param {string} name - The name of the task to be created.\n * @param {TaskFunction} func - The function to be executed as part of the task.\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions & EphemeralTaskOptions} [options={}] - Additional options for configuring the task.\n * @return {EphemeralTask} The created ephemeral meta task.\n */\n static createEphemeralMetaTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions & EphemeralTaskOptions = {},\n ): EphemeralTask {\n options.isMeta = true;\n return this.createEphemeralTask(name, func, description, options);\n }\n\n /**\n * Creates a new routine with the specified name, tasks, and an optional description.\n * Routines are named entry points to starting tasks and are registered in the GraphRegistry.\n * They are used to group tasks together and provide a high-level structure for organizing and managing the execution of a set of tasks.\n * See {@link GraphRoutine} for more information.\n *\n * @param {string} name - The name of the routine to create.\n * @param {Task[]} tasks - A list of tasks to include in the routine.\n * @param {string} [description=\"\"] - An optional description for the routine.\n * @return {GraphRoutine} A new instance of the GraphRoutine containing the specified tasks and description.\n *\n * @example\n * ```ts\n * const task1 = Cadenza.createTask(\"Task 1\", () => {});\n * const task2 = Cadenza.createTask(\"Task 2\", () => {});\n *\n * task1.then(task2);\n *\n * const routine = Cadenza.createRoutine(\"Some routine\", [task1]);\n *\n * Cadenza.run(routine);\n *\n * // Or, routines can be triggered by signals\n * routine.doOn(\"some.signal\");\n *\n * Cadenza.emit(\"some.signal\", {});\n * ```\n */\n static createRoutine(\n name: string,\n tasks: Task[],\n description: string = \"\",\n ): GraphRoutine {\n this.bootstrap();\n this.validateName(name);\n if (tasks.length === 0) {\n throw new Error(`Routine '${name}' created with no starting tasks.`);\n }\n return new GraphRoutine(name, tasks, description);\n }\n\n /**\n * Creates a meta routine with a given name, tasks, and optional description.\n * Routines are named entry points to starting tasks and are registered in the GraphRegistry.\n * They are used to group tasks together and provide a high-level structure for organizing and managing the execution of a set of tasks.\n * See {@link GraphRoutine} and {@link createRoutine} for more information.\n *\n * @param {string} name - The name of the routine to be created.\n * @param {Task[]} tasks - An array of tasks that the routine will consist of.\n * @param {string} [description=\"\"] - An optional description for the routine.\n * @return {GraphRoutine} A new instance of the `GraphRoutine` representing the created routine.\n * @throws {Error} If no starting tasks are provided.\n */\n static createMetaRoutine(\n name: string,\n tasks: Task[],\n description: string = \"\",\n ): GraphRoutine {\n this.bootstrap();\n this.validateName(name);\n if (tasks.length === 0) {\n throw new Error(`Routine '${name}' created with no starting tasks.`);\n }\n return new GraphRoutine(name, tasks, description, true);\n }\n\n static reset() {\n this.broker?.reset();\n this.registry?.reset();\n this.isBootstrapped = false;\n }\n}\n","import Task from \"./Task\";\n\nexport default class SignalTask extends Task {\n constructor(signal: string, description: string = \"\") {\n super(signal, () => true, description);\n\n this.signalsToEmitAfter.add(signal);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOO,SAAS,gBACd,OACA,YAAsC,MAAM,OACzC;AACH,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,oBAAI,QAAkB;AAEtC,QAAM,QAA2D,CAAC;AAClE,QAAM,SAAS,MAAM,QAAQ,KAAK,IAAI,CAAC,IAAI,CAAC;AAE5C,QAAM,KAAK,EAAE,QAAQ,OAAO,QAAQ,OAAO,CAAC;AAC5C,UAAQ,IAAI,OAAO,MAAM;AAEzB,SAAO,MAAM,QAAQ;AACnB,UAAM,EAAE,QAAQ,QAAQ,IAAI,IAAI,MAAM,IAAI;AAC1C,UAAM,gBAAgB,QAAQ,SAAY,OAAO,GAAG,IAAI;AAExD;AAAA;AAAA,MAEE,QAAQ,kBACR,QAAQ,qBACR,QAAQ,UACR,QAAQ,aACR,QAAQ,WACR,QAAQ,cACR,QAAQ,gBACR,QAAQ;AAAA,MACR;AACA,aAAO,GAAG,IAAI;AACd;AAAA,IACF;AAEA,eAAW,CAAC,GAAG,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AAC/C,UAAI,UAAU,CAAC,EAAG;AAElB,UAAI,SAAS,OAAO,UAAU,UAAU;AACtC,YAAI,QAAQ,IAAI,KAAK,GAAG;AACtB,wBAAc,CAAC,IAAI,QAAQ,IAAI,KAAK;AACpC;AAAA,QACF;AAEA,cAAM,cAAc,MAAM,QAAQ,KAAK,IAAI,CAAC,IAAI,CAAC;AACjD,sBAAc,CAAC,IAAI;AACnB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,IACrE;AACA,WAAO,IAAI,aAAa,MAAM,OAAO,aAAa,IAAI;AAAA,EACxD;AAAA,EAEA,OAAO,QAAQ;AACb,SAAK,QAAQ,MAAM;AACnB,SAAK,UAAU,MAAM;AACrB,SAAK,iBAAiB;AAAA,EACxB;AACF;AAnxBqB,QAKZ,iBAAiB;AALL,QAMZ,OAAoB;;;AC5C7B,IAAqB,aAArB,cAAwC,KAAK;AAAA,EAC3C,YAAY,QAAgB,cAAsB,IAAI;AACpD,UAAM,QAAQ,MAAM,MAAM,WAAW;AAErC,SAAK,mBAAmB,IAAI,MAAM;AAAA,EACpC;AACF;;;AhCiBA,IAAO,gBAAQ;","names":["uuid","import_uuid","import_uuid","task","uuid","import_uuid","import_uuid","uuid","uuid","context","result","outputValidation","tasks","import_uuid","uuid","uuid"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils/tools.ts","../src/engine/SignalBroker.ts","../src/engine/GraphRunner.ts","../src/engine/GraphRun.ts","../src/utils/ColorRandomizer.ts","../src/engine/exporters/vue-flow/VueFlowExportVisitor.ts","../src/engine/exporters/vue-flow/VueFlowExporter.ts","../src/graph/execution/GraphNode.ts","../src/graph/context/GraphContext.ts","../src/graph/iterators/GraphNodeIterator.ts","../src/interfaces/SignalEmitter.ts","../src/utils/promise.ts","../src/graph/definition/GraphRoutine.ts","../src/graph/definition/Task.ts","../src/graph/iterators/TaskIterator.ts","../src/registry/GraphRegistry.ts","../src/graph/definition/DebounceTask.ts","../src/graph/definition/EphemeralTask.ts","../src/interfaces/ExecutionChain.ts","../src/graph/iterators/GraphLayerIterator.ts","../src/interfaces/GraphLayer.ts","../src/graph/execution/SyncGraphLayer.ts","../src/interfaces/GraphBuilder.ts","../src/engine/builders/GraphBreadthFirstBuilder.ts","../src/interfaces/GraphRunStrategy.ts","../src/engine/ThrottleEngine.ts","../src/graph/execution/AsyncGraphLayer.ts","../src/engine/builders/GraphAsyncQueueBuilder.ts","../src/engine/strategy/GraphAsyncRun.ts","../src/engine/strategy/GraphStandardRun.ts","../src/Cadenza.ts","../src/graph/definition/SignalTask.ts"],"sourcesContent":["import Cadenza, { CadenzaMode, TaskOptions } from \"./Cadenza\";\nimport GraphRun from \"./engine/GraphRun\";\nimport GraphRunner from \"./engine/GraphRunner\";\nimport SignalBroker from \"./engine/SignalBroker\";\nimport GraphContext from \"./graph/context/GraphContext\";\nimport DebounceTask, { DebounceOptions } from \"./graph/definition/DebounceTask\";\nimport EphemeralTask, {\n EphemeralTaskOptions,\n} from \"./graph/definition/EphemeralTask\";\nimport GraphRoutine from \"./graph/definition/GraphRoutine\";\nimport SignalTask from \"./graph/definition/SignalTask\";\nimport Task, {\n TaskFunction,\n TaskResult,\n ThrottleTagGetter,\n} from \"./graph/definition/Task\";\nimport SignalEmitter from \"./interfaces/SignalEmitter\";\nimport GraphRegistry from \"./registry/GraphRegistry\";\nimport { AnyObject } from \"./types/global\";\nimport {\n SchemaConstraints,\n SchemaDefinition,\n SchemaType,\n} from \"./types/schema\";\n\nexport default Cadenza;\nexport type {\n TaskResult,\n TaskOptions,\n AnyObject,\n SchemaDefinition,\n SchemaConstraints,\n SchemaType,\n ThrottleTagGetter,\n CadenzaMode,\n TaskFunction,\n DebounceOptions,\n EphemeralTaskOptions,\n};\nexport {\n Task,\n GraphRoutine,\n DebounceTask,\n EphemeralTask,\n SignalTask,\n SignalEmitter,\n GraphContext,\n GraphRegistry,\n GraphRun,\n SignalBroker,\n GraphRunner,\n};\n","/**\n * Creates a deep clone of the given input object or array, while allowing specific keys to be filtered out based on a provided criteria.\n *\n * @param {T} input The input data to be cloned. It can be an object or an array.\n * @param {(key: string) => boolean} [filterOut] A callback function to determine which keys should be excluded from the cloned structure. It receives the key as a parameter and should return `true` to exclude the key, or `false` to include it. Default is a function that includes all keys (`() => false`).\n * @return {T} Returns a deep clone of the input object or array with the specified keys filtered out.\n */\nexport function deepCloneFilter<T>(\n input: T,\n filterOut: (key: string) => boolean = () => false,\n): T {\n if (input === null || typeof input !== \"object\") {\n return input;\n }\n\n const visited = new WeakMap<any, any>(); // For cycle detection\n\n const stack: Array<{ source: any; target: any; key?: string }> = [];\n const output = Array.isArray(input) ? [] : {};\n\n stack.push({ source: input, target: output });\n visited.set(input, output);\n\n while (stack.length) {\n const { source, target, key } = stack.pop()!;\n const currentTarget = key !== undefined ? target[key] : target;\n\n if (\n // TODO Should probably not be done like this...\n key === \"taskInstance\" ||\n key === \"routineInstance\" ||\n key === \"task\" ||\n key === \"routine\" ||\n key === \"tasks\" ||\n key === \"routines\" ||\n key === \"httpServer\" ||\n key === \"httpsServer\"\n ) {\n target[key] = source;\n continue;\n }\n\n for (const [k, value] of Object.entries(source)) {\n if (filterOut(k)) continue;\n\n if (value && typeof value === \"object\") {\n if (visited.has(value)) {\n currentTarget[k] = visited.get(value); // Cycle: link to existing clone\n continue;\n }\n\n const clonedValue = Array.isArray(value) ? [] : {};\n currentTarget[k] = clonedValue;\n visited.set(value, clonedValue);\n\n stack.push({ source: value, target: currentTarget, key: k });\n } else {\n currentTarget[k] = value;\n }\n }\n }\n\n return output as T;\n}\n\n/**\n * Converts a given timestamp to an ISO 8601 formatted string.\n *\n * @param {number} timestamp - The timestamp in milliseconds to be formatted.\n * @return {string} The ISO 8601 formatted date string.\n */\nexport function formatTimestamp(timestamp: number) {\n return new Date(timestamp).toISOString();\n}\n","import GraphRunner from \"./GraphRunner\";\nimport { AnyObject, ThrottleHandle } from \"../types/global\";\nimport Task from \"../graph/definition/Task\";\nimport GraphRoutine from \"../graph/definition/GraphRoutine\";\nimport Cadenza from \"../Cadenza\";\nimport { formatTimestamp } from \"../utils/tools\";\nimport { v4 as uuid } from \"uuid\";\n\n/**\n * This class manages signals and observers, enabling communication across different parts of an application.\n * It follows a singleton design pattern, allowing for centralized signal management.\n */\nexport default class SignalBroker {\n static instance_: SignalBroker;\n\n static get instance(): SignalBroker {\n if (!this.instance_) {\n this.instance_ = new SignalBroker();\n }\n return this.instance_;\n }\n\n debug: boolean = false;\n verbose: boolean = false;\n\n setDebug(value: boolean) {\n this.debug = value;\n }\n\n setVerbose(value: boolean) {\n this.verbose = value;\n }\n\n /**\n * Validates the provided signal name string to ensure it adheres to specific formatting rules.\n * Throws an error if any of the validation checks fail.\n *\n * @param {string} signalName - The signal name to be validated.\n * @return {void} - Returns nothing if the signal name is valid.\n * @throws {Error} - Throws an error if the signal name is longer than 100 characters, contains spaces,\n * contains backslashes, or contains uppercase letters in restricted parts of the name.\n */\n validateSignalName(signalName: string) {\n if (signalName.length > 100) {\n throw new Error(\n `Signal name must be less than 100 characters: ${signalName}`,\n );\n }\n\n if (signalName.includes(\" \")) {\n throw new Error(`Signal name must not contain spaces: ${signalName}\"`);\n }\n\n if (signalName.includes(\"\\\\\")) {\n throw new Error(\n `Signal name must not contain backslashes: ${signalName}`,\n );\n }\n\n if (/[A-Z]/.test(signalName.split(\":\")[0].split(\".\").slice(1).join(\".\"))) {\n throw new Error(\n `Signal name must not contain uppercase letters in the middle of the signal name. It is only allowed in the first part of the signal name: ${signalName}`,\n );\n }\n }\n\n runner: GraphRunner | undefined;\n metaRunner: GraphRunner | undefined;\n\n public clearSignalsTask: Task | undefined;\n public getSignalsTask: Task | undefined;\n public registerSignalTask: Task | undefined;\n\n // TODO: Signals should be a class with a the observers, registered flag and other data.\n signalObservers: Map<\n string,\n {\n fn: (\n runner: GraphRunner,\n tasks: (Task | GraphRoutine)[],\n context: AnyObject,\n ) => void;\n tasks: Set<Task | GraphRoutine>;\n registered: boolean;\n }\n > = new Map();\n\n emitStacks: Map<string, Map<string, AnyObject>> = new Map(); // execId -> emitted signals\n\n constructor() {\n this.addSignal(\"meta.signal_broker.added\");\n }\n\n /**\n * Initializes with runners.\n * @param runner Standard runner for user signals.\n * @param metaRunner Meta runner for 'meta.' signals (suppresses further meta-emits).\n */\n bootstrap(runner: GraphRunner, metaRunner: GraphRunner): void {\n this.runner = runner;\n this.metaRunner = metaRunner;\n }\n\n /**\n * Initializes and sets up the various tasks for managing and processing signals.\n *\n * @return {void} This method does not return a value.\n */\n init() {\n this.clearSignalsTask = Cadenza.createDebounceMetaTask(\n \"Execute and clear queued signals\",\n () => {\n for (const [id, signals] of this.emitStacks.entries()) {\n signals.forEach((context, signal) => {\n this.execute(signal, context);\n signals.delete(signal);\n });\n\n this.emitStacks.delete(id);\n }\n return true;\n },\n \"Executes queued signals and clears the stack\",\n )\n .doOn(\"meta.process_signal_queue_requested\")\n .emits(\"meta.signal_broker.queue_empty\");\n\n this.getSignalsTask = Cadenza.createMetaTask(\"Get signals\", (ctx) => {\n const uniqueSignals = Array.from(this.signalObservers.keys()).filter(\n (s) => !s.includes(\":\"),\n );\n\n const processedSignals = uniqueSignals.map((signal) => ({\n signal,\n data: {\n registered: this.signalObservers.get(signal)?.registered ?? false,\n },\n }));\n\n return {\n signals: processedSignals,\n ...ctx,\n };\n });\n\n this.registerSignalTask = Cadenza.createMetaTask(\n \"Register signal\",\n (ctx) => {\n const { signalName } = ctx;\n this.signalObservers.get(signalName)!.registered = true;\n },\n ).doOn(\"meta.signal.registered\");\n }\n\n /**\n * Observes a signal with a routine/task.\n * @param signal The signal (e.g., 'domain.action', 'domain.*' for wildcards).\n * @param routineOrTask The observer.\n * @edge Duplicates ignored; supports wildcards for broad listening.\n */\n observe(signal: string, routineOrTask: Task | GraphRoutine): void {\n this.addSignal(signal);\n this.signalObservers.get(signal)!.tasks.add(routineOrTask);\n }\n\n /**\n * Unsubscribes a routine/task from a signal.\n * @param signal The signal.\n * @param routineOrTask The observer.\n * @edge Removes all instances if duplicate; deletes if empty.\n */\n unsubscribe(signal: string, routineOrTask: Task | GraphRoutine): void {\n const obs = this.signalObservers.get(signal);\n if (obs) {\n obs.tasks.delete(routineOrTask);\n if (obs.tasks.size === 0) {\n this.signalObservers.delete(signal);\n }\n }\n }\n\n /**\n * Schedules a signal to be emitted after a specified delay or at an exact date and time.\n *\n * @param {string} signal - The name of the signal to be emitted.\n * @param {AnyObject} context - The context to be passed along with the signal.\n * @param {number} [timeoutMs=60000] - The delay in milliseconds before the signal is emitted. Defaults to 60,000 ms.\n * @param {Date} [exactDateTime] - An exact date and time at which to emit the signal. If provided, this overrides the `timeoutMs`.\n * @return {AbortController} An AbortController instance that can be used to cancel the scheduled signal emission.\n */\n schedule(\n signal: string,\n context: AnyObject,\n timeoutMs: number = 60_000,\n exactDateTime?: Date,\n ): AbortController {\n // 1. Compute the final delay\n let delay = timeoutMs;\n if (exactDateTime != null) {\n delay = exactDateTime.getTime() - Date.now();\n }\n delay = Math.max(0, timeoutMs);\n\n // 2. Create an AbortController so the caller can cancel\n const controller = new AbortController();\n const { signal: signalController } = controller;\n\n const tick = () => this.emit(signal, context);\n\n const timerId = setTimeout(() => {\n if (!signalController.aborted) tick();\n }, delay);\n\n // 3. Cleanup on abort\n signalController.addEventListener(\"abort\", () => clearTimeout(timerId));\n\n return controller; // caller can do `const ac = obj.schedule(...); ac.abort();`\n }\n\n /**\n * Emits `signal` repeatedly with a fixed interval.\n *\n * @param signal\n * @param context\n * @param intervalMs\n * @param leading If true, emits immediately (unless a startDateTime is given and we are before it).\n * @param startDateTime Optional absolute Date when the *first* emission after `leading` should occur.\n * @returns a handle with `clear()` to stop the loop.\n */\n throttle(\n signal: string,\n context: AnyObject,\n intervalMs: number = 60_000,\n leading = false,\n startDateTime?: Date,\n ): ThrottleHandle {\n if (intervalMs <= 0) {\n throw new Error(\"intervalMs must be a positive number\");\n }\n\n const emit = () => this.emit(signal, context);\n\n if (leading) {\n const now = Date.now();\n const start = startDateTime?.getTime();\n\n // If we have a startDateTime and we are already past it → fire now\n if (!start || start <= now) {\n emit();\n }\n }\n\n let firstDelay = intervalMs;\n if (startDateTime) {\n // Find the *next* slot that is >= now\n let slot = startDateTime.getTime();\n const now = Date.now();\n\n while (slot < now) {\n slot += intervalMs;\n }\n firstDelay = slot - now;\n }\n\n let timer: NodeJS.Timeout | null = null;\n let stopped = false;\n\n const scheduleNext = () => {\n if (stopped) return;\n emit();\n timer = setTimeout(scheduleNext, intervalMs);\n };\n\n timer = setTimeout(scheduleNext, firstDelay);\n\n return {\n clear() {\n stopped = true;\n if (timer !== null) clearTimeout(timer);\n },\n };\n }\n\n /**\n * Emits a signal with the specified context, triggering any associated handlers for that signal.\n *\n * @param {string} signal - The name of the signal to emit.\n * @param {AnyObject} [context={}] - An optional context object containing additional information or metadata\n * associated with the signal. If the context includes a `__routineExecId`, it will be handled accordingly.\n * @return {void} This method does not return a value.\n */\n emit(signal: string, context: AnyObject = {}): void {\n const execId = context.__routineExecId || \"global\"; // Assume from metadata\n delete context.__routineExecId;\n\n if (!this.emitStacks.has(execId)) this.emitStacks.set(execId, new Map());\n const stack = this.emitStacks.get(execId)!;\n stack.set(signal, context);\n\n this.addSignal(signal);\n\n let executed = false;\n try {\n executed = this.execute(signal, context);\n } finally {\n if (executed) stack.delete(signal);\n if (stack.size === 0) this.emitStacks.delete(execId);\n }\n }\n\n /**\n * Executes a signal by emitting events, updating context, and invoking listeners.\n * Creates a new execution trace if necessary and updates the context with relevant metadata.\n * Handles specific, hierarchy-based, and wildcard signals.\n *\n * @param {string} signal - The signal name to be executed, potentially including namespaces or tags (e.g., \"meta.*\" or \"signal:type\").\n * @param {AnyObject} context - An object containing relevant metadata and execution details used for handling the signal.\n * @return {boolean} Returns true if any listeners were successfully executed, otherwise false.\n */\n execute(signal: string, context: AnyObject): boolean {\n const isMeta = signal.includes(\"meta.\");\n const isSubMeta = signal.includes(\"sub_meta.\") || context.__isSubMeta;\n const isMetric = context.__signalEmission?.isMetric;\n\n const executionTraceId =\n context.__signalEmission?.executionTraceId ??\n context.__metadata?.__executionTraceId ??\n context.__executionTraceId ??\n uuid();\n\n if (!isSubMeta && (!isMeta || this.debug)) {\n const isNewTrace =\n !context.__signalEmission?.executionTraceId &&\n !context.__metadata?.__executionTraceId &&\n !context.__executionTraceId;\n\n if (isNewTrace) {\n this.emit(\"sub_meta.signal_broker.new_trace\", {\n data: {\n uuid: executionTraceId,\n issuer_type: \"service\", // TODO: Add issuer type\n issuer_id:\n context.__metadata?.__issuerId ?? context.__issuerId ?? null,\n issued_at: formatTimestamp(Date.now()),\n intent: context.__metadata?.__intent ?? context.__intent ?? null,\n context: {\n id: uuid(),\n context: context,\n },\n is_meta: isMeta,\n },\n metadata: {\n __executionTraceId: executionTraceId,\n },\n });\n }\n\n context.__metadata = {\n ...context.__metadata,\n __executionTraceId: executionTraceId,\n };\n\n const emittedAt = Date.now();\n\n const signalParts = signal.split(\":\");\n const signalName = signalParts[0];\n const signalTag = signalParts.length > 1 ? signalParts[1] : null;\n context.__signalEmission = {\n ...(context.__signalEmission ?? {}),\n uuid: uuid(),\n executionTraceId,\n signalName,\n signalTag,\n emittedAt: formatTimestamp(emittedAt),\n consumed: false,\n consumedBy: null,\n isMeta,\n };\n\n this.emit(\"sub_meta.signal_broker.emitting_signal\", { ...context });\n } else if (isSubMeta) {\n context.__isSubMeta = true;\n }\n\n context.__metadata = {\n ...context.__metadata,\n __executionTraceId: executionTraceId,\n };\n\n if (this.debug && ((!isMetric && !isSubMeta) || this.verbose)) {\n console.log(\n `EMITTING ${signal} to listeners ${this.signalObservers.get(signal)?.tasks.size ?? 0} with context ${this.verbose ? JSON.stringify(context) : JSON.stringify(context).slice(0, 100)}`,\n );\n }\n\n let executed;\n executed = this.executeListener(signal, context); // Exact signal\n\n if (!isSubMeta) {\n const parts = signal\n .slice(0, Math.max(signal.lastIndexOf(\":\"), signal.lastIndexOf(\".\")))\n .split(\".\");\n for (let i = parts.length; i > -1; i--) {\n const parent = parts.slice(0, i).join(\".\");\n executed = this.executeListener(parent + \".*\", context) || executed; // Wildcard\n }\n }\n\n return executed;\n }\n\n /**\n * Executes the tasks associated with a given signal and context.\n * It processes both normal and meta tasks depending on the signal type\n * and the availability of the appropriate runner.\n *\n * @param {string} signal - The signal identifier that determines which tasks to execute.\n * @param {AnyObject} context - The context object passed to the task execution function.\n * @return {boolean} - Returns true if tasks were executed; otherwise, false.\n */\n executeListener(signal: string, context: AnyObject): boolean {\n const obs = this.signalObservers.get(signal);\n if (!obs || obs.tasks.size === 0) {\n return false;\n }\n\n const isMeta = signal.startsWith(\"meta\");\n if (!isMeta) {\n const tasks: Task[] = [];\n const metaTasks: Task[] = [];\n\n obs.tasks.forEach(\n (\n task, // @ts-ignore\n ) => (task.isMeta ? metaTasks.push(task) : tasks.push(task)),\n );\n\n if (tasks.length && this.runner) {\n obs.fn(this.runner, tasks, context);\n }\n\n if (metaTasks.length && this.metaRunner) {\n obs.fn(this.metaRunner, metaTasks, context);\n }\n\n return true;\n } else if (this.metaRunner) {\n obs.fn(this.metaRunner, Array.from(obs.tasks), context);\n return true;\n }\n\n return false;\n }\n\n /**\n * Adds a signal to the signalObservers for tracking and execution.\n * Performs validation on the signal name and emits a meta signal event when added.\n * If the signal contains a namespace (denoted by a colon \":\"), its base signal is\n * also added if it doesn't already exist.\n *\n * @param {string} signal - The name of the signal to be added.\n * @return {void} This method does not return any value.\n */\n addSignal(signal: string): void {\n let _signal = signal;\n if (!this.signalObservers.has(_signal)) {\n this.validateSignalName(_signal);\n this.signalObservers.set(_signal, {\n fn: (\n runner: GraphRunner,\n tasks: (Task | GraphRoutine)[],\n context: AnyObject,\n ) => runner.run(tasks, context),\n tasks: new Set(),\n registered: false,\n });\n\n const sections = _signal.split(\":\");\n if (sections.length === 2) {\n _signal = sections[0];\n\n if (!this.signalObservers.has(sections[0])) {\n this.signalObservers.set(_signal, {\n fn: (\n runner: GraphRunner,\n tasks: (Task | GraphRoutine)[],\n context: AnyObject,\n ) => runner.run(tasks, context),\n tasks: new Set(),\n registered: false,\n });\n } else {\n return;\n }\n }\n\n this.emit(\"meta.signal_broker.added\", { signalName: _signal });\n }\n }\n\n /**\n * Lists all observed signals.\n * @returns Array of signals.\n */\n listObservedSignals(): string[] {\n return Array.from(this.signalObservers.keys());\n }\n\n reset() {\n this.emitStacks.clear();\n this.signalObservers.clear();\n }\n}\n","import { v4 as uuid } from \"uuid\";\nimport Task from \"../graph/definition/Task\";\nimport GraphRun from \"./GraphRun\";\nimport GraphNode from \"../graph/execution/GraphNode\";\nimport GraphRunStrategy from \"../interfaces/GraphRunStrategy\";\nimport { AnyObject } from \"../types/global\";\nimport GraphRoutine from \"../graph/definition/GraphRoutine\";\nimport SignalEmitter from \"../interfaces/SignalEmitter\";\nimport Cadenza from \"../Cadenza\";\nimport GraphRegistry from \"../registry/GraphRegistry\";\nimport GraphContext from \"../graph/context/GraphContext\";\nimport { formatTimestamp } from \"../utils/tools\";\n\n/**\n * Represents a runner for managing and executing tasks or routines within a graph.\n * The `GraphRunner` extends `SignalEmitter` to include signal-based event-driven mechanisms.\n */\nexport default class GraphRunner extends SignalEmitter {\n currentRun: GraphRun;\n debug: boolean = false;\n verbose: boolean = false;\n isRunning: boolean = false;\n readonly isMeta: boolean = false;\n\n strategy: GraphRunStrategy;\n\n /**\n * Constructs a runner.\n * @param isMeta Meta flag (default false).\n * @edge Creates 'Start run' meta-task chained to registry gets.\n */\n constructor(isMeta: boolean = false) {\n super(isMeta);\n this.isMeta = isMeta;\n this.strategy = Cadenza.runStrategy.PARALLEL;\n this.currentRun = new GraphRun(this.strategy);\n }\n\n init() {\n if (this.isMeta) return;\n\n Cadenza.createMetaTask(\n \"Start run\",\n this.startRun.bind(this),\n \"Starts a run\",\n ).doAfter(\n GraphRegistry.instance.getTaskByName,\n GraphRegistry.instance.getRoutineByName,\n );\n }\n\n /**\n * Adds tasks or routines to the current execution pipeline. Supports both individual tasks,\n * routines, or arrays of tasks and routines. Handles metadata and execution context management.\n *\n * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} tasks - The task(s) or routine(s) to be added.\n * It can be a single task, a single routine, or an array of tasks and routines.\n * @param {AnyObject} [context={}] - Optional context object to provide execution trace and metadata.\n * Used to propagate information across task or routine executions.\n * @return {void} - This method does not return a value.\n */\n addTasks(\n tasks: Task | GraphRoutine | (Task | GraphRoutine)[],\n context: AnyObject = {},\n ): void {\n let _tasks = Array.isArray(tasks) ? tasks : [tasks];\n if (_tasks.length === 0) {\n console.warn(\"No tasks/routines to add.\");\n return;\n }\n\n let routineName = _tasks.map((t) => t.name).join(\" | \");\n let routineVersion = null;\n let isMeta = _tasks.every((t) => t.isMeta);\n\n const allTasks = _tasks.flatMap((t) => {\n if (t instanceof GraphRoutine) {\n routineName = t.name;\n routineVersion = t.version;\n isMeta = t.isMeta;\n const routineTasks: Task[] = [];\n t.forEachTask((task: Task) => routineTasks.push(task));\n return routineTasks;\n }\n return t;\n });\n\n const isSubMeta =\n allTasks.some((t) => t.isSubMeta) || !!context.__isSubMeta;\n context.__isSubMeta = isSubMeta;\n\n const isNewTrace =\n !context.__routineExecId &&\n !context.__metadata?.__executionTraceId &&\n !context.__executionTraceId;\n\n const executionTraceId =\n context.__metadata?.__executionTraceId ??\n context.__executionTraceId ??\n uuid();\n\n context.__executionTraceId = executionTraceId;\n\n const routineExecId = context.__routineExecId ?? uuid();\n context.__routineExecId = routineExecId;\n\n const ctx = new GraphContext(context || {});\n\n if (!isSubMeta) {\n const contextData = ctx.export();\n if (isNewTrace) {\n this.emitMetrics(\"meta.runner.new_trace\", {\n data: {\n uuid: executionTraceId,\n issuer_type: \"service\", // TODO: Add issuer type\n issuer_id:\n context.__metadata?.__issuerId ?? context.__issuerId ?? null,\n issued_at: formatTimestamp(Date.now()),\n intent: context.__metadata?.__intent ?? context.__intent ?? null,\n context: contextData,\n is_meta: isMeta,\n },\n __metadata: {\n __executionTraceId: executionTraceId,\n },\n });\n }\n\n this.emitMetrics(\"meta.runner.added_tasks\", {\n data: {\n uuid: routineExecId,\n name: routineName,\n routineVersion,\n isMeta,\n executionTraceId,\n context: isNewTrace ? contextData.id : contextData,\n previousRoutineExecution:\n context.__localRoutineExecId ??\n context.__metadata?.__routineExecId ??\n null, // TODO: There is a chance this is not added to the database yet...\n created: formatTimestamp(Date.now()),\n },\n __metadata: {\n __executionTraceId: executionTraceId,\n },\n });\n }\n\n allTasks.forEach((task) =>\n this.currentRun.addNode(\n new GraphNode(task, ctx, routineExecId, [], this.debug, this.verbose),\n ),\n );\n }\n\n /**\n * Executes the provided tasks or routines. Maintains the execution state\n * and handles synchronous or asynchronous processing.\n *\n * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} [tasks] - A single task, a single routine, or an array of tasks or routines to execute. Optional.\n * @param {AnyObject} [context] - An optional context object to be used during task execution.\n * @return {GraphRun|Promise<GraphRun>} - Returns a `GraphRun` instance if the execution is synchronous, or a `Promise` resolving to a `GraphRun` for asynchronous execution.\n */\n public run(\n tasks?: Task | GraphRoutine | (Task | GraphRoutine)[],\n context?: AnyObject,\n ): GraphRun | Promise<GraphRun> {\n if (tasks) {\n this.addTasks(tasks, context ?? {});\n }\n\n if (this.isRunning) {\n return this.currentRun;\n }\n\n if (this.currentRun) {\n this.isRunning = true;\n const runResult = this.currentRun.run();\n\n if (runResult instanceof Promise) {\n return this.runAsync(runResult);\n }\n }\n\n return this.reset();\n }\n\n /**\n * Executes the provided asynchronous operation and resets the state afterwards.\n *\n * @param {Promise<void>} run - A promise representing the asynchronous operation to execute.\n * @return {Promise<GraphRun>} A promise that resolves to the result of the reset operation after the asynchronous operation completes.\n */\n async runAsync(run: Promise<void>): Promise<GraphRun> {\n await run;\n return this.reset();\n }\n\n /**\n * Resets the current state of the graph, creating a new GraphRun instance\n * and returning the previous run instance.\n * If the debug mode is not enabled, it will destroy the existing resources.\n *\n * @return {GraphRun} The last GraphRun instance before the reset.\n */\n reset(): GraphRun {\n this.isRunning = false;\n\n const lastRun = this.currentRun;\n\n if (!this.debug) {\n this.destroy();\n }\n\n this.currentRun = new GraphRun(this.strategy);\n\n return lastRun;\n }\n\n public setDebug(value: boolean): void {\n this.debug = value;\n }\n\n public setVerbose(value: boolean): void {\n this.verbose = value;\n }\n\n public destroy(): void {\n this.currentRun.destroy();\n }\n\n /**\n * Sets the strategy to be used for running the graph and initializes\n * the current run with the provided strategy if no process is currently running.\n *\n * @param {GraphRunStrategy} strategy - The strategy to use for running the graph.\n * @return {void}\n */\n public setStrategy(strategy: GraphRunStrategy): void {\n this.strategy = strategy;\n if (!this.isRunning) {\n this.currentRun = new GraphRun(this.strategy);\n }\n }\n\n // TODO This should not live here. This is deputy related.\n startRun(\n context: AnyObject,\n emit: (signal: string, ctx: AnyObject) => void,\n ): boolean {\n if (context.task || context.routine) {\n const routine = context.task ?? context.routine;\n delete context.task;\n delete context.routine;\n context.__routineExecId = context.__metadata?.__deputyExecId ?? null;\n context.__isDeputy = true;\n this.run(routine, context);\n return true;\n } else {\n context.errored = true;\n context.__error = \"No routine or task defined.\";\n emit(\"meta.runner.failed\", context);\n return false;\n }\n }\n}\n","import { v4 as uuid } from \"uuid\";\nimport GraphNode from \"../graph/execution/GraphNode\";\nimport GraphExporter from \"../interfaces/GraphExporter\";\nimport SyncGraphLayer from \"../graph/execution/SyncGraphLayer\";\nimport GraphRunStrategy from \"../interfaces/GraphRunStrategy\";\nimport GraphLayer from \"../interfaces/GraphLayer\";\nimport VueFlowExporter from \"./exporters/vue-flow/VueFlowExporter\";\n\nexport interface RunJson {\n __id: string;\n __label: string;\n __graph: any;\n __data: any;\n}\n\n/**\n * Represents a GraphRun instance which manages the execution of a graph-based workflow.\n * It utilizes a specific strategy and export mechanism to manage, execute, and export the graph data.\n */\nexport default class GraphRun {\n readonly id: string;\n graph: GraphLayer | undefined;\n // @ts-ignore\n strategy: GraphRunStrategy;\n exporter: GraphExporter | undefined;\n\n constructor(strategy: GraphRunStrategy) {\n this.id = uuid();\n this.strategy = strategy;\n this.strategy.setRunInstance(this);\n this.exporter = new VueFlowExporter();\n }\n\n setGraph(graph: GraphLayer) {\n this.graph = graph;\n }\n\n addNode(node: GraphNode) {\n this.strategy.addNode(node);\n }\n\n // Composite function / Command execution\n run(): void | Promise<void> {\n return this.strategy.run();\n }\n\n // Composite function\n destroy() {\n this.graph?.destroy();\n this.graph = undefined;\n this.exporter = undefined;\n }\n\n // Composite function\n log() {\n console.log(\"vvvvvvvvvvvvvvvvv\");\n console.log(\"GraphRun\");\n console.log(\"vvvvvvvvvvvvvvvvv\");\n this.graph?.log();\n console.log(\"=================\");\n }\n\n // Memento\n export(): RunJson {\n if (this.exporter && this.graph) {\n const data = this.strategy.export();\n return {\n __id: this.id,\n __label: data.__startTime ?? this.id,\n __graph: this.exporter?.exportGraph(this.graph as SyncGraphLayer),\n __data: data,\n };\n }\n\n return {\n __id: this.id,\n __label: this.id,\n __graph: undefined,\n __data: {},\n };\n }\n\n // Export Strategy\n setExporter(exporter: GraphExporter) {\n this.exporter = exporter;\n }\n}\n","export default class ColorRandomizer {\n numberOfSteps: number;\n stepCounter = 0;\n spread: number;\n range: number;\n\n constructor(numberOfSteps: number = 200, spread: number = 30) {\n this.numberOfSteps = numberOfSteps;\n this.spread = spread;\n this.range = Math.floor(numberOfSteps / this.spread);\n }\n\n rainbow(numOfSteps: number, step: number) {\n // This function generates vibrant, \"evenly spaced\" colours (i.e. no clustering). This is ideal for creating easily distinguishable vibrant markers in Google Maps and other apps.\n // Adam Cole, 2011-Sept-14\n // HSV to RBG adapted from: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript\n let r, g, b;\n const h = step / numOfSteps;\n const i = ~~(h * 6);\n const f = h * 6 - i;\n const q = 1 - f;\n switch (i % 6) {\n case 0:\n r = 1;\n g = f;\n b = 0;\n break;\n case 1:\n r = q;\n g = 1;\n b = 0;\n break;\n case 2:\n r = 0;\n g = 1;\n b = f;\n break;\n case 3:\n r = 0;\n g = q;\n b = 1;\n break;\n case 4:\n r = f;\n g = 0;\n b = 1;\n break;\n case 5:\n r = 1;\n g = 0;\n b = q;\n break;\n default:\n r = 0;\n g = 0;\n b = 0;\n break;\n }\n // @ts-ignore\n const c =\n \"#\" +\n (\"00\" + (~~(r * 255)).toString(16)).slice(-2) +\n (\"00\" + (~~(g * 255)).toString(16)).slice(-2) +\n (\"00\" + (~~(b * 255)).toString(16)).slice(-2);\n return c;\n }\n\n getRandomColor() {\n this.stepCounter++;\n\n if (this.stepCounter > this.numberOfSteps) {\n this.stepCounter = 1;\n }\n\n const randomStep =\n ((this.stepCounter * this.range) % this.numberOfSteps) -\n this.range +\n Math.floor(this.stepCounter / this.spread);\n\n return this.rainbow(this.numberOfSteps, randomStep);\n }\n}\n","import GraphVisitor from \"../../../interfaces/GraphVisitor\";\nimport SyncGraphLayer from \"../../../graph/execution/SyncGraphLayer\";\nimport GraphNode from \"../../../graph/execution/GraphNode\";\nimport Task from \"../../../graph/definition/Task\";\nimport ColorRandomizer from \"../../../utils/ColorRandomizer\";\n\nexport default class VueFlowExportVisitor implements GraphVisitor {\n nodeCount = 0;\n elements: any[] = [];\n index = 0;\n numberOfLayerNodes = 0;\n contextToColor: { [id: string]: string } = {};\n colorRandomizer = new ColorRandomizer();\n\n visitLayer(layer: SyncGraphLayer): any {\n const snapshot = layer.export();\n\n this.numberOfLayerNodes = snapshot.__numberOfNodes;\n this.index = 0;\n }\n\n visitNode(node: GraphNode): any {\n const snapshot = node.export();\n\n if (!this.contextToColor[snapshot.__context.id]) {\n this.contextToColor[snapshot.__context.id] =\n this.colorRandomizer.getRandomColor();\n }\n\n const color = this.contextToColor[snapshot.__context.id];\n\n this.elements.push({\n id: snapshot.__id.slice(0, 8),\n label: snapshot.__task.__name,\n position: {\n x: snapshot.__task.__layerIndex * 500,\n y: -50 * this.numberOfLayerNodes * 0.5 + (this.index * 60 + 30),\n },\n sourcePosition: \"right\",\n targetPosition: \"left\",\n style: { backgroundColor: `${color}`, width: \"180px\" },\n data: {\n executionTime: snapshot.__executionTime,\n executionStart: snapshot.__executionStart,\n executionEnd: snapshot.__executionEnd,\n description: snapshot.__task.__description,\n functionString: snapshot.__task.__functionString,\n context: snapshot.__context.context,\n layerIndex: snapshot.__task.__layerIndex,\n },\n });\n\n for (const [index, nextNodeId] of snapshot.__nextNodes.entries()) {\n this.elements.push({\n id: `${snapshot.__id.slice(0, 8)}-${index}`,\n source: snapshot.__id.slice(0, 8),\n target: nextNodeId.slice(0, 8),\n });\n }\n\n this.index++;\n this.nodeCount++;\n }\n\n visitTask(task: Task) {\n const snapshot = task.export();\n\n this.elements.push({\n id: snapshot.__id.slice(0, 8),\n label: snapshot.__name,\n position: { x: snapshot.__layerIndex * 300, y: this.index * 50 + 30 },\n sourcePosition: \"right\",\n targetPosition: \"left\",\n data: {\n description: snapshot.__description,\n functionString: snapshot.__functionString,\n layerIndex: snapshot.__layerIndex,\n },\n });\n\n for (const [index, nextTaskId] of snapshot.__nextTasks.entries()) {\n this.elements.push({\n id: `${snapshot.__id.slice(0, 8)}-${index}`,\n source: snapshot.__id.slice(0, 8),\n target: nextTaskId.slice(0, 8),\n });\n }\n\n this.index++;\n this.nodeCount++;\n }\n\n getElements() {\n return this.elements;\n }\n\n getNodeCount() {\n return this.nodeCount;\n }\n}\n","import GraphExporter from \"../../../interfaces/GraphExporter\";\nimport SyncGraphLayer from \"../../../graph/execution/SyncGraphLayer\";\nimport VueFlowExportVisitor from \"./VueFlowExportVisitor\";\nimport Task from \"../../../graph/definition/Task\";\n\nexport default class VueFlowExporter implements GraphExporter {\n exportGraph(graph: SyncGraphLayer): any {\n const exporterVisitor = new VueFlowExportVisitor();\n const layers = graph.getIterator();\n while (layers.hasNext()) {\n const layer = layers.next();\n layer.accept(exporterVisitor);\n }\n\n return {\n elements: exporterVisitor.getElements(),\n numberOfNodes: exporterVisitor.getNodeCount(),\n };\n }\n\n exportStaticGraph(graph: Task[]) {\n const exporterVisitor = new VueFlowExportVisitor();\n\n let prevTask = null;\n for (const task of graph) {\n if (task === prevTask) {\n continue;\n }\n\n const tasks = task.getIterator();\n const exportedTaskNames: string[] = [];\n\n while (tasks.hasNext()) {\n const task = tasks.next();\n if (task && !exportedTaskNames.includes(task.name)) {\n exportedTaskNames.push(task.name);\n task.accept(exporterVisitor);\n }\n }\n\n prevTask = task;\n }\n\n return {\n elements: exporterVisitor.getElements(),\n numberOfNodes: exporterVisitor.getNodeCount(),\n };\n }\n}\n","import { v4 as uuid } from \"uuid\";\nimport Task, { TaskResult } from \"../definition/Task\";\nimport GraphContext from \"../context/GraphContext\";\nimport Graph from \"../../interfaces/Graph\";\nimport GraphVisitor from \"../../interfaces/GraphVisitor\";\nimport GraphNodeIterator from \"../iterators/GraphNodeIterator\";\nimport SignalEmitter from \"../../interfaces/SignalEmitter\";\nimport GraphLayer from \"../../interfaces/GraphLayer\";\nimport { AnyObject } from \"../../types/global\";\nimport { sleep } from \"../../utils/promise\";\nimport { formatTimestamp } from \"../../utils/tools\";\n\n/**\n * Represents a node in a graph structure used for executing tasks.\n * A Node is a container for a task and its associated context, providing\n * methods for executing the task and managing its lifecycle.\n *\n * It extends the SignalEmitter class to emit and handle signals related to\n * the node's lifecycle, such as \"meta.node.started\" and \"meta.node.completed\".\n *\n * It also implements the Graph interface, allowing it to be used as a part of\n * a graph structure, such as a GraphLayer or GraphRoutine.\n *\n * @extends SignalEmitter\n * @implements Graph\n */\nexport default class GraphNode extends SignalEmitter implements Graph {\n id: string;\n routineExecId: string;\n executionTraceId: string;\n task: Task;\n context: GraphContext;\n layer: GraphLayer | undefined;\n divided: boolean = false;\n splitGroupId: string = \"\";\n processing: boolean = false;\n subgraphComplete: boolean = false;\n graphComplete: boolean = false;\n result: TaskResult = false;\n retryCount: number = 0;\n retryDelay: number = 0;\n retries: number = 0;\n previousNodes: GraphNode[] = [];\n nextNodes: GraphNode[] = [];\n executionTime: number = 0;\n executionStart: number = 0;\n failed: boolean = false;\n errored: boolean = false;\n destroyed: boolean = false;\n debug: boolean = false;\n verbose: boolean = false;\n\n constructor(\n task: Task,\n context: GraphContext,\n routineExecId: string,\n prevNodes: GraphNode[] = [],\n debug: boolean = false,\n verbose: boolean = false,\n ) {\n super(\n (task.isMeta && !debug) ||\n task.isSubMeta ||\n context?.getMetadata()?.__isSubMeta,\n );\n this.id = uuid();\n this.task = task;\n this.context = context;\n this.retryCount = task.retryCount;\n this.retryDelay = task.retryDelay;\n this.previousNodes = prevNodes;\n this.routineExecId = routineExecId;\n this.splitGroupId = routineExecId;\n this.debug = debug;\n this.verbose = verbose;\n const ctx = context.getMetadata();\n this.executionTraceId =\n ctx.__executionTraceId ?? ctx.__metadata?.__executionTraceId;\n\n if (!this.task || !this.task.validateInput) {\n console.log(\"task not found\", this.task, this.context);\n }\n }\n\n setDebug(value: boolean) {\n this.debug = value;\n }\n\n public isUnique() {\n return this.task.isUnique;\n }\n\n public isMeta() {\n return this.task.isMeta;\n }\n\n public isProcessed() {\n return this.divided;\n }\n\n public isProcessing() {\n return this.processing;\n }\n\n public subgraphDone() {\n return this.subgraphComplete;\n }\n\n public graphDone() {\n return this.graphComplete;\n }\n\n /**\n * Compares the current GraphNode instance with another GraphNode to determine if they are considered equal.\n *\n * @param {GraphNode} node - The GraphNode object to compare with the current instance.\n * @return {boolean} Returns true if the nodes share the same task, context, and belong to the same graph; otherwise, false.\n */\n public isEqualTo(node: GraphNode) {\n return (\n this.sharesTaskWith(node) &&\n this.sharesContextWith(node) &&\n this.isPartOfSameGraph(node)\n );\n }\n\n /**\n * Determines if the given node is part of the same graph as the current node.\n *\n * @param {GraphNode} node - The node to compare with the current node.\n * @return {boolean} Returns true if the provided node is part of the same graph\n * (i.e., has the same routineExecId), otherwise false.\n */\n public isPartOfSameGraph(node: GraphNode) {\n return this.routineExecId === node.routineExecId;\n }\n\n /**\n * Determines whether the current instance shares a task with the provided node.\n *\n * @param {GraphNode} node - The graph node to compare with the current instance.\n * @return {boolean} Returns true if the task names of both nodes match, otherwise false.\n */\n public sharesTaskWith(node: GraphNode) {\n return this.task.name === node.task.name;\n }\n\n /**\n * Determines whether the current node shares the same context as the specified node.\n *\n * @param {GraphNode} node - The graph node to compare with the current node's context.\n * @return {boolean} True if both nodes share the same context; otherwise, false.\n */\n public sharesContextWith(node: GraphNode) {\n return this.context.id === node.context.id;\n }\n\n public getLayerIndex() {\n return this.task.layerIndex;\n }\n\n public getConcurrency() {\n return this.task.concurrency;\n }\n\n /**\n * Retrieves the tag associated with the current task and context.\n *\n * @return {string} The tag retrieved from the task within the given context.\n */\n public getTag() {\n return this.task.getTag(this.context);\n }\n\n /**\n * Schedules the current node/task on the specified graph layer if applicable.\n *\n * This method assesses whether the current node/task should be scheduled\n * on the given graph layer. It ensures that tasks are only scheduled\n * under certain conditions, such as checking if the task shares\n * execution contexts or dependencies with other nodes, and handles\n * various metadata emissions and context updates during the scheduling process.\n *\n * @param {GraphLayer} layer - The graph layer on which the current task should be scheduled.\n * @returns {void} Does not return a value.\n */\n public scheduleOn(layer: GraphLayer) {\n let shouldSchedule = true;\n const nodes = layer.getNodesByRoutineExecId(this.routineExecId);\n for (const node of nodes) {\n if (node.isEqualTo(this)) {\n shouldSchedule = false;\n break;\n }\n\n if (node.sharesTaskWith(this) && node.isUnique()) {\n node.consume(this);\n shouldSchedule = false;\n break;\n }\n }\n\n if (shouldSchedule) {\n this.layer = layer;\n layer.add(this);\n\n const context = this.context.getFullContext();\n\n const scheduledAt = Date.now();\n this.emitMetricsWithMetadata(\"meta.node.scheduled\", {\n data: {\n uuid: this.id,\n routineExecutionId: this.routineExecId,\n executionTraceId: this.executionTraceId,\n context:\n this.previousNodes.length === 0\n ? this.context.id\n : this.context.export(),\n taskName: this.task.name,\n taskVersion: this.task.version,\n isMeta: this.isMeta(),\n isScheduled: true,\n splitGroupId: this.splitGroupId,\n created: formatTimestamp(scheduledAt),\n },\n });\n\n this.previousNodes.forEach((node) => {\n this.emitMetricsWithMetadata(\"meta.node.mapped\", {\n data: {\n taskExecutionId: this.id,\n previousTaskExecutionId: node.id,\n },\n filter: {\n taskName: this.task.name,\n taskVersion: this.task.version,\n predecessorTaskName: node.task.name,\n predecessorTaskVersion: node.task.version,\n },\n });\n });\n\n if (!this.silent && context.__previousTaskExecutionId) {\n this.emitMetricsWithMetadata(\n \"meta.node.detected_previous_task_execution\",\n {\n data: {\n taskExecutionId: this.id,\n previousTaskExecutionId: context.__previousTaskExecutionId,\n },\n filter: {\n taskName: this.task.name,\n taskVersion: this.task.version,\n },\n ...context,\n },\n );\n context.__previousTaskExecutionId = null;\n }\n\n if (\n context.__signalEmission?.consumed === false &&\n (!this.isMeta() || this.debug)\n ) {\n this.emitMetricsWithMetadata(\"meta.node.consumed_signal\", {\n data: {\n signalEmissionId: context.__signalEmission.uuid,\n signalName: context.__signalEmission.signalName,\n signalTag: context.__signalEmission.signalTag,\n taskName: this.task.name,\n taskVersion: this.task.version,\n taskExecutionId: this.id,\n routineExecutionId: this.routineExecId,\n executionTraceId: this.executionTraceId,\n consumedAt: formatTimestamp(scheduledAt),\n },\n });\n\n context.__signalEmission.consumed = true;\n context.__signalEmission.consumedBy = this.id;\n }\n }\n }\n\n /**\n * Starts the execution process by initializing the execution start timestamp,\n * emitting relevant metadata, and logging debug information if applicable.\n *\n * The method performs the following actions:\n * 1. Sets the execution start timestamp if it's not already initialized.\n * 2. Emits metrics with metadata about the routine execution starting, including additional data if there are no previous nodes.\n * 3. Optionally logs debug or verbose information based on the current settings.\n * 4. Emits additional metrics to indicate that the execution has started.\n *\n * @return {number} The timestamp indicating when the execution started.\n */\n public start() {\n if (this.executionStart === 0) {\n this.executionStart = Date.now();\n }\n\n if (this.previousNodes.length === 0) {\n this.emitMetricsWithMetadata(\"meta.node.started_routine_execution\", {\n data: {\n isRunning: true,\n started: formatTimestamp(this.executionStart),\n },\n filter: { uuid: this.routineExecId },\n });\n }\n\n if (\n (this.debug &&\n !this.task.isSubMeta &&\n !this.context.getMetadata().__isSubMeta) ||\n this.verbose\n ) {\n this.log();\n }\n\n this.emitMetricsWithMetadata(\"meta.node.started\", {\n data: {\n isRunning: true,\n started: formatTimestamp(this.executionStart),\n },\n filter: { uuid: this.id },\n });\n\n return this.executionStart;\n }\n\n /**\n * Marks the end of an execution process, performs necessary cleanup, emits\n * metrics with associated metadata, and signals the completion of execution.\n * Also handles specific cases when the graph completes.\n *\n * @return {number} The timestamp corresponding to the end of execution. If execution\n * was not started, it returns 0.\n */\n public end() {\n if (this.executionStart === 0) {\n return 0;\n }\n\n this.processing = false;\n const end = Date.now();\n this.executionTime = end - this.executionStart;\n\n const context = this.context.getFullContext();\n\n if (this.errored || this.failed) {\n this.emitMetricsWithMetadata(\"meta.node.errored\", {\n data: {\n isRunning: false,\n errored: this.errored,\n failed: this.failed,\n errorMessage: context.__error,\n },\n filter: { uuid: this.id },\n });\n }\n\n this.emitMetricsWithMetadata(\"meta.node.ended\", {\n data: {\n isRunning: false,\n isComplete: true,\n resultContext: this.context.export(),\n errored: this.errored,\n failed: this.failed,\n errorMessage: context.__error,\n progress: 1.0,\n ended: formatTimestamp(end),\n },\n filter: { uuid: this.id },\n });\n\n if (this.graphDone()) {\n const context = this.context.export();\n if (context.context.__isDeputy)\n this.emitWithMetadata(\n `meta.node.graph_completed:${this.routineExecId}`,\n context.context,\n );\n\n // TODO Reminder, Service registry should be listening to this event, (updateSelf)\n this.emitMetricsWithMetadata(\"meta.node.ended_routine_execution\", {\n data: {\n isRunning: false,\n isComplete: true,\n resultContext: this.context.id,\n progress: 1.0,\n ended: formatTimestamp(end),\n },\n filter: { uuid: this.routineExecId },\n });\n }\n\n return end;\n }\n\n /**\n * Executes the main logic of the task, including input validation, processing, and post-processing.\n * Handles both synchronous and asynchronous workflows.\n *\n * @return {Array|Promise|undefined} Returns the next nodes to process if available.\n * If asynchronous processing is required, it returns a Promise that resolves to the next nodes.\n * Returns undefined in case of an error during input validation or preconditions that prevent processing.\n */\n public execute() {\n if (!this.divided && !this.processing) {\n this.processing = true;\n\n const inputValidation = this.task.validateInput(\n this.isMeta() ? this.context.getMetadata() : this.context.getContext(),\n );\n if (inputValidation !== true) {\n this.onError(inputValidation.__validationErrors);\n this.postProcess();\n return this.nextNodes;\n }\n\n this.result = this.work();\n\n if (this.result instanceof Promise) {\n return this.executeAsync();\n }\n\n const nextNodes = this.postProcess();\n if (nextNodes instanceof Promise) {\n return nextNodes;\n }\n\n this.nextNodes = nextNodes;\n }\n\n return this.nextNodes;\n }\n\n /**\n * Executes an asynchronous workflow that processes a result and retries on errors.\n * The method handles different result states, checks for error properties, and invokes\n * error handling when necessary.\n *\n * @return {Promise<void>} A promise that resolves when the operation completes successfully,\n * or rejects if an unhandled error occurs.\n */\n async workAsync() {\n try {\n this.result = await this.result;\n if (\n typeof this.result === \"object\" &&\n (this.result.hasOwnProperty(\"errored\") ||\n this.result.hasOwnProperty(\"failed\"))\n ) {\n const result = await this.retryAsync((this.result as any).__error);\n if (\n typeof result === \"object\" &&\n (result.hasOwnProperty(\"errored\") || result.hasOwnProperty(\"failed\"))\n ) {\n this.onError(result.__error);\n }\n }\n } catch (e: unknown) {\n const result = await this.retryAsync(e);\n if (result === e) {\n this.onError(e);\n }\n }\n }\n\n /**\n * Executes an asynchronous operation, processes the result, and determines the next nodes to execute.\n * This method will manage asynchronous work, handle post-processing of results, and ensure proper handling of both synchronous and asynchronous next node configurations.\n *\n * @return {Promise<any>} A promise resolving to the next nodes to be executed. Can be the result of post-processing or a directly resolved next nodes object.\n */\n async executeAsync() {\n await this.workAsync();\n const nextNodes = this.postProcess();\n if (nextNodes instanceof Promise) {\n return nextNodes;\n }\n this.nextNodes = nextNodes;\n return this.nextNodes;\n }\n\n /**\n * Executes the task associated with the current instance, using the given context,\n * progress callback, and metadata. If the task fails or an error occurs, it attempts\n * to retry the execution. If the retry is not successful, it propagates the error and\n * returns the result.\n *\n * @return {TaskResult | Promise<TaskResult>} The result of the task execution, or a\n * promise that resolves to the task result. This includes handling for retries on\n * failure and error propagation.\n */\n work(): TaskResult | Promise<TaskResult> {\n try {\n const result = this.task.execute(\n this.context,\n this.emitWithMetadata.bind(this),\n this.onProgress.bind(this),\n { nodeId: this.id, routineExecId: this.routineExecId },\n );\n\n if ((result as any)?.errored || (result as any)?.failed) {\n return this.retry(result);\n }\n\n return result;\n } catch (e: unknown) {\n const result = this.retry(e);\n return result.then((result) => {\n if (result !== e) {\n return result;\n }\n\n this.onError(e);\n return this.result;\n });\n }\n }\n\n /**\n * Emits a signal along with its associated metadata. The metadata includes\n * task-specific information such as task name, version, execution ID, and\n * additional context metadata like routine execution ID and execution trace ID.\n * This method is designed to enrich emitted signals with relevant details\n * before broadcasting them.\n *\n * @param {string} signal - The name of the signal to be emitted.\n * @param {AnyObject} data - The data object to be sent along with the signal. Metadata\n * will be injected into this object before being emitted.\n * @return {void} No return value.\n */\n emitWithMetadata(signal: string, data: AnyObject) {\n if (!this.task?.isHidden) {\n data.__signalEmission = {\n fullSignalName: signal,\n taskName: this.task.name,\n taskVersion: this.task.version,\n taskExecutionId: this.id,\n routineExecutionId: this.routineExecId,\n executionTraceId: this.executionTraceId,\n isMetric: false,\n };\n data.__metadata = {\n ...data.__metadata,\n __routineExecId: this.routineExecId,\n __executionTraceId: this.executionTraceId,\n };\n }\n\n this.emit(signal, data);\n\n if (!this.task.emitsSignals.has(signal)) {\n this.task.emitsSignals.add(signal);\n }\n }\n\n /**\n * Emits metrics with additional metadata describing the task execution and context.\n *\n * @param {string} signal - The signal name being emitted.\n * @param {AnyObject} data - The data associated with the signal emission, enriched with metadata.\n * @return {void} Emits the signal with enriched data and does not return a value.\n */\n emitMetricsWithMetadata(signal: string, data: AnyObject) {\n if (!this.task?.isHidden) {\n data.__signalEmission = {\n taskName: this.task.name,\n taskVersion: this.task.version,\n taskExecutionId: this.id,\n routineExecutionId: this.routineExecId,\n executionTraceId: this.executionTraceId,\n isMetric: true,\n };\n data.__metadata = {\n ...data.__metadata,\n __routineExecId: this.routineExecId,\n __executionTraceId: this.executionTraceId,\n };\n }\n\n this.emitMetrics(signal, data);\n\n if (!this.task.emitsSignals.has(signal)) {\n this.task.emitsSignals.add(signal);\n }\n }\n\n /**\n * Updates the progress of a task and emits metrics with associated metadata.\n *\n * @param {number} progress - A number representing the progress value, which will be clamped between 0 and 1.\n * @return {void} This method does not return a value.\n */\n onProgress(progress: number) {\n progress = Math.min(Math.max(0, progress), 1);\n\n this.emitMetricsWithMetadata(\"meta.node.progress\", {\n data: {\n progress,\n },\n filter: {\n uuid: this.id,\n },\n });\n\n this.emitMetricsWithMetadata(\n `meta.node.routine_execution_progress:${this.routineExecId}`,\n {\n data: {\n progress:\n (progress * this.task.progressWeight) /\n (this.layer?.getIdenticalNodes(this).length ?? 1),\n },\n filter: {\n uuid: this.routineExecId,\n },\n },\n );\n }\n\n /**\n * Processes the result of the current operation, validates it, and determines the next set of nodes.\n *\n * This method ensures that results of certain types such as strings or arrays\n * are flagged as errors. It divides the current context into subsequent nodes\n * for further processing. If the division returns a promise, it delegates the\n * processing to `postProcessAsync`. For synchronous division, it sets the\n * `nextNodes` and finalizes the operation.\n *\n * @return {(Array|undefined)} Returns an array of next nodes for further processing,\n * or undefined if no further processing is required.\n */\n postProcess() {\n if (typeof this.result === \"string\") {\n this.onError(\n `Returning strings is not allowed. Returned: ${this.result}`,\n );\n }\n\n if (Array.isArray(this.result)) {\n this.onError(`Returning arrays is not allowed. Returned: ${this.result}`);\n }\n\n const nextNodes = this.divide();\n\n if (nextNodes instanceof Promise) {\n return this.postProcessAsync(nextNodes);\n }\n\n this.nextNodes = nextNodes;\n this.finalize();\n return this.nextNodes;\n }\n\n /**\n * Asynchronously processes and finalizes the provided graph nodes.\n *\n * @param {Promise<GraphNode[]>} nextNodes A promise that resolves to an array of graph nodes to be processed.\n * @return {Promise<GraphNode[]>} A promise that resolves to the processed array of graph nodes.\n */\n async postProcessAsync(nextNodes: Promise<GraphNode[]>) {\n this.nextNodes = await nextNodes;\n this.finalize();\n return this.nextNodes;\n }\n\n /**\n * Finalizes the current task execution by determining if the task is complete, handles any errors or failures,\n * emits relevant signals based on the task outcomes, and ensures proper end of the task lifecycle.\n *\n * @return {void} Does not return a value.\n */\n finalize() {\n if (this.nextNodes.length === 0) {\n this.completeSubgraph();\n }\n\n if (this.errored || this.failed) {\n this.task.mapOnFailSignals((signal: string) =>\n this.emitWithMetadata(signal, this.context.getFullContext()),\n );\n } else if (this.result !== undefined && this.result !== false) {\n this.task.mapSignals((signal: string) =>\n this.emitWithMetadata(signal, this.context.getFullContext()),\n );\n }\n\n this.end();\n }\n\n /**\n * Handles an error event, processes the error, and updates the state accordingly.\n *\n * @param {unknown} error - The error object or message that occurred.\n * @param {AnyObject} [errorData={}] - Additional error data to include in the result.\n * @return {void} This method does not return any value.\n */\n onError(error: unknown, errorData: AnyObject = {}) {\n this.result = {\n ...this.context.getFullContext(),\n __error: `Node error: ${error}`,\n __retries: this.retries,\n error: `Node error: ${error}`,\n errored: true,\n returnedValue: this.result,\n ...errorData,\n };\n this.migrate(this.result);\n this.errored = true;\n }\n\n /**\n * Retries a task based on the defined retry count and delay time. If the retry count is 0, it immediately resolves with the provided previous result.\n *\n * @param {any} [prevResult] - The result from a previous attempt, if any, to return when no retries are performed.\n * @return {Promise<TaskResult>} - A promise that resolves with the result of the retried task or the previous result if no retries occur.\n */\n async retry(prevResult?: any): Promise<TaskResult> {\n if (this.retryCount === 0) {\n return prevResult;\n }\n\n await this.delayRetry();\n return this.work();\n }\n\n /**\n * Retries an asynchronous operation and returns its result.\n * If the retry count is zero, the method immediately returns the provided previous result.\n *\n * @param {any} [prevResult] - The optional result from a previous operation attempt, if applicable.\n * @return {Promise<TaskResult>} A promise that resolves to the result of the retried operation.\n */\n async retryAsync(prevResult?: any): Promise<TaskResult> {\n if (this.retryCount === 0) {\n return prevResult;\n }\n\n await this.delayRetry();\n this.result = this.work();\n return this.workAsync();\n }\n\n async delayRetry() {\n this.retryCount--;\n this.retries++;\n await sleep(this.retryDelay);\n this.retryDelay *= this.task.retryDelayFactor;\n if (\n this.task.retryDelayMax > 0 &&\n this.retryDelay > this.task.retryDelayMax\n ) {\n this.retryDelay = this.task.retryDelayMax;\n }\n }\n\n /**\n * Processes the result of a task by generating new nodes based on the task output.\n * The method handles synchronous and asynchronous generators, validates task output,\n * and creates new nodes accordingly. If errors occur, the method attempts to handle them\n * by generating alternative task nodes.\n *\n * @return {GraphNode[] | Promise<GraphNode[]>} Returns an array of generated GraphNode objects\n * (synchronously or wrapped in a Promise) based on the task result, or propagates errors if validation fails.\n */\n divide(): GraphNode[] | Promise<GraphNode[]> {\n const newNodes: GraphNode[] = [];\n\n if (\n (this.result as Generator)?.next &&\n typeof (this.result as Generator).next === \"function\"\n ) {\n const generator = this.result as Generator;\n let current = generator.next();\n if (current instanceof Promise) {\n return this.divideAsync(current);\n }\n\n while (!current.done && current.value !== undefined) {\n const outputValidation = this.task.validateOutput(current.value as any);\n if (outputValidation !== true) {\n this.onError(outputValidation.__validationErrors);\n break;\n } else {\n newNodes.push(...this.generateNewNodes(current.value));\n current = generator.next();\n }\n }\n } else if (this.result !== undefined && !this.errored) {\n newNodes.push(...this.generateNewNodes(this.result));\n\n if (typeof this.result !== \"boolean\") {\n const outputValidation = this.task.validateOutput(this.result as any);\n if (outputValidation !== true) {\n this.onError(outputValidation.__validationErrors);\n }\n\n this.divided = true;\n this.migrate({\n ...this.result,\n ...this.context.getMetadata(),\n __nextNodes: newNodes.map((n) => n.id),\n __retries: this.retries,\n });\n\n return newNodes;\n }\n }\n\n if (this.errored) {\n newNodes.push(\n ...this.task.mapNext(\n (t: Task) =>\n this.clone()\n .split(uuid())\n .differentiate(t)\n .migrate({ ...(this.result as any) }),\n true,\n ),\n );\n }\n\n this.divided = true;\n this.migrate({\n ...this.context.getFullContext(),\n __nextNodes: newNodes.map((n) => n.id),\n __retries: this.retries,\n });\n\n return newNodes;\n }\n\n /**\n * Processes an asynchronous iterator result, validates its output, and generates new graph nodes accordingly.\n * Additionally, continues to process and validate results from an asynchronous generator.\n *\n * @param {Promise<IteratorResult<any>>} current - A promise resolving to the current step result from an asynchronous iterator.\n * @return {Promise<GraphNode[]>} A promise resolving to an array of generated GraphNode objects based on validated outputs.\n */\n async divideAsync(\n current: Promise<IteratorResult<any>>,\n ): Promise<GraphNode[]> {\n const nextNodes: GraphNode[] = [];\n const _current = await current;\n\n const outputValidation = this.task.validateOutput(_current.value as any);\n if (outputValidation !== true) {\n this.onError(outputValidation.__validationErrors);\n return nextNodes;\n } else {\n nextNodes.push(...this.generateNewNodes(_current.value));\n }\n\n for await (const result of this.result as AsyncGenerator<any>) {\n const outputValidation = this.task.validateOutput(result);\n if (outputValidation !== true) {\n this.onError(outputValidation.__validationErrors);\n return [];\n } else {\n nextNodes.push(...this.generateNewNodes(result));\n }\n }\n\n this.divided = true;\n\n return nextNodes;\n }\n\n /**\n * Generates new nodes based on the provided result and task configuration.\n *\n * @param {any} result - The result of the previous operation, which determines the configuration and context for new nodes. It can be a boolean or an object containing details like failure, errors, or metadata.\n * @return {GraphNode[]} An array of newly generated graph nodes configured based on the task and context.\n */\n generateNewNodes(result: any) {\n const groupId = uuid();\n const newNodes = [];\n if (typeof result !== \"boolean\") {\n const failed =\n (result.failed !== undefined && result.failed) ||\n result.error !== undefined;\n newNodes.push(\n ...(this.task.mapNext((t: Task) => {\n const context = t.isUnique\n ? {\n joinedContexts: [\n { ...result, taskName: this.task.name, __nodeId: this.id },\n ],\n ...this.context.getMetadata(),\n }\n : { ...result, ...this.context.getMetadata() };\n return this.clone().split(groupId).differentiate(t).migrate(context);\n }, failed) as GraphNode[]),\n );\n\n this.failed = failed;\n } else {\n const shouldContinue = result;\n if (shouldContinue) {\n newNodes.push(\n ...(this.task.mapNext((t: Task) => {\n const newNode = this.clone().split(groupId).differentiate(t);\n if (t.isUnique) {\n newNode.migrate({\n joinedContexts: [\n {\n ...this.context.getContext(),\n taskName: this.task.name,\n __nodeId: this.id,\n },\n ],\n ...this.context.getMetadata(),\n });\n }\n\n return newNode;\n }) as GraphNode[]),\n );\n }\n }\n\n return newNodes;\n }\n\n /**\n * Executes the differentiation process based on a given task and updates the instance properties accordingly.\n *\n * @param {Task} task - The task object containing information such as retry count, retry delay, and metadata status.\n * @return {GraphNode} The updated instance after processing the task.\n */\n differentiate(task: Task): GraphNode {\n this.task = task;\n this.retryCount = task.retryCount;\n this.retryDelay = task.retryDelay;\n this.silent =\n (task.isMeta && !this.debug) ||\n task.isSubMeta ||\n this.context?.getMetadata()?.__isSubMeta;\n return this;\n }\n\n /**\n * Migrates the current instance to a new context and returns the updated instance.\n *\n * @param {any} ctx - The context data to be used for migration.\n * @return {GraphNode} The updated instance after migration.\n */\n migrate(ctx: any): GraphNode {\n this.context = new GraphContext(ctx);\n return this;\n }\n\n /**\n * Splits the current node into a new group identified by the provided ID.\n *\n * @param {string} id - The unique identifier for the new split group.\n * @return {GraphNode} The current instance of the GraphNode with the updated split group ID.\n */\n split(id: string): GraphNode {\n this.splitGroupId = id;\n return this;\n }\n\n /**\n * Creates a new instance of the GraphNode with the current node's properties.\n * This method allows for duplicating the existing graph node.\n *\n * @return {GraphNode} A new instance of GraphNode that is a copy of the current node.\n */\n public clone(): GraphNode {\n return new GraphNode(\n this.task,\n this.context,\n this.routineExecId,\n [this],\n this.debug,\n this.verbose,\n );\n }\n\n /**\n * Consumes the given graph node by combining contexts, merging previous nodes,\n * and performing associated operations on the provided node.\n *\n * @param {GraphNode} node - The graph node to be consumed.\n * @return {void} This method does not return a value.\n */\n public consume(node: GraphNode) {\n this.context = this.context.combine(node.context);\n this.previousNodes = this.previousNodes.concat(node.previousNodes);\n node.completeSubgraph();\n node.changeIdentity(this.id);\n node.destroy();\n }\n\n /**\n * Changes the identity of the current instance by updating the `id` property.\n *\n * @param {string} id - The new identity value to be assigned.\n * @return {void} Does not return a value.\n */\n changeIdentity(id: string) {\n this.id = id;\n }\n\n /**\n * Completes the subgraph for the current node and recursively for its previous nodes\n * once all next nodes have their subgraphs marked as done. If there are no previous nodes,\n * it completes the entire graph.\n *\n * @return {void} Does not return a value.\n */\n completeSubgraph() {\n for (const node of this.nextNodes) {\n if (!node.subgraphDone()) {\n return;\n }\n }\n\n this.subgraphComplete = true;\n\n if (this.previousNodes.length === 0) {\n this.completeGraph();\n return;\n }\n\n this.previousNodes.forEach((n) => n.completeSubgraph());\n }\n\n /**\n * Completes the current graph by setting a flag indicating the graph has been completed\n * and recursively completes all subsequent nodes in the graph.\n *\n * @return {void} Does not return a value.\n */\n completeGraph() {\n this.graphComplete = true;\n this.nextNodes.forEach((n) => n.completeGraph());\n }\n\n /**\n * Destroys the current instance by releasing resources, breaking references,\n * and resetting properties to ensure proper cleanup.\n *\n * @return {void} No return value.\n */\n public destroy() {\n // @ts-ignore\n this.context = null;\n // @ts-ignore\n this.task = null;\n this.nextNodes = [];\n this.previousNodes.forEach((n) =>\n n.nextNodes.splice(n.nextNodes.indexOf(this), 1),\n );\n this.previousNodes = [];\n this.result = undefined;\n this.layer = undefined;\n this.destroyed = true;\n }\n\n /**\n * Retrieves an iterator for traversing through the graph nodes.\n *\n * @return {GraphNodeIterator} An iterator instance specific to this graph node.\n */\n public getIterator() {\n return new GraphNodeIterator(this);\n }\n\n /**\n * Applies a callback function to each node in the `nextNodes` array and returns\n * the resulting array from the map operation.\n *\n * @param {function} callback - A function to execute on each `GraphNode` in the `nextNodes` array.\n * The function receives a `GraphNode` as its argument.\n * @return {Array} The resulting array after applying the callback function to each node in `nextNodes`.\n */\n public mapNext(callback: (node: GraphNode) => any) {\n return this.nextNodes.map(callback);\n }\n\n /**\n * Accepts a visitor object and calls its visitNode method with the current instance.\n *\n * @param {GraphVisitor} visitor - The visitor instance implementing the GraphVisitor interface.\n * @return {void} This method does not return a value.\n */\n public accept(visitor: GraphVisitor) {\n visitor.visitNode(this);\n }\n\n /**\n * Exports the current object's state and returns it in a serialized format.\n * The exported object contains metadata, task details, context information, execution times, node relationships, routine execution status, and other state information.\n *\n * @return {Object} An object representing the current state.\n */\n public export() {\n return {\n __id: this.id,\n __task: this.task.export(),\n __context: this.context.export(),\n __result: this.result,\n __executionTime: this.executionTime,\n __executionStart: this.executionStart,\n __executionEnd: this.executionStart + this.executionTime,\n __nextNodes: this.nextNodes.map((node) => node.id),\n __previousNodes: this.previousNodes.map((node) => node.id),\n __routineExecId: this.routineExecId,\n __isProcessing: this.processing,\n __isMeta: this.isMeta(),\n __graphComplete: this.graphComplete,\n __failed: this.failed,\n __errored: this.errored,\n __isUnique: this.isUnique(),\n __splitGroupId: this.splitGroupId,\n __tag: this.getTag(),\n };\n }\n\n lightExport() {\n return {\n __id: this.id,\n __task: {\n __name: this.task.name,\n __version: this.task.version,\n },\n __context: this.context.export(),\n __executionTime: this.executionTime,\n __executionStart: this.executionStart,\n __nextNodes: this.nextNodes.map((node) => node.id),\n __previousNodes: this.previousNodes.map((node) => node.id),\n __routineExecId: this.routineExecId,\n __isProcessing: this.processing,\n __graphComplete: this.graphComplete,\n __isMeta: this.isMeta(),\n __failed: this.failed,\n __errored: this.errored,\n __isUnique: this.isUnique(),\n __splitGroupId: this.splitGroupId,\n __tag: this.getTag(),\n };\n }\n\n public log() {\n try {\n console.log(\n \"Node EXECUTION:\",\n this.task.name,\n JSON.stringify(this.context.getFullContext()),\n );\n } catch (e) {\n console.log(\"Node EXECUTION:\", this.task.name, \"[circular context]\");\n }\n }\n}\n","import { v4 as uuid } from \"uuid\";\nimport { deepCloneFilter } from \"../../utils/tools\";\nimport { AnyObject } from \"../../types/global\";\n\n/**\n * Represents a context object used within a graph system.\n * Contexts are essentially a container for data that is relevant to a specific task or routine.\n * They are passed down the graph and can be used to store and manipulate data during the execution process.\n * The context is divided into full context, user data, and metadata.\n * Provides methods for accessing, cloning, mutating, combining, and exporting the context data.\n */\nexport default class GraphContext {\n readonly id: string;\n readonly fullContext: AnyObject; // Raw (for internal)\n readonly userData: AnyObject; // Filtered, frozen\n readonly metadata: AnyObject; // __keys, frozen\n\n constructor(context: AnyObject) {\n if (Array.isArray(context)) {\n throw new Error(\"Array contexts not supported\"); // Per clarification\n }\n this.fullContext = context;\n this.userData = Object.fromEntries(\n Object.entries(this.fullContext).filter(([key]) => !key.startsWith(\"__\")),\n );\n this.metadata = Object.fromEntries(\n Object.entries(this.fullContext).filter(([key]) => key.startsWith(\"__\")),\n );\n this.id = uuid();\n }\n\n /**\n * Gets frozen user data (read-only, no clone).\n * @returns Frozen user context.\n */\n getContext(): AnyObject {\n return this.userData;\n }\n\n /**\n * Clones the current user context data and returns a deep-cloned copy of it.\n *\n * @return {AnyObject} A deep-cloned copy of the user context data.\n */\n getClonedContext(): AnyObject {\n return deepCloneFilter(this.userData);\n }\n\n /**\n * Gets full raw context (cloned for safety).\n * @returns Cloned full context.\n */\n getFullContext(): AnyObject {\n return this.fullContext;\n }\n\n /**\n * Creates and returns a deep-cloned version of the fullContext object.\n *\n * @return {AnyObject} A deep copy of the fullContext instance, preserving all nested structures and data.\n */\n getClonedFullContext(): AnyObject {\n return deepCloneFilter(this.fullContext);\n }\n\n /**\n * Gets frozen metadata (read-only).\n * @returns Frozen metadata object.\n */\n getMetadata(): AnyObject {\n return this.metadata;\n }\n\n /**\n * Clones this context (new instance).\n * @returns New GraphContext.\n */\n clone(): GraphContext {\n return this.mutate(this.fullContext);\n }\n\n /**\n * Creates new context from data (via registry).\n * @param context New data.\n * @returns New GraphContext.\n */\n mutate(context: AnyObject): GraphContext {\n return new GraphContext(context);\n }\n\n /**\n * Combines the current GraphContext with another GraphContext, merging their user data\n * and full context into a new GraphContext instance.\n *\n * @param {GraphContext} otherContext - The other GraphContext to combine with the current one.\n * @return {GraphContext} A new GraphContext instance containing merged data from both contexts.\n */\n combine(otherContext: GraphContext): GraphContext {\n const newUser = { ...this.userData };\n newUser.joinedContexts = this.userData.joinedContexts\n ? [...this.userData.joinedContexts]\n : [this.userData];\n\n const otherUser = otherContext.userData;\n if (Array.isArray(otherUser.joinedContexts)) {\n newUser.joinedContexts.push(...otherUser.joinedContexts);\n } else {\n newUser.joinedContexts.push(otherUser);\n }\n\n const newFull = {\n ...this.fullContext,\n ...otherContext.fullContext,\n ...newUser,\n };\n return new GraphContext(newFull);\n }\n\n /**\n * Exports the context.\n * @returns Exported object.\n */\n export(): { id: string; context: AnyObject } {\n return {\n id: this.id,\n context: this.getFullContext(),\n };\n }\n}\n","import Iterator from \"../../interfaces/Iterator\";\nimport GraphNode from \"../execution/GraphNode\";\n\n/**\n * Represents an iterator for traversing nodes in a graph structure.\n * Implements the Iterator interface and allows traversal of nodes layer by layer.\n */\nexport default class GraphNodeIterator implements Iterator {\n currentNode: GraphNode | undefined;\n currentLayer: GraphNode[] = [];\n nextLayer: GraphNode[] = [];\n index: number = 0;\n\n constructor(node: GraphNode) {\n this.currentNode = node;\n this.currentLayer = [node];\n }\n\n hasNext(): boolean {\n return !!this.currentNode;\n }\n\n next(): any {\n const nextNode = this.currentNode;\n\n if (!nextNode) {\n return undefined;\n }\n\n this.nextLayer.push(...nextNode.mapNext((n: GraphNode) => n));\n\n this.index++;\n\n if (this.index === this.currentLayer.length) {\n this.currentLayer = this.nextLayer;\n this.nextLayer = [];\n this.index = 0;\n }\n\n this.currentNode = this.currentLayer.length\n ? this.currentLayer[this.index]\n : undefined;\n\n return nextNode;\n }\n}\n","import Cadenza from \"../Cadenza\";\nimport { AnyObject } from \"../types/global\";\n\n/**\n * Abstract class representing a signal emitter.\n * Allows emitting events or signals, with the option to suppress emissions if desired.\n */\nexport default abstract class SignalEmitter {\n silent: boolean;\n\n /**\n * Constructor for signal emitters.\n * @param silent If true, suppresses all emissions (e.g., for meta-runners to avoid loops; affects all emits).\n */\n constructor(silent: boolean = false) {\n this.silent = silent;\n }\n\n /**\n * Emits a signal via the broker.\n * @param signal The signal name.\n * @param data Optional payload (defaults to empty object).\n */\n emit(signal: string, data: AnyObject = {}): void {\n Cadenza.broker.emit(signal, data);\n }\n\n /**\n * Emits a signal via the broker if not silent.\n * @param signal The signal name.\n * @param data Optional payload (defaults to empty object).\n */\n emitMetrics(signal: string, data: AnyObject = {}): void {\n if (this.silent) {\n return;\n }\n Cadenza.broker.emit(signal, data);\n }\n}\n","/**\n * Pauses the execution of the program for the specified duration.\n *\n * @param {number} ms - The number of milliseconds to pause execution.\n * @return {Promise<void>} A promise that resolves after the specified duration has elapsed.\n */\nexport function sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import Task from \"./Task\";\nimport Cadenza from \"../../Cadenza\";\nimport SignalEmitter from \"../../interfaces/SignalEmitter\";\n\n/**\n * Represents a routine in a graph structure with tasks and signal observation capabilities.\n * Routines are named entrypoint for a sub-graph, describing the purpose for the subsequent flow.\n * Since Task names are specific to the task it performs, it doesn't describe the overall flow.\n * Routines, therefore are used to assign names to sub-flows that can be referenced using that name instead of the name of the task(s).\n * Extends SignalEmitter to emit and handle signals related to the routine's lifecycle and tasks.\n */\nexport default class GraphRoutine extends SignalEmitter {\n readonly name: string;\n version: number = 1;\n readonly description: string;\n readonly isMeta: boolean = false;\n tasks: Set<Task> = new Set();\n registered: boolean = false;\n\n observedSignals: Set<string> = new Set();\n\n constructor(\n name: string,\n tasks: Task[],\n description: string,\n isMeta: boolean = false,\n ) {\n super();\n this.name = name;\n this.description = description;\n this.isMeta = isMeta;\n this.emit(\"meta.routine.created\", {\n data: {\n name: this.name,\n version: this.version,\n description: this.description,\n isMeta: this.isMeta,\n },\n routineInstance: this,\n });\n tasks.forEach((t) => {\n this.tasks.add(t);\n\n const tasks = t.getIterator();\n\n while (tasks.hasNext()) {\n const task = tasks.next();\n if (!task) break;\n this.emit(\"meta.routine.task_added\", {\n data: {\n taskName: task.name,\n taskVersion: task.version,\n routineName: this.name,\n routineVersion: this.version,\n },\n });\n }\n });\n }\n\n /**\n * Iterates over each task in the `tasks` collection and applies the provided callback function.\n * If the callback returns a Promise, resolves all Promises concurrently.\n *\n * @param {function} callBack - A function to be executed on each task from the `tasks` collection.\n * The callback receives the current task as its argument.\n * @return {Promise<void>} A Promise that resolves once all callback executions, including asynchronous ones, are complete.\n */\n public async forEachTask(callBack: (task: Task) => any): Promise<void> {\n const promises = [];\n for (const task of this.tasks) {\n const res = callBack(task);\n if (res instanceof Promise) promises.push(res);\n }\n await Promise.all(promises);\n }\n\n /**\n * Sets global Version.\n * @param version The Version.\n */\n public setVersion(version: number): void {\n this.version = version;\n this.emit(\"meta.routine.global_version_set\", { version: this.version });\n }\n\n /**\n * Subscribes the current instance to the specified signals, enabling it to observe them.\n *\n * @param {...string} signals - The names of the signals to observe.\n * @return {this} Returns the instance to allow for method chaining.\n */\n doOn(...signals: string[]): this {\n signals.forEach((signal) => {\n if (this.observedSignals.has(signal)) return;\n Cadenza.broker.observe(signal, this as any);\n this.observedSignals.add(signal);\n });\n return this;\n }\n\n /**\n * Unsubscribes from all observed signals and clears the internal collection\n * of observed signals. This ensures that the instance is no longer listening\n * or reacting to any previously subscribed signals.\n *\n * @return {this} Returns the current instance for chaining purposes.\n */\n unsubscribeAll(): this {\n this.observedSignals.forEach((signal) =>\n Cadenza.broker.unsubscribe(signal, this as any),\n );\n this.observedSignals.clear();\n return this;\n }\n\n /**\n * Unsubscribes the current instance from the specified signals.\n *\n * @param {...string} signals - The signals to unsubscribe from.\n * @return {this} The current instance for method chaining.\n */\n unsubscribe(...signals: string[]): this {\n signals.forEach((signal) => {\n if (this.observedSignals.has(signal)) {\n Cadenza.broker.unsubscribe(signal, this as any);\n this.observedSignals.delete(signal);\n }\n });\n return this;\n }\n\n /**\n * Cleans up resources and emits an event indicating the destruction of the routine.\n *\n * This method unsubscribes from all events, clears the tasks list,\n * and emits a \"meta.routine.destroyed\" event with details of the destruction.\n *\n * @return {void}\n */\n public destroy(): void {\n this.unsubscribeAll();\n this.tasks.clear();\n this.emit(\"meta.routine.destroyed\", {\n data: { deleted: true },\n filter: { name: this.name, version: this.version },\n });\n }\n}\n","import { v4 as uuid } from \"uuid\";\nimport GraphContext from \"../context/GraphContext\";\nimport GraphVisitor from \"../../interfaces/GraphVisitor\";\nimport TaskIterator from \"../iterators/TaskIterator\";\nimport Graph from \"../../interfaces/Graph\";\nimport { AnyObject } from \"../../types/global\";\nimport { SchemaDefinition } from \"../../types/schema\";\nimport SignalEmitter from \"../../interfaces/SignalEmitter\";\nimport Cadenza from \"../../Cadenza\";\n\nexport type TaskFunction = (\n context: AnyObject,\n emit: (signal: string, context: AnyObject) => void,\n progressCallback: (progress: number) => void,\n) => TaskResult;\nexport type TaskResult = boolean | AnyObject | Generator | Promise<any> | void;\nexport type ThrottleTagGetter = (context?: AnyObject, task?: Task) => string;\n\n/**\n * Represents a task with a specific behavior, configuration, and lifecycle management.\n * Tasks are used to define units of work that can be executed and orchestrated.\n * Tasks can specify input/output validation, concurrency, retry policies, and more.\n * This class extends SignalEmitter and implements Graph, allowing tasks to emit and observe signals.\n */\nexport default class Task extends SignalEmitter implements Graph {\n readonly name: string;\n readonly description: string;\n version: number = 1;\n concurrency: number;\n timeout: number;\n readonly isMeta: boolean = false;\n readonly isSubMeta: boolean = false;\n readonly isHidden: boolean = false;\n readonly isUnique: boolean = false;\n readonly throttled: boolean = false;\n\n readonly isSignal: boolean = false;\n readonly isDeputy: boolean = false;\n readonly isEphemeral: boolean = false;\n readonly isDebounce: boolean = false;\n\n inputContextSchema: SchemaDefinition | undefined = undefined;\n validateInputContext: boolean = false;\n outputContextSchema: SchemaDefinition | undefined = undefined;\n validateOutputContext: boolean = false;\n\n readonly retryCount: number = 0;\n readonly retryDelay: number = 0;\n readonly retryDelayMax: number = 0;\n readonly retryDelayFactor: number = 1;\n\n layerIndex: number = 0;\n progressWeight: number = 0;\n nextTasks: Set<Task> = new Set();\n onFailTasks: Set<Task> = new Set();\n predecessorTasks: Set<Task> = new Set();\n destroyed: boolean = false;\n register: boolean = true;\n registered: boolean = false;\n registeredSignals: Set<string> = new Set();\n taskMapRegistration: Set<string> = new Set();\n\n emitsSignals: Set<string> = new Set();\n signalsToEmitAfter: Set<string> = new Set();\n signalsToEmitOnFail: Set<string> = new Set();\n observedSignals: Set<string> = new Set();\n\n readonly taskFunction: TaskFunction;\n\n /**\n * Constructs an instance of the task with the specified properties and configuration options.\n *\n * @param {string} name - The name of the task.\n * @param {TaskFunction} task - The function that represents the task logic.\n * @param {string} [description=\"\"] - A description of the task.\n * @param {number} [concurrency=0] - The number of concurrent executions allowed for the task.\n * @param {number} [timeout=0] - The maximum execution time for the task in milliseconds.\n * @param {boolean} [register=true] - Indicates if the task should be registered or not.\n * @param {boolean} [isUnique=false] - Specifies if the task should only allow one instance to exist at any time.\n * @param {boolean} [isMeta=false] - Indicates if the task is a meta-task.\n * @param {boolean} [isSubMeta=false] - Indicates if the task is a sub-meta-task.\n * @param {boolean} [isHidden=false] - Determines if the task is hidden and not exposed publicly.\n * @param {ThrottleTagGetter} [getTagCallback=undefined] - A callback to generate a throttle tag for the task.\n * @param {SchemaDefinition} [inputSchema=undefined] - The input schema for validating the task's input context.\n * @param {boolean} [validateInputContext=false] - Specifies if the input context should be validated against the input schema.\n * @param {SchemaDefinition} [outputSchema=undefined] - The output schema for validating the task's output context.\n * @param {boolean} [validateOutputContext=false] - Specifies if the output context should be validated against the output schema.\n * @param {number} [retryCount=0] - The number of retry attempts allowed for the task in case of failure.\n * @param {number} [retryDelay=0] - The initial delay (in milliseconds) between retry attempts.\n * @param {number} [retryDelayMax=0] - The maximum delay (in milliseconds) allowed between retries.\n * @param {number} [retryDelayFactor=1] - The factor by which the retry delay increases after each attempt.\n */\n constructor(\n name: string,\n task: TaskFunction,\n description: string = \"\",\n concurrency: number = 0,\n timeout: number = 0,\n register: boolean = true,\n isUnique: boolean = false,\n isMeta: boolean = false,\n isSubMeta: boolean = false,\n isHidden: boolean = false,\n getTagCallback: ThrottleTagGetter | undefined = undefined,\n inputSchema: SchemaDefinition | undefined = undefined,\n validateInputContext: boolean = false,\n outputSchema: SchemaDefinition | undefined = undefined,\n validateOutputContext: boolean = false,\n retryCount: number = 0,\n retryDelay: number = 0,\n retryDelayMax: number = 0,\n retryDelayFactor: number = 1,\n ) {\n super(isSubMeta || isHidden);\n this.name = name;\n this.taskFunction = task;\n this.description = description;\n this.concurrency = concurrency;\n this.timeout = timeout;\n this.isUnique = isUnique;\n this.isMeta = isMeta;\n this.isSubMeta = isSubMeta;\n this.isHidden = isHidden;\n this.inputContextSchema = inputSchema;\n this.validateInputContext = validateInputContext;\n this.outputContextSchema = outputSchema;\n this.validateOutputContext = validateOutputContext;\n this.retryCount = retryCount;\n this.retryDelay = retryDelay;\n this.retryDelayMax = retryDelayMax;\n this.retryDelayFactor = retryDelayFactor;\n this.register = register;\n\n if (getTagCallback) {\n this.getTag = (context?: AnyObject) => getTagCallback(context, this);\n this.throttled = true;\n }\n\n if (register && !this.isHidden) {\n const { __functionString, __getTagCallback } = this.export();\n this.emitWithMetadata(\"meta.task.created\", {\n data: {\n name: this.name,\n version: this.version,\n description: this.description,\n functionString: __functionString,\n tagIdGetter: __getTagCallback,\n layerIndex: this.layerIndex,\n concurrency: this.concurrency,\n retryCount: this.retryCount,\n retryDelay: this.retryDelay,\n retryDelayMax: this.retryDelayMax,\n retryDelayFactor: this.retryDelayFactor,\n timeout: this.timeout,\n isUnique: this.isUnique,\n isSignal: this.isSignal,\n isThrottled: this.throttled,\n isDebounce: this.isDebounce,\n isEphemeral: this.isEphemeral,\n isMeta: this.isMeta,\n isSubMeta: this.isSubMeta,\n validateInputContext: this.validateInputContext,\n validateOutputContext: this.validateOutputContext,\n // inputContextSchemaId: this.inputContextSchema,\n // outputContextSchemaId: this.outputContextSchema,\n },\n taskInstance: this,\n __isSubMeta: this.isSubMeta,\n });\n }\n }\n\n clone(traverse: boolean = false, includeSignals: boolean = false) {\n const clonedTask = new Task(\n `${this.name} (clone ${uuid().slice(0, 8)})`,\n this.taskFunction,\n this.description,\n this.concurrency,\n this.timeout,\n this.register,\n this.isUnique,\n this.isMeta,\n this.isSubMeta,\n this.isHidden,\n this.getTag,\n this.inputContextSchema,\n this.validateInputContext,\n this.outputContextSchema,\n this.validateOutputContext,\n this.retryCount,\n this.retryDelay,\n this.retryDelayMax,\n this.retryDelayFactor,\n );\n\n if (includeSignals) {\n clonedTask.doOn(...this.observedSignals);\n clonedTask.emits(...this.signalsToEmitAfter);\n clonedTask.emitsOnFail(...this.signalsToEmitOnFail);\n clonedTask.emitsSignals = new Set(Array.from(this.emitsSignals));\n }\n\n if (traverse) {\n this.mapNext((t: Task) => {\n clonedTask.then(t.clone(traverse, includeSignals));\n });\n }\n\n return clonedTask;\n }\n\n /**\n * Retrieves the tag associated with the instance.\n * Can be overridden by subclasses.\n *\n * @param {AnyObject} [context] - Optional context parameter that can be provided.\n * @return {string} The tag value of the instance.\n */\n public getTag(context?: AnyObject): string {\n return this.name;\n }\n\n public setVersion(version: number): void {\n this.version = version;\n this.emitWithMetadata(\"meta.task.version_set\", {\n __version: this.version,\n });\n }\n\n public setTimeout(timeout: number): void {\n this.timeout = timeout;\n }\n\n public setConcurrency(concurrency: number): void {\n this.concurrency = concurrency;\n }\n\n public setProgressWeight(weight: number): void {\n this.progressWeight = weight;\n }\n\n public setInputContextSchema(schema: SchemaDefinition): void {\n this.inputContextSchema = schema;\n }\n\n public setOutputContextSchema(schema: SchemaDefinition): void {\n this.outputContextSchema = schema;\n }\n\n public setValidateInputContext(value: boolean): void {\n this.validateInputContext = value;\n }\n\n public setValidateOutputContext(value: boolean): void {\n this.validateOutputContext = value;\n }\n\n /**\n * Emits a signal along with metadata if certain conditions are met.\n *\n * This method sends a signal with optional context data and adds metadata\n * to the emitted data if the instance is not hidden and not a subordinate metadata object.\n *\n * @param {string} signal - The name of the signal to emit.\n * @param {AnyObject} [ctx={}] - Additional context data to include with the emitted signal.\n * @return {void} Does not return a value.\n */\n emitWithMetadata(signal: string, ctx: AnyObject = {}) {\n const data = { ...ctx };\n if (!this.isHidden && !this.isSubMeta) {\n data.__signalEmission = {\n taskName: this.name,\n taskVersion: this.version,\n isMetric: false,\n };\n }\n\n this.emit(signal, data);\n }\n\n /**\n * Emits metrics with additional metadata enhancement based on the context and the state of the instance.\n * This is used to prevent loops on the meta layer in debug mode.\n *\n * @param {string} signal - The signal identifier for the metric being emitted.\n * @param {AnyObject} [ctx={}] - Optional context object to provide additional information with the metric.\n * @return {void} This method does not return any value.\n */\n emitMetricsWithMetadata(signal: string, ctx: AnyObject = {}) {\n const data = { ...ctx };\n if (!this.isHidden && !this.isSubMeta) {\n data.__signalEmission = {\n taskName: this.name,\n taskVersion: this.version,\n isMetric: true,\n };\n }\n\n this.emitMetrics(signal, data);\n }\n\n /**\n * Validates a data object against a specified schema definition and returns validation results.\n *\n * @param {any} data - The target object to validate against the schema.\n * @param {SchemaDefinition | undefined} schema - The schema definition describing the expected structure and constraints of the data.\n * @param {string} [path=\"context\"] - The base path or context for traversing the data, used in generating error messages.\n * @return {{ valid: boolean, errors: Record<string, string> }} - An object containing a validity flag (`valid`)\n * and a map (`errors`) of validation error messages keyed by property paths.\n */\n validateSchema(\n data: any,\n schema: SchemaDefinition | undefined,\n path: string = \"context\",\n ): { valid: boolean; errors: Record<string, string> } {\n const errors: Record<string, string> = {};\n\n if (!schema || typeof schema !== \"object\") return { valid: true, errors };\n\n // Check required fields\n const required = schema.required || [];\n for (const key of required) {\n if (!(key in data)) {\n errors[`${path}.${key}`] = `Required field '${key}' is missing`;\n }\n }\n\n // Validate defined properties (ignore extras)\n const properties = schema.properties || {};\n for (const [key, value] of Object.entries(data)) {\n if (key in properties) {\n const prop = properties[key];\n const propType = prop.type;\n\n if (propType === \"any\") {\n continue;\n }\n\n if ((value === undefined || value === null) && !prop.strict) {\n continue;\n }\n\n if (propType === \"string\" && typeof value !== \"string\") {\n errors[`${path}.${key}`] =\n `Expected 'string' for '${key}', got '${typeof value}'`;\n } else if (propType === \"number\" && typeof value !== \"number\") {\n errors[`${path}.${key}`] =\n `Expected 'number' for '${key}', got '${typeof value}'`;\n } else if (propType === \"boolean\" && typeof value !== \"boolean\") {\n errors[`${path}.${key}`] =\n `Expected 'boolean' for '${key}', got '${typeof value}'`;\n } else if (propType === \"array\" && !Array.isArray(value)) {\n errors[`${path}.${key}`] =\n `Expected 'array' for '${key}', got '${typeof value}'`;\n } else if (\n propType === \"object\" &&\n (typeof value !== \"object\" || value === null || Array.isArray(value))\n ) {\n errors[`${path}.${key}`] =\n `Expected 'object' for '${key}', got '${typeof value}'`;\n } else if (propType === \"array\" && prop.items) {\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n const subValidation = this.validateSchema(\n item,\n prop.items,\n `${path}.${key}[${index}]`,\n );\n if (!subValidation.valid) {\n Object.assign(errors, subValidation.errors);\n }\n });\n }\n } else if (\n propType === \"object\" &&\n !Array.isArray(value) &&\n value !== null\n ) {\n const subValidation = this.validateSchema(\n value,\n prop,\n `${path}.${key}`,\n );\n if (!subValidation.valid) {\n Object.assign(errors, subValidation.errors);\n }\n }\n\n // Check constraints (extended as discussed)\n const constraints = prop.constraints || {};\n if (typeof value === \"string\") {\n if (constraints.minLength && value.length < constraints.minLength) {\n errors[`${path}.${key}`] =\n `String '${key}' shorter than minLength ${constraints.minLength}`;\n }\n if (constraints.maxLength && value.length > constraints.maxLength) {\n errors[`${path}.${key}`] =\n `String '${key}' exceeds maxLength ${constraints.maxLength}`;\n }\n if (\n constraints.pattern &&\n !new RegExp(constraints.pattern).test(value)\n ) {\n errors[`${path}.${key}`] =\n `String '${key}' does not match pattern ${constraints.pattern}`;\n }\n } else if (typeof value === \"number\") {\n if (constraints.min && value < constraints.min) {\n errors[`${path}.${key}`] =\n `Number '${key}' below min ${constraints.min}`;\n }\n if (constraints.max && value > constraints.max) {\n errors[`${path}.${key}`] =\n `Number '${key}' exceeds max ${constraints.max}`;\n }\n if (constraints.multipleOf && value % constraints.multipleOf !== 0) {\n errors[`${path}.${key}`] =\n `Number '${key}' not multiple of ${constraints.multipleOf}`;\n }\n } else if (constraints.enum && !constraints.enum.includes(value)) {\n errors[`${path}.${key}`] =\n `Value '${value}' for '${key}' not in enum ${JSON.stringify(constraints.enum)}`;\n } else if (constraints.format) {\n const formats = {\n email: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/,\n url: /^(https?|ftp):\\/\\/[^\\s/$.?#].[^\\s]*$/,\n \"date-time\":\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})?$/,\n uuid: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,\n custom: /.*/, // Placeholder; override with prop.constraints.pattern if present\n } as any;\n const regex =\n formats[constraints.format] ||\n new RegExp(constraints.pattern || \".*\");\n if (typeof value === \"string\" && !regex.test(value)) {\n errors[`${path}.${key}`] =\n `Value '${value}' for '${key}' does not match format '${constraints.format}'`;\n }\n } else if (constraints.oneOf && !constraints.oneOf.includes(value)) {\n errors[`${path}.${key}`] =\n `Value '${value}' for '${key}' not in oneOf ${JSON.stringify(constraints.oneOf)}`;\n }\n } else if (schema.strict) {\n errors[`${path}.${key}`] = `Key '${key}' is not allowed`;\n }\n }\n\n if (Object.keys(errors).length > 0) {\n return { valid: false, errors };\n }\n return { valid: true, errors: {} };\n }\n\n /**\n * Validates the input context against the predefined schema and emits metadata if validation fails.\n *\n * @param {AnyObject} context - The input context to validate.\n * @return {true | AnyObject} - Returns `true` if validation succeeds, otherwise returns an error object containing details of the validation failure.\n */\n public validateInput(context: AnyObject): true | AnyObject {\n if (this.validateInputContext) {\n const validationResult = this.validateSchema(\n context,\n this.inputContextSchema,\n );\n if (!validationResult.valid) {\n this.emitWithMetadata(\"meta.task.input_validation_failed\", {\n __taskName: this.name,\n __taskVersion: this.version,\n __context: context,\n __errors: validationResult.errors,\n });\n return {\n errored: true,\n __error: \"Input context validation failed\",\n __validationErrors: JSON.stringify(validationResult.errors),\n };\n }\n }\n return true;\n }\n\n /**\n * Validates the output context using the provided schema and emits metadata if validation fails.\n *\n * @param {AnyObject} context - The output context to validate.\n * @return {true | AnyObject} Returns `true` if the output context is valid; otherwise, returns an object\n * containing error information when validation fails.\n */\n public validateOutput(context: AnyObject): true | AnyObject {\n if (this.validateOutputContext) {\n const validationResult = this.validateSchema(\n context,\n this.outputContextSchema,\n );\n if (!validationResult.valid) {\n this.emitWithMetadata(\"meta.task.output_validation_failed\", {\n __taskName: this.name,\n __taskVersion: this.version,\n __result: context,\n __errors: validationResult.errors,\n });\n return {\n errored: true,\n __error: \"Output context validation failed\",\n __validationErrors: JSON.stringify(validationResult.errors),\n };\n }\n }\n return true;\n }\n\n /**\n * Executes a task within a given context, optionally emitting signals and reporting progress.\n *\n * @param {GraphContext} context The execution context which provides data and functions necessary for the task.\n * @param {function(string, AnyObject): void} emit A function to emit signals and communicate intermediate results or states.\n * @param {function(number): void} progressCallback A callback function used to report task progress as a percentage (0 to 100).\n * @param {{ nodeId: string; routineExecId: string }} nodeData An object containing identifiers related to the node and execution routine.\n * @return {TaskResult} The result of the executed task.\n */\n public execute(\n context: GraphContext,\n emit: (signal: string, context: AnyObject) => void,\n progressCallback: (progress: number) => void,\n nodeData: { nodeId: string; routineExecId: string },\n ): TaskResult {\n return this.taskFunction(\n this.isMeta ? context.getClonedFullContext() : context.getClonedContext(),\n emit,\n progressCallback,\n );\n }\n\n /**\n * Adds tasks as predecessors to the current task and establishes dependencies between them.\n * Ensures that adding predecessors does not create cyclic dependencies.\n * Updates task relationships, progress weights, and emits relevant metrics after operations.\n *\n * @param {Task[]} tasks - An array of tasks to be added as predecessors to the current task.\n * @return {this} The current task instance for method chaining.\n * @throws {Error} Throws an error if adding a predecessor creates a cycle in the task structure.\n */\n public doAfter(...tasks: (Task | undefined)[]): this {\n for (const pred of tasks) {\n if (!pred) continue;\n if (this.predecessorTasks.has(pred)) continue;\n\n pred.nextTasks.add(this);\n this.predecessorTasks.add(pred);\n this.updateLayerFromPredecessors();\n\n if (this.hasCycle()) {\n this.decouple(pred);\n throw new Error(`Cycle adding pred ${pred.name} to ${this.name}`);\n }\n\n this.emitMetricsWithMetadata(\"meta.task.relationship_added\", {\n data: {\n taskName: this.name,\n taskVersion: this.version,\n predecessorTaskName: pred.name,\n predecessorTaskVersion: pred.version,\n },\n });\n }\n\n this.updateProgressWeights();\n return this;\n }\n\n /**\n * Adds a sequence of tasks as successors to the current task, ensuring no cyclic dependencies are introduced.\n * Metrics are emitted when a relationship is successfully added.\n *\n * @param {...Task} tasks - The tasks to be added as successors to the current task.\n * @return {this} Returns the current task instance for method chaining.\n * @throws {Error} Throws an error if adding a task causes a cyclic dependency.\n */\n public then(...tasks: (Task | undefined)[]): this {\n for (const next of tasks) {\n if (!next) continue;\n if (this.nextTasks.has(next)) continue;\n\n this.nextTasks.add(next);\n next.predecessorTasks.add(this);\n next.updateLayerFromPredecessors();\n\n if (next.hasCycle()) {\n this.decouple(next);\n throw new Error(`Cycle adding next ${next.name} to ${this.name}`);\n }\n\n this.emitMetricsWithMetadata(\"meta.task.relationship_added\", {\n data: {\n taskName: next.name,\n taskVersion: next.version,\n predecessorTaskName: this.name,\n predecessorTaskVersion: this.version,\n },\n });\n }\n\n this.updateProgressWeights();\n return this;\n }\n\n /**\n * Decouples the current task from the provided task by removing mutual references.\n *\n * @param {Task} task - The task to decouple from the current task.\n * @return {void} This method does not return a value.\n */\n public decouple(task: Task): void {\n if (task.nextTasks.has(this)) {\n task.nextTasks.delete(this);\n this.predecessorTasks.delete(task);\n }\n\n if (task.onFailTasks.has(this)) {\n task.onFailTasks.delete(this);\n this.predecessorTasks.delete(task);\n }\n\n // TODO: Delete task map instances\n\n this.updateLayerFromPredecessors();\n }\n\n /**\n * Updates the progress weights for tasks within each layer of the subgraph.\n * The progress weight for each task is calculated based on the inverse proportion\n * of the number of layers and the number of tasks in each layer. This ensures an\n * even distribution of progress weight across the tasks in the layers.\n *\n * @return {void} Does not return a value.\n */\n updateProgressWeights(): void {\n const layers = this.getSubgraphLayers();\n const numLayers = layers.size;\n if (numLayers === 0) return;\n\n const weightPerLayer = 1 / numLayers;\n\n layers.forEach((tasksInLayer) => {\n const numTasks = tasksInLayer.size;\n if (numTasks === 0) return;\n tasksInLayer.forEach(\n (task) => (task.progressWeight = weightPerLayer / numTasks),\n );\n });\n }\n\n /**\n * Retrieves a mapping of layer indices to sets of tasks within each layer of a subgraph.\n * This method traverses the task dependencies and organizes tasks by their respective layer indices.\n *\n * @return {Map<number, Set<Task>>} A map where the key is the layer index (number) and the value is a set of tasks (Set<Task>) belonging to that layer.\n */\n getSubgraphLayers(): Map<number, Set<Task>> {\n const layers = new Map<number, Set<Task>>();\n const queue = [this as Task];\n const visited = new Set<Task>();\n\n while (queue.length) {\n const task = queue.shift()!;\n if (visited.has(task)) continue;\n visited.add(task);\n\n if (!layers.has(task.layerIndex)) layers.set(task.layerIndex, new Set());\n layers.get(task.layerIndex)!.add(task);\n\n task.nextTasks.forEach((next) => queue.push(next));\n }\n\n return layers;\n }\n\n /**\n * Updates the `layerIndex` of the current task based on the maximum layer index of its predecessors\n * and propagates the update recursively to all subsequent tasks. If the `layerIndex` changes,\n * emits a metric event with metadata about the change.\n *\n * @return {void} This method does not return a value.\n */\n updateLayerFromPredecessors(): void {\n const prevLayerIndex = this.layerIndex;\n let maxPred = 0;\n this.predecessorTasks.forEach(\n (pred) => (maxPred = Math.max(maxPred, pred.layerIndex)),\n );\n this.layerIndex = maxPred + 1;\n\n if (prevLayerIndex !== this.layerIndex) {\n this.emitMetricsWithMetadata(\"meta.task.layer_index_changed\", {\n data: {\n layerIndex: this.layerIndex,\n },\n filter: { name: this.name, version: this.version },\n });\n }\n\n const queue = Array.from(this.nextTasks);\n while (queue.length) {\n const next = queue.shift()!;\n next.updateLayerFromPredecessors();\n next.nextTasks.forEach((n) => queue.push(n));\n }\n }\n\n /**\n * Determines whether there is a cycle in the tasks graph.\n * This method performs a depth-first search (DFS) to detect cycles.\n *\n * @return {boolean} - Returns true if a cycle is found in the graph, otherwise false.\n */\n hasCycle(): boolean {\n const visited = new Set<Task>();\n const recStack = new Set<Task>();\n\n const dfs = (task: Task): boolean => {\n if (recStack.has(task)) return true;\n if (visited.has(task)) return false;\n\n visited.add(task);\n recStack.add(task);\n\n for (const next of task.nextTasks) {\n if (dfs(next)) return true;\n }\n\n recStack.delete(task);\n return false;\n };\n\n return dfs(this);\n }\n\n /**\n * Maps over the next set of tasks or failed tasks if specified, applying the provided callback function.\n *\n * @param {Function} callback A function that will be called with each task, transforming the task as needed. It receives a single parameter of type Task.\n * @param {boolean} [failed=false] A boolean that determines whether to map over the failed tasks (true) or the next tasks (false).\n * @return {any[]} An array of transformed tasks resulting from applying the callback function.\n */\n public mapNext(\n callback: (task: Task) => any,\n failed: boolean = false,\n ): any[] {\n const tasks = failed\n ? Array.from(this.onFailTasks)\n : Array.from(this.nextTasks);\n return tasks.map(callback);\n }\n\n /**\n * Maps through each task in the set of predecessor tasks and applies the provided callback function.\n *\n * @param {function} callback - A function to execute on each task in the predecessor tasks. The function receives a `Task` object as its argument and returns any value.\n * @return {any[]} An array containing the results of applying the callback function to each predecessor task.\n */\n public mapPrevious(callback: (task: Task) => any): any[] {\n return Array.from(this.predecessorTasks).map(callback);\n }\n\n /**\n * Adds the specified signals to the current instance, making it observe them.\n * If the instance is already observing a signal, it will be skipped.\n * The method also emits metadata information if the `register` property is set.\n *\n * @param {...string[]} signals - The array of signal names to observe.\n * @return {this} The current instance after adding the specified signals.\n */\n doOn(...signals: string[]): this {\n signals.forEach((signal) => {\n if (this.observedSignals.has(signal)) return;\n if (this.emitsSignals.has(signal))\n throw new Error(\n `Detected signal loop for task ${this.name}. Signal name: ${signal}`,\n );\n Cadenza.broker.observe(signal, this as any);\n this.observedSignals.add(signal);\n if (this.register) {\n this.emitWithMetadata(\"meta.task.observed_signal\", {\n data: {\n signalName: signal.split(\":\")[0],\n taskName: this.name,\n taskVersion: this.version,\n },\n });\n }\n });\n return this;\n }\n\n /**\n * Registers the specified signals to be emitted after the Task executes successfully and attaches them for further processing.\n *\n * @param {...string} signals - The list of signals to be registered for emission.\n * @return {this} The current instance for method chaining.\n */\n emits(...signals: string[]): this {\n signals.forEach((signal) => {\n if (this.observedSignals.has(signal))\n throw new Error(\n `Detected signal loop for task ${this.name}. Signal name: ${signal}`,\n );\n this.signalsToEmitAfter.add(signal);\n this.attachSignal(signal);\n });\n return this;\n }\n\n /**\n * Configures the instance to emit specified signals when the task execution fails.\n * A failure is defined as anything that does not return a successful result.\n *\n * @param {...string} signals - The names of the signals to emit upon failure.\n * @return {this} Returns the current instance for chaining.\n */\n emitsOnFail(...signals: string[]): this {\n signals.forEach((signal) => {\n this.signalsToEmitOnFail.add(signal);\n this.attachSignal(signal, true);\n });\n return this;\n }\n\n /**\n * Attaches a signal to the current context and emits metadata if the register flag is set.\n *\n * @param {string} signal - The name of the signal to attach.\n * @param {boolean} [isOnFail=false] - Indicates if the signal should be marked as \"on fail\".\n * @return {void} This method does not return a value.\n */\n attachSignal(signal: string, isOnFail: boolean = false) {\n this.emitsSignals.add(signal);\n if (this.register) {\n this.emitWithMetadata(\"meta.task.attached_signal\", {\n data: {\n signalName: signal.split(\":\")[0],\n taskName: this.name,\n taskVersion: this.version,\n isOnFail,\n },\n });\n }\n }\n\n /**\n * Unsubscribes the current instance from the specified signals.\n * This method removes the signals from the observedSignals set, unsubscribes\n * from the underlying broker, and emits metadata for the unsubscription if applicable.\n *\n * @param {string[]} signals - The list of signal names to unsubscribe from.\n * @return {this} Returns the current instance for method chaining.\n */\n unsubscribe(...signals: string[]): this {\n signals.forEach((signal) => {\n if (this.observedSignals.has(signal)) {\n Cadenza.broker.unsubscribe(signal, this as any);\n this.observedSignals.delete(signal);\n\n if (this.register) {\n signal = signal.split(\":\")[0];\n this.emitWithMetadata(\"meta.task.unsubscribed_signal\", {\n filter: {\n signalName: signal,\n taskName: this.name,\n taskVersion: this.version,\n },\n });\n }\n }\n });\n return this;\n }\n\n /**\n * Unsubscribes from all currently observed signals and clears the list of observed signals.\n *\n * @return {this} The instance of the class to allow method chaining.\n */\n unsubscribeAll(): this {\n this.unsubscribe(...this.observedSignals);\n this.observedSignals.clear();\n return this;\n }\n\n /**\n * Detaches the specified signals from being emitted after execution and optionally emits metadata for each detached signal.\n *\n * @param {...string} signals - The list of signal names to be detached. Signals can be in the format \"namespace:signalName\".\n * @return {this} Returns the current instance of the object for method chaining.\n */\n detachSignals(...signals: string[]): this {\n signals.forEach((signal) => {\n this.signalsToEmitAfter.delete(signal);\n if (this.register) {\n signal = signal.split(\":\")[0];\n this.emitWithMetadata(\"meta.task.detached_signal\", {\n filter: {\n signalName: signal,\n taskName: this.name,\n taskVersion: this.version,\n },\n });\n }\n });\n return this;\n }\n\n /**\n * Detaches all signals associated with the object by invoking the `detachSignals` method\n * and clearing the `signalsToEmitAfter` collection.\n *\n * @return {this} Returns the current instance to allow method chaining.\n */\n detachAllSignals(): this {\n this.detachSignals(...this.signalsToEmitAfter);\n this.signalsToEmitAfter.clear();\n return this;\n }\n\n /**\n * Maps over the signals in the `signalsToEmitAfter` set and applies a callback function to each signal.\n *\n * @param {function(string): void} callback - A function that is called with each signal\n * in the `signalsToEmitAfter` set, providing the signal as an argument.\n * @return {Array<any>} An array containing the results of applying the callback\n * function to each signal.\n */\n mapSignals(callback: (signal: string) => void) {\n return Array.from(this.signalsToEmitAfter).map(callback);\n }\n\n /**\n * Maps over the signals in `signalsToEmitOnFail` and applies the provided callback to each signal.\n *\n * @param {function(string): void} callback - A function that receives each signal as a string and performs an operation or transformation on it.\n * @return {Array} The array resulting from applying the callback to each signal in `signalsToEmitOnFail`.\n */\n mapOnFailSignals(callback: (signal: string) => void) {\n return Array.from(this.signalsToEmitOnFail).map(callback);\n }\n\n /**\n * Maps over the observed signals with the provided callback function.\n *\n * @param {function(string): void} callback - A function to execute on each signal in the observed signals array.\n * @return {Array} A new array containing the results of calling the callback function on each observed signal.\n */\n mapObservedSignals(callback: (signal: string) => void) {\n return Array.from(this.observedSignals).map(callback);\n }\n\n /**\n * Emits a collection of signals stored in the `signalsToEmitAfter` array.\n *\n * @param {GraphContext} context - The context object containing data or state to be passed to the emitted signals.\n * @return {void} This method does not return a value.\n */\n emitSignals(context: GraphContext): void {\n this.signalsToEmitAfter.forEach((signal) => {\n this.emit(signal, context.getFullContext());\n });\n }\n\n /**\n * Emits registered signals when an operation fails.\n *\n * @param {GraphContext} context - The context from which the full context is derived and passed to the signals being emitted.\n * @return {void} This method does not return any value.\n */\n emitOnFailSignals(context: GraphContext): void {\n this.signalsToEmitOnFail.forEach((signal) => {\n this.emit(signal, context.getFullContext());\n });\n }\n\n /**\n * Cleans up and destroys the task instance, detaching it from other tasks and\n * performing necessary cleanup operations.\n *\n * This method:\n * - Unsubscribes from all signals and events.\n * - Detaches all associated signal handlers.\n * - Removes the task from successor and predecessor task mappings.\n * - Clears all task relationships and marks the task as destroyed.\n * - Emits destruction metrics, if applicable.\n *\n * @return {void} No value is returned because the function performs clean-up operations.\n */\n public destroy(): void {\n this.unsubscribeAll();\n this.detachAllSignals();\n\n this.predecessorTasks.forEach((pred) => pred.nextTasks.delete(this));\n this.nextTasks.forEach((next) => next.predecessorTasks.delete(this));\n this.onFailTasks.forEach((fail) => fail.predecessorTasks.delete(this));\n\n this.nextTasks.clear();\n this.predecessorTasks.clear();\n this.onFailTasks.clear();\n\n this.destroyed = true;\n\n if (this.register) {\n this.emitMetricsWithMetadata(\"meta.task.destroyed\", {\n data: { deleted: true },\n filter: { name: this.name, version: this.version },\n });\n }\n\n // TODO: Delete task map instances\n }\n\n /**\n * Exports the current state of the object as a structured plain object.\n *\n * @return {AnyObject} An object containing the serialized properties of the current instance. The exported object includes various metadata, schema information, task attributes, and related tasks, such as:\n * - Name and description of the task.\n * - Layer index, uniqueness, meta, and signal-related flags.\n * - Event triggers and attached signals.\n * - Throttling, concurrency, timeout settings, and ephemeral flag.\n * - Task function as a string.\n * - Serialization of getter callbacks and schemas for input/output validation.\n * - Relationships such as next tasks, failure tasks, and predecessor tasks.\n */\n public export(): AnyObject {\n return {\n __name: this.name,\n __description: this.description,\n __layerIndex: this.layerIndex,\n __isUnique: this.isUnique,\n __isMeta: this.isMeta,\n __isSignal: this.isSignal,\n __eventTriggers: this.observedSignals,\n __attachedEvents: this.signalsToEmitAfter,\n __isDeputy: this.isDeputy,\n __throttled: this.throttled,\n __isEphemeral: this.isEphemeral,\n __concurrency: this.concurrency,\n __timeout: this.timeout,\n __functionString: this.taskFunction.toString(),\n __getTagCallback: this.getTag.toString(),\n __inputSchema: this.inputContextSchema,\n __validateInputContext: this.validateInputContext,\n __outputSchema: this.outputContextSchema,\n __validateOutputContext: this.validateOutputContext,\n __nextTasks: Array.from(this.nextTasks).map((t) => t.name),\n __onFailTasks: Array.from(this.onFailTasks).map((t) => t.name),\n __previousTasks: Array.from(this.predecessorTasks).map((t) => t.name),\n };\n }\n\n /**\n * Returns an iterator for iterating over tasks associated with this instance.\n *\n * @return {TaskIterator} An iterator instance for tasks.\n */\n public getIterator(): TaskIterator {\n return new TaskIterator(this);\n }\n\n /**\n * Accepts a visitor object to perform operations on the current instance.\n *\n * @param {GraphVisitor} visitor - The visitor object implementing operations for this instance.\n * @return {void} This method does not return a value.\n */\n public accept(visitor: GraphVisitor): void {\n visitor.visitTask(this);\n }\n\n public log(): void {\n console.log(this.name);\n }\n}\n","import Iterator from \"../../interfaces/Iterator\";\nimport Task from \"../definition/Task\";\n\n/**\n * TaskIterator is a custom iterator for traversing over a set of tasks.\n * It provides mechanisms to iterate through tasks in a layered manner,\n * where each task can branch out to other tasks forming multiple layers.\n */\nexport default class TaskIterator implements Iterator {\n currentTask: Task | undefined;\n currentLayer: Set<Task> = new Set();\n nextLayer: Set<Task> = new Set();\n iterator: { next: () => { value: Task | undefined } } =\n this.currentLayer[Symbol.iterator]();\n\n constructor(task: Task) {\n this.currentTask = task;\n this.currentLayer.add(task);\n }\n hasNext(): boolean {\n return !!this.currentTask;\n }\n\n next(): Task | undefined {\n const nextTask = this.currentTask;\n\n if (!nextTask) {\n return undefined;\n }\n\n nextTask.mapNext((t: Task) => this.nextLayer.add(t));\n\n let next = this.iterator.next();\n\n if (next.value === undefined) {\n this.currentLayer.clear();\n this.currentLayer = this.nextLayer;\n this.nextLayer = new Set();\n this.iterator = this.currentLayer[Symbol.iterator]();\n next = this.iterator.next();\n }\n\n this.currentTask = next.value;\n\n return nextTask;\n }\n}\n","import Cadenza from \"../Cadenza\";\nimport Task from \"../graph/definition/Task\";\nimport GraphRoutine from \"../graph/definition/GraphRoutine\";\nimport { AnyObject } from \"../types/global\";\n\n/**\n * This class serves as a registry for managing tasks and routines within a graph-based execution model.\n * It provides functionalities to register, update, retrieve, delete, and iterate over tasks and routines.\n */\nexport default class GraphRegistry {\n static _instance: GraphRegistry;\n public static get instance(): GraphRegistry {\n if (!this._instance) this._instance = new GraphRegistry();\n return this._instance;\n }\n\n tasks: Map<string, Task> = new Map();\n routines: Map<string, GraphRoutine> = new Map();\n\n registerTask: Task;\n updateTaskInputSchema: Task;\n updateTaskOutputSchema: Task;\n getTaskByName: Task;\n getTasksByLayer: Task;\n getAllTasks: Task;\n doForEachTask: Task;\n deleteTask: Task;\n registerRoutine: Task;\n getRoutineByName: Task;\n getAllRoutines: Task;\n doForEachRoutine: Task;\n deleteRoutine: Task;\n\n /**\n * Constructs a new instance and sets up various meta tasks and routines.\n *\n * This constructor initializes several predefined tasks for managing operations\n * like registering tasks, updating schemas for tasks, fetching tasks or routines,\n * and performing actions on all tasks or routines. It also initializes routines\n * to handle similar operations and hardcodes the initial meta tasks and routines.\n *\n * It initializes the instance state by setting up tasks and routines.\n */\n constructor() {\n // Hardcode seed MetaTask (observes on existing broker)\n this.registerTask = new Task(\n \"Register task\",\n (context: AnyObject) => {\n const { taskInstance } = context;\n if (taskInstance && !this.tasks.has(taskInstance.name)) {\n this.tasks.set(taskInstance.name, taskInstance);\n }\n delete context.taskInstance;\n return true;\n },\n \"Registers tasks. Seed for meta.taskCreated\",\n 0,\n 0,\n true,\n false,\n true,\n ).doOn(\"meta.task.created\");\n\n // Manual seed register\n this.tasks.set(this.registerTask.name, this.registerTask);\n\n this.updateTaskInputSchema = Cadenza.createMetaTask(\n \"Update task input schema\",\n (context) => {\n const { __id, __schema } = context;\n const task = this.tasks.get(__id);\n if (!task) return true;\n task.setInputContextSchema(__schema);\n return true;\n },\n \"Updates task input schema.\",\n ).doOn(\"meta.task.input_schema_updated\");\n\n this.updateTaskOutputSchema = Cadenza.createMetaTask(\n \"Update task input schema\",\n (context) => {\n const { __id, __schema } = context;\n const task = this.tasks.get(__id);\n if (!task) return true;\n task.setOutputContextSchema(__schema);\n return true;\n },\n \"Updates task input schema.\",\n ).doOn(\"meta.task.output_schema_updated\");\n\n this.getTaskByName = Cadenza.createMetaTask(\n \"Get task by name\",\n (context) => {\n const { __name } = context;\n for (const task of this.tasks.values()) {\n if (task.name === __name) {\n return { ...context, task };\n }\n }\n return false;\n },\n \"Gets task by name (first match).\",\n );\n\n this.getTasksByLayer = Cadenza.createMetaTask(\n \"Get tasks by layer\",\n (context) => {\n const { __layerIndex } = context;\n const layerTasks = Array.from(this.tasks.values()).filter(\n (task) => task.layerIndex === __layerIndex,\n );\n return { ...context, tasks: layerTasks };\n },\n \"Gets tasks by layer index.\",\n );\n\n this.getAllTasks = Cadenza.createMetaTask(\n \"Get all tasks\",\n (context) => ({ ...context, tasks: Array.from(this.tasks.values()) }), // Use arrow to capture this\n \"Gets all tasks.\",\n );\n\n this.doForEachTask = Cadenza.createMetaTask(\n \"Do for each task\",\n function* (context: AnyObject) {\n // @ts-ignore\n for (const task of this.tasks.values()) {\n yield { ...context, task };\n }\n }.bind(this), // Bind to capture this in generator\n \"Yields each task for branching.\",\n );\n\n this.deleteTask = Cadenza.createMetaTask(\n \"Delete task\",\n (context) => {\n const { filter } = context;\n this.tasks.delete(filter.name);\n return context;\n },\n \"Deletes task.\",\n ).doOn(\"meta.task.destroyed\");\n\n this.registerRoutine = Cadenza.createMetaTask(\n \"Register routine\",\n (context) => {\n const { routineInstance } = context;\n if (routineInstance && !this.routines.has(routineInstance.name)) {\n this.routines.set(routineInstance.name, routineInstance);\n }\n delete context.routineInstance;\n return true;\n },\n \"Registers routine.\",\n ).doOn(\"meta.routine.created\");\n\n this.getRoutineByName = Cadenza.createMetaTask(\n \"Get routine by name\",\n (context) => {\n const { __name } = context;\n for (const routine of this.routines.values()) {\n if (routine.name === __name) {\n return { ...context, routine };\n }\n }\n return false;\n },\n \"Gets routine by name.\",\n );\n\n this.getAllRoutines = Cadenza.createMetaTask(\n \"Get all routines\",\n (context) => ({\n ...context,\n routines: Array.from(this.routines.values()),\n }), // Use arrow to capture this\n \"Gets all routines.\",\n );\n\n this.doForEachRoutine = Cadenza.createMetaTask(\n \"Do for each routine\",\n function* (context: AnyObject) {\n // @ts-ignore\n for (const routine of this.routines.values()) {\n yield { ...context, routine: routine };\n }\n }.bind(this),\n \"Yields each routine.\",\n );\n\n this.deleteRoutine = Cadenza.createMetaTask(\n \"Delete routine\",\n (context) => {\n const { __name } = context;\n this.routines.delete(__name);\n return context;\n },\n \"Deletes routine.\",\n );\n }\n\n reset() {\n this.tasks.clear();\n this.routines.clear();\n }\n}\n","import Task, { TaskFunction, TaskResult } from \"./Task\";\nimport GraphContext from \"../context/GraphContext\";\nimport { SchemaDefinition } from \"../../types/schema\";\n\nexport interface DebounceOptions {\n leading?: boolean;\n trailing?: boolean;\n maxWait?: number;\n}\n\n/**\n * Class representing a debounced task, inheriting from the `Task` class.\n * This class allows tasks to be executed with debounce behavior, controlling\n * the frequency at which the task function is triggered.\n */\nexport default class DebounceTask extends Task {\n readonly debounceTime: number;\n leading: boolean;\n trailing: boolean;\n maxWait: number;\n timer: NodeJS.Timeout | null = null;\n maxTimer: NodeJS.Timeout | null = null;\n hasLaterCall: boolean = false;\n lastResolve: ((value: unknown) => void) | null = null;\n lastReject: ((reason?: any) => void) | null = null;\n lastContext: GraphContext | null = null;\n lastTimeout: NodeJS.Timeout | null = null;\n lastProgressCallback: ((progress: number) => void) | null = null;\n lastEmitFunction: ((signal: string, context: any) => void) | null = null;\n\n constructor(\n name: string,\n task: TaskFunction,\n description: string = \"\",\n debounceTime: number = 1000,\n leading: boolean = false,\n trailing: boolean = true,\n maxWait: number = 0,\n concurrency: number = 0,\n timeout: number = 0,\n register: boolean = true,\n isUnique: boolean = false,\n isMeta: boolean = false,\n isSubMeta: boolean = false,\n isHidden: boolean = false,\n inputSchema: SchemaDefinition | undefined = undefined,\n validateInputSchema: boolean = false,\n outputSchema: SchemaDefinition | undefined = undefined,\n validateOutputSchema: boolean = false,\n ) {\n super(\n name,\n task,\n description,\n concurrency,\n timeout,\n register,\n isUnique,\n isMeta,\n isSubMeta,\n isHidden,\n undefined,\n inputSchema,\n validateInputSchema,\n outputSchema,\n validateOutputSchema,\n );\n this.debounceTime = debounceTime;\n this.leading = leading;\n this.trailing = trailing;\n this.maxWait = maxWait;\n }\n\n /**\n * Executes the taskFunction with the provided context, emit function, and progress callback.\n * It clears any existing timeout before execution.\n * Handles synchronous and asynchronous results from taskFunction.\n * If an error occurs during execution, it resolves with the error.\n *\n * @return {void} This method does not return any value.\n */\n executeFunction(): void {\n if (this.lastTimeout) {\n clearTimeout(this.lastTimeout);\n }\n\n let result;\n try {\n result = this.taskFunction(\n this.lastContext!.getClonedContext(),\n this.lastEmitFunction!,\n this.lastProgressCallback!,\n );\n } catch (error) {\n if (this.lastResolve) {\n this.lastResolve(error);\n }\n return;\n }\n\n if (result instanceof Promise) {\n result.then(this.lastResolve!).catch(this.lastReject!);\n } else {\n if (this.lastResolve) {\n this.lastResolve(result);\n }\n }\n }\n\n /**\n * Executes a debounced operation, ensuring controlled execution of functions\n * over a specified debounce time and maximum wait time. This method handles\n * both leading and trailing edge executions and invokes callbacks accordingly.\n *\n * @param {Function} resolve - The function to call when the operation is successfully resolved.\n * @param {Function} reject - The function to call with an error or reason if the operation fails.\n * @param {GraphContext} context - The execution context for the operation.\n * @param {NodeJS.Timeout} timeout - A timeout object for managing execution delays.\n * @param {Function} emit - A callback function to emit signals with a specific context.\n * @param {Function} progressCallback - A callback function to report progress during operation execution.\n * @return {void} Does not return a value but sets internal timers and invokes provided callbacks.\n */\n debouncedTrigger(\n resolve: (value: unknown) => void,\n reject: (reason?: any) => void,\n context: GraphContext,\n timeout: NodeJS.Timeout,\n emit: (signal: string, context: any) => void,\n progressCallback: (progress: number) => void,\n ): void {\n const callNow = this.leading && this.timer === null;\n const isNewBurst = this.timer === null;\n\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n this.lastResolve = resolve;\n this.lastReject = reject;\n this.lastContext = context;\n this.lastTimeout = timeout;\n this.lastProgressCallback = progressCallback;\n this.lastEmitFunction = emit;\n\n if (!callNow) {\n this.hasLaterCall = true;\n }\n\n this.timer = setTimeout(() => {\n this.timer = null;\n if (this.trailing && this.hasLaterCall) {\n this.executeFunction();\n this.hasLaterCall = false;\n }\n if (this.maxTimer) {\n clearTimeout(this.maxTimer);\n this.maxTimer = null;\n }\n }, this.debounceTime);\n\n if (callNow) {\n this.executeFunction();\n this.hasLaterCall = false;\n }\n\n if (this.maxWait > 0 && isNewBurst) {\n this.maxTimer = setTimeout(() => {\n this.maxTimer = null;\n if (this.trailing && this.hasLaterCall) {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n this.executeFunction();\n this.hasLaterCall = false;\n }\n }, this.maxWait);\n }\n }\n\n /**\n * Executes a task with a debounced trigger mechanism.\n *\n * @param {GraphContext} context - The context containing relevant graph data for the execution.\n * @param {function(string, any): void} emit - A function used to emit signals with associated context.\n * @param {function(number): void} progressCallback - A callback function to report the progress of the task as a number between 0 and 1.\n * @return {Promise<TaskResult>} A promise that resolves with the task result upon completion or rejects on failure.\n */\n execute(\n context: GraphContext,\n emit: (signal: string, context: any) => void,\n progressCallback: (progress: number) => void,\n ): TaskResult {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n resolve(false);\n }, this.debounceTime + 1);\n\n this.debouncedTrigger(\n resolve,\n reject,\n context,\n timeout,\n emit,\n progressCallback,\n );\n });\n }\n}\n","import Task, { TaskFunction, ThrottleTagGetter } from \"./Task\";\nimport { SchemaDefinition } from \"../../types/schema\";\nimport { AnyObject } from \"../../types/global\";\n\nexport type EphemeralTaskOptions = {\n once?: boolean;\n destroyCondition?: (context: any) => boolean;\n};\n\n/**\n * Represents a transient task that executes and may optionally self-destruct\n * based on given conditions.\n *\n * EphemeralTask extends the standard Task class and introduces additional\n * features for managing tasks that are intended to run only once, or under\n * certain conditions. This class is particularly useful when you want a task\n * to clean up after itself and not persist within the system indefinitely.\n */\nexport default class EphemeralTask extends Task {\n readonly once: boolean;\n readonly condition: (context: any) => boolean;\n readonly isEphemeral: boolean = true;\n\n constructor(\n name: string,\n task: TaskFunction,\n description: string = \"\",\n once: boolean = true,\n condition: (context: any) => boolean = () => true,\n concurrency: number = 0,\n timeout: number = 0,\n register: boolean = false,\n isUnique: boolean = false,\n isMeta: boolean = false,\n isSubMeta: boolean = false,\n isHidden: boolean = false,\n getTagCallback: ThrottleTagGetter | undefined = undefined,\n inputSchema: SchemaDefinition | undefined = undefined,\n validateInputContext: boolean = false,\n outputSchema: SchemaDefinition | undefined = undefined,\n validateOutputContext: boolean = false,\n retryCount: number = 0,\n retryDelay: number = 0,\n retryDelayMax: number = 0,\n retryDelayFactor: number = 1,\n ) {\n super(\n name,\n task,\n description,\n concurrency,\n timeout,\n register,\n isUnique,\n isMeta,\n isSubMeta,\n isHidden,\n getTagCallback,\n inputSchema,\n validateInputContext,\n outputSchema,\n validateOutputContext,\n retryCount,\n retryDelay,\n retryDelayMax,\n retryDelayFactor,\n );\n this.once = once;\n this.condition = condition;\n }\n\n /**\n * Executes the process logic with the provided context, emit function, progress callback, and node data.\n *\n * @param {any} context - The execution context, carrying necessary parameters or states for the operation.\n * @param {function(string, AnyObject): void} emit - A function to emit signals with a string identifier and associated context.\n * @param {function(number): void} progressCallback - A callback function to report the progress of the execution as a numerical value.\n * @param {{ nodeId: string, routineExecId: string }} nodeData - An object containing details about the node ID and routine execution ID.\n * @return {any} The result of the execution, returned from the base implementation or processed internally.\n */\n public execute(\n context: any,\n emit: (signal: string, context: AnyObject) => void,\n progressCallback: (progress: number) => void,\n nodeData: { nodeId: string; routineExecId: string },\n ) {\n const result = super.execute(context, emit, progressCallback, nodeData);\n\n if (this.once || this.condition(result)) {\n this.destroy();\n }\n\n return result;\n }\n}\n","/**\n * Represents an abstract chain of execution, where each instance can be\n * connected to a succeeding or preceding instance to form a chain of steps.\n * Provides methods to manage the links between instances in the chain.\n */\nexport default abstract class ExecutionChain {\n next: ExecutionChain | undefined;\n previous: ExecutionChain | undefined;\n\n public setNext(next: ExecutionChain): void {\n if (this.hasNext) {\n return;\n }\n\n next.previous = this;\n this.next = next;\n }\n\n get hasNext() {\n return !!this.next;\n }\n\n get hasPreceding() {\n return !!this.previous;\n }\n\n getNext() {\n return this.next;\n }\n\n getPreceding() {\n return this.previous;\n }\n\n decouple() {\n this.next = undefined;\n this.previous = undefined;\n }\n}\n","import Iterator from \"../../interfaces/Iterator\";\nimport SyncGraphLayer from \"../execution/SyncGraphLayer\";\nimport GraphLayer from \"../../interfaces/GraphLayer\";\n\n/**\n * The `GraphLayerIterator` class provides an iterator for traversing through\n * layers of a `GraphLayer` data structure. It allows sequential and bi-directional\n * iteration, as well as access to the first and last layers in the graph.\n *\n * @implements {Iterator}\n */\nexport default class GraphLayerIterator implements Iterator {\n graph: GraphLayer;\n currentLayer: GraphLayer | undefined;\n\n constructor(graph: GraphLayer) {\n this.graph = graph;\n }\n hasNext() {\n return !this.currentLayer || this.currentLayer.hasNext;\n }\n\n hasPrevious(): boolean {\n return !this.currentLayer || this.currentLayer.hasPreceding;\n }\n\n next(): GraphLayer {\n if (!this.currentLayer) {\n return this.getFirst();\n } else if (this.hasNext()) {\n this.currentLayer = this.currentLayer.getNext() as GraphLayer;\n }\n\n // @ts-ignore\n return this.currentLayer;\n }\n\n previous(): GraphLayer {\n if (!this.currentLayer) {\n this.currentLayer = this.graph;\n } else if (this.hasPrevious()) {\n this.currentLayer = this.currentLayer.getPreceding() as SyncGraphLayer;\n }\n\n // @ts-ignore\n return this.currentLayer;\n }\n\n getFirst(): GraphLayer {\n if (!this.currentLayer) {\n this.currentLayer = this.graph;\n }\n\n while (this.hasPrevious()) {\n this.currentLayer = this.currentLayer?.getPreceding() as SyncGraphLayer;\n }\n\n return this.currentLayer;\n }\n\n getLast(): GraphLayer {\n if (!this.currentLayer) {\n this.currentLayer = this.graph;\n }\n\n while (this.hasNext()) {\n this.currentLayer = this.currentLayer?.getNext() as GraphLayer;\n }\n\n return this.currentLayer as GraphLayer;\n }\n}\n","import ExecutionChain from \"./ExecutionChain\";\nimport Graph from \"./Graph\";\nimport GraphNode from \"../graph/execution/GraphNode\";\nimport GraphLayerIterator from \"../graph/iterators/GraphLayerIterator\";\nimport GraphVisitor from \"./GraphVisitor\";\nimport GraphContext from \"../graph/context/GraphContext\";\n\n/**\n * Represents an abstract layer in a graph, handling nodes and their execution.\n * A `GraphLayer` can manage execution states, debug states, and relationships with other layers in the graph.\n * This class is designed to be extended and requires the implementation of the `execute` method.\n *\n * @abstract\n * @class GraphLayer\n * @extends ExecutionChain\n * @implements Graph\n */\nexport default abstract class GraphLayer\n extends ExecutionChain\n implements Graph\n{\n readonly index: number;\n nodes: GraphNode[] = [];\n executionTime: number = 0;\n executionStart: number = 0;\n debug: boolean = false;\n\n constructor(index: number) {\n super();\n this.index = index;\n }\n\n /**\n * Sets the debug mode for the current instance and all associated nodes.\n *\n * @param {boolean} value - A boolean value to enable (true) or disable (false) debug mode.\n * @return {void} No return value.\n */\n setDebug(value: boolean) {\n this.debug = value;\n for (const node of this.nodes) {\n node.setDebug(value);\n }\n }\n\n /**\n * Abstract method to execute a specific operation given a context.\n *\n * @param {GraphContext} [context] - Optional parameter representing the execution context, which contains relevant data for performing the operation.\n * @return {unknown} - Returns the result of the operation, its type may vary depending on the implementation.\n */\n abstract execute(context?: GraphContext): unknown;\n\n /**\n * Checks if the current layer has a preceding layer.\n *\n * @return {boolean} True if the current layer has a preceding layer that is an instance of GraphLayer; otherwise, false.\n */\n get hasPreceding() {\n return !!this.previous && this.previous instanceof GraphLayer;\n }\n\n getNumberOfNodes() {\n return this.nodes.length;\n }\n\n /**\n * Retrieves a list of nodes that match the given routine execution ID.\n *\n * @param {string} routineExecId - The ID of the routine execution to filter nodes by.\n * @return {Array} An array of nodes that have the specified routine execution ID.\n */\n getNodesByRoutineExecId(routineExecId: string) {\n return this.nodes.filter((node) => node.routineExecId === routineExecId);\n }\n\n /**\n * Finds and returns all nodes in the graph that are identical to the given node.\n * Two nodes are considered identical if they share the same routine execution ID\n * and share a task with each other.\n *\n * @param {GraphNode} node - The reference node to compare against other nodes in the graph.\n * @return {GraphNode[]} An array of nodes that are identical to the given node.\n */\n getIdenticalNodes(node: GraphNode) {\n return this.nodes.filter(\n (n) => node.routineExecId === n.routineExecId && node.sharesTaskWith(n),\n );\n }\n\n /**\n * Checks whether all nodes in the collection have been processed.\n *\n * @return {boolean} Returns true if all nodes are processed, otherwise false.\n */\n isProcessed() {\n for (const node of this.nodes) {\n if (!node.isProcessed()) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Checks whether all layers in the graph have been processed.\n *\n * @return {boolean} Returns true if all graph layers are processed; otherwise, returns false.\n */\n graphDone() {\n let done = true;\n\n let layer: GraphLayer | undefined = this;\n while (layer) {\n if (!layer.isProcessed()) {\n done = false;\n break;\n }\n layer = layer.getNext() as GraphLayer;\n }\n\n return done;\n }\n\n /**\n * Sets the next GraphLayer in the sequence if it has a higher index than the current layer.\n * Updates the previous property if the given next layer has an existing previous layer.\n *\n * @param {GraphLayer} next - The next GraphLayer to be linked in the sequence.\n * @return {void} Does not return a value. Modifies the current layer's state.\n */\n setNext(next: GraphLayer) {\n if (next.index <= this.index) {\n return;\n }\n\n if (next.previous !== undefined) {\n this.previous = next.previous;\n }\n\n super.setNext(next);\n }\n\n /**\n * Adds a node to the graph.\n *\n * @param {GraphNode} node - The node to be added to the graph.\n * @return {void}\n */\n add(node: GraphNode) {\n this.nodes.push(node);\n }\n\n /**\n * Starts the execution timer if it has not been started already.\n * Records the current timestamp as the start time.\n *\n * @return {number} The timestamp representing the start time in milliseconds.\n */\n start() {\n if (!this.executionStart) {\n this.executionStart = Date.now();\n }\n return this.executionStart;\n }\n\n /**\n * Marks the end of a process by capturing the current timestamp and calculating the execution time if a start time exists.\n *\n * @return {number} The timestamp at which the process ended, or 0 if the start time is not defined.\n */\n end() {\n if (!this.executionStart) {\n return 0;\n }\n\n const end = Date.now();\n this.executionTime = end - this.executionStart;\n return end;\n }\n\n /**\n * Destroys the current graph layer and its associated resources.\n * This method recursively destroys all nodes in the current layer, clears the node list,\n * and ensures that any connected subsequent graph layers are also destroyed.\n * Additionally, it calls the decoupling logic to disconnect the current layer from its dependencies.\n *\n * @return {void} Does not return any value.\n */\n destroy() {\n for (const node of this.nodes) {\n node.destroy();\n }\n\n this.nodes = [];\n\n if (this.hasNext) {\n const layer = this.getNext() as GraphLayer;\n layer?.destroy();\n }\n\n this.decouple();\n }\n\n /**\n * Returns an iterator for traversing through the graph layers.\n *\n * @return {GraphLayerIterator} An instance of GraphLayerIterator to traverse graph layers.\n */\n getIterator(): GraphLayerIterator {\n return new GraphLayerIterator(this);\n }\n\n /**\n * Accepts a visitor object to traverse or perform operations on the current graph layer and its nodes.\n *\n * @param {GraphVisitor} visitor - The visitor instance implementing the visitLayer and visitNode behavior.\n * @return {void} Returns nothing.\n */\n accept(visitor: GraphVisitor) {\n visitor.visitLayer(this);\n\n for (const node of this.nodes) {\n node.accept(visitor);\n }\n }\n\n export() {\n return {\n __index: this.index,\n __executionTime: this.executionTime,\n __numberOfNodes: this.getNumberOfNodes(),\n __hasNextLayer: this.hasNext,\n __hasPrecedingLayer: this.hasPreceding,\n __nodes: this.nodes.map((node) => node.id),\n };\n }\n\n log() {\n console.log(`---Layer ${this.index}---`);\n console.log(\"Execution time:\", this.executionTime);\n let prevNode;\n for (const node of this.nodes) {\n if (!prevNode || !prevNode.sharesContextWith(node)) {\n console.log(\"**********\");\n }\n node.log();\n prevNode = node;\n }\n console.log(\"***********\");\n if (this.hasNext) {\n (this.getNext() as GraphLayer).log();\n }\n }\n}\n","import GraphNode from \"./GraphNode\";\nimport GraphLayer from \"../../interfaces/GraphLayer\";\n\n/**\n * Represents a synchronous graph layer derived from the GraphLayer base class.\n * This class is designed to execute graph nodes in a strictly synchronous manner.\n * Asynchronous functions are explicitly disallowed, ensuring consistency and predictability.\n */\nexport default class SyncGraphLayer extends GraphLayer {\n /**\n * Executes the processing logic of the current set of graph nodes. Iterates through all\n * nodes, skipping any that have already been processed, and executes their respective\n * logic to generate new nodes. Asynchronous functions are not supported and will\n * trigger an error log.\n *\n * @return {GraphNode[]} An array of newly generated graph nodes after executing the logic of each unprocessed node.\n */\n execute(): GraphNode[] {\n this.start();\n\n const result: GraphNode[] = [];\n for (const node of this.nodes) {\n if (node.isProcessed()) {\n continue;\n }\n\n const newNodes = node.execute();\n\n if (newNodes instanceof Promise) {\n console.error(\"Asynchronous functions are not allowed in sync mode!\");\n continue;\n }\n\n result.push(...(newNodes as GraphNode[]));\n }\n\n this.end();\n\n return result;\n }\n}\n","import SyncGraphLayer from \"../graph/execution/SyncGraphLayer\";\nimport GraphNode from \"../graph/execution/GraphNode\";\nimport GraphLayer from \"./GraphLayer\";\n\n/**\n * GraphBuilder is an abstract base class designed to construct and manage a graph structure\n * composed of multiple layers. Subclasses are expected to implement the `compose` method\n * based on specific requirements. This class provides methods for adding nodes, managing\n * layers, and resetting the graph construction process.\n *\n * This class supports creating layered graph structures, dynamically adding layers and nodes,\n * and debugging graph-building operations.\n */\nexport default abstract class GraphBuilder {\n graph: GraphLayer | undefined;\n topLayerIndex: number = 0;\n layers: GraphLayer[] = [];\n debug: boolean = false;\n\n setDebug(value: boolean) {\n this.debug = value;\n }\n\n getResult(): GraphLayer {\n return this.graph as GraphLayer;\n }\n\n /**\n * Composes a series of functions or operations.\n * This method should be implemented in the child class\n * to define custom composition logic.\n *\n * @return {any} The result of the composed operations or functions\n * when implemented in the child class.\n */\n compose() {\n throw \"Implement this in child class...\";\n }\n\n /**\n * Adds a node to the appropriate layer of the graph.\n *\n * @param {GraphNode} node - The node to be added to the graph. The node contains\n * layer information that determines which layer it belongs to.\n * @return {void} Does not return a value.\n */\n addNode(node: GraphNode) {\n const index = node.getLayerIndex();\n\n this.addLayer(index);\n const layer = this.getLayer(index);\n\n node.scheduleOn(layer);\n }\n\n /**\n * Adds multiple nodes to the graph.\n *\n * @param {GraphNode[]} nodes - An array of nodes to be added to the graph.\n * @return {void} This method does not return a value.\n */\n addNodes(nodes: GraphNode[]) {\n for (const node of nodes) {\n this.addNode(node);\n }\n }\n\n /**\n * Adds a new layer to the graph at the specified index. If the graph does not exist,\n * it creates the graph using the specified index. Updates the graph's top layer index\n * and maintains the order of layers.\n *\n * @param {number} index - The index at which the new layer should be added to the graph.\n * @return {void} This method does not return a value.\n */\n addLayer(index: number) {\n if (!this.graph) {\n const layer = this.createLayer(index);\n this.graph = layer;\n this.layers.push(layer);\n this.topLayerIndex = index;\n return;\n }\n\n const lastLayerIndex = this.topLayerIndex + this.layers.length - 1;\n\n if (index >= this.topLayerIndex && index <= lastLayerIndex) {\n return;\n }\n\n if (this.topLayerIndex > index) {\n const layer = this.createLayer(this.topLayerIndex - 1);\n layer.setNext(this.layers[0]);\n this.graph = layer;\n this.layers.unshift(layer);\n this.topLayerIndex = this.topLayerIndex - 1;\n this.addLayer(index);\n } else {\n const layer = this.createLayer(lastLayerIndex + 1);\n this.layers[this.layers.length - 1].setNext(layer);\n this.layers.push(layer);\n this.addLayer(index);\n }\n }\n\n /**\n * Creates a new layer for the graph at the specified index.\n *\n * @param {number} index - The index of the layer to be created.\n * @return {GraphLayer} A new instance of the graph layer corresponding to the provided index.\n */\n createLayer(index: number): GraphLayer {\n const layer = new SyncGraphLayer(index);\n layer.setDebug(this.debug);\n return layer;\n }\n\n /**\n * Retrieves a specific layer from the current set of layers.\n *\n * @param {number} layerIndex - The index of the layer to retrieve.\n * @return {*} The layer corresponding to the given index.\n */\n getLayer(layerIndex: number) {\n return this.layers[layerIndex - this.topLayerIndex];\n }\n\n public reset() {\n this.graph = undefined;\n this.topLayerIndex = 0;\n this.layers = [];\n }\n}\n","import GraphBuilder from \"../../interfaces/GraphBuilder\";\nimport GraphNode from \"../../graph/execution/GraphNode\";\n\n/**\n * A builder class for constructing graphs using a breadth-first approach. Extends the\n * functionality of the `GraphBuilder` class to iterate through graph layers and execute\n * operations on each layer in a breadth-first manner.\n *\n * This class is designed to process a graph layer by layer, executing specific logic\n * on nodes of the current layer and adding newly created or discovered nodes to the graph.\n */\nexport default class GraphBreadthFirstBuilder extends GraphBuilder {\n /**\n * Composes layers of a graph by iterating through them, executing their logic,\n * and adding the resulting nodes to the current graph.\n *\n * @return {void} This method does not return a value.\n */\n compose() {\n if (!this.graph) {\n return;\n }\n\n const layers = this.graph.getIterator();\n while (layers.hasNext()) {\n const layer = layers.next();\n const newNodes = layer.execute() as GraphNode[];\n this.addNodes(newNodes);\n }\n }\n}\n","import GraphNode from \"../graph/execution/GraphNode\";\nimport GraphBuilder from \"./GraphBuilder\";\nimport GraphRun from \"../engine/GraphRun\";\nimport GraphBreadthFirstBuilder from \"../engine/builders/GraphBreadthFirstBuilder\";\n\n/**\n * Abstract class representing a strategy for configuring and executing graph operations.\n * Provides a structure for managing graph builders, altering strategies, and updating the execution context.\n *\n * This class cannot be instantiated directly and must be extended by concrete implementations.\n */\nexport default abstract class GraphRunStrategy {\n graphBuilder: GraphBuilder;\n runInstance?: GraphRun;\n\n constructor() {\n this.graphBuilder = new GraphBreadthFirstBuilder();\n }\n\n setRunInstance(runInstance: GraphRun) {\n this.runInstance = runInstance;\n }\n\n changeStrategy(builder: GraphBuilder) {\n this.graphBuilder = builder;\n }\n\n reset() {\n this.graphBuilder.reset();\n }\n\n addNode(node: GraphNode) {\n this.graphBuilder.addNode(node);\n }\n\n updateRunInstance() {\n this.runInstance?.setGraph(this.graphBuilder.getResult());\n }\n\n abstract run(): void;\n abstract export(): any;\n}\n","import GraphNode from \"../graph/execution/GraphNode\";\n\ntype ProcessFunction = (node: GraphNode) => Promise<GraphNode[]> | GraphNode[];\n\n/**\n * The ThrottleEngine class provides a mechanism for controlling the concurrency level\n * of function execution, grouped by tags. It ensures that no more than the specified\n * maximum number of functions per tag run concurrently.\n */\nexport default class ThrottleEngine {\n static instance_: ThrottleEngine;\n\n static get instance() {\n if (!this.instance_) {\n this.instance_ = new ThrottleEngine();\n }\n return this.instance_;\n }\n\n queues: { [tag: string]: [ProcessFunction, GraphNode][] } = {};\n runningCounts: { [tag: string]: number } = {};\n maxConcurrencyPerTag: { [tag: string]: number } = {};\n\n functionIdToPromiseResolve: {\n [functionInstanceId: string]: (value: GraphNode[]) => void;\n } = {};\n\n /**\n * Set a custom concurrency limit for a specific tag\n */\n setConcurrencyLimit(tag: string, limit: number) {\n this.maxConcurrencyPerTag[tag] = limit;\n }\n\n /**\n * Manages the execution of a function `fn` applied on a specified node `node` with controlled concurrency for a given tag.\n * The method ensures that processes are executed in a throttled manner, respecting the maximum concurrency for each tag.\n *\n * @param {ProcessFunction} fn - The function to be executed on the provided node.\n * @param {GraphNode} node - The graph node on which the function `fn` will be applied.\n * @param {string} [tag=\"default\"] - The concurrency grouping tag used to control and group the throttling behavior.\n * @return {Promise<GraphNode[]>} A promise resolving to an array of GraphNode objects once the throttled function execution completes.\n */\n throttle(\n fn: ProcessFunction,\n node: GraphNode,\n tag: string = \"default\",\n ): Promise<GraphNode[]> {\n const functionPromise = new Promise((resolve) => {\n this.functionIdToPromiseResolve[node.id] = resolve as (\n value: GraphNode[],\n ) => void;\n }) as Promise<GraphNode[]>;\n\n this.queues[tag] ??= [];\n this.queues[tag].push([fn, node]);\n\n // Default to 1 if not set\n this.maxConcurrencyPerTag[tag] ??= 1;\n\n this.processQueue(tag);\n\n return functionPromise;\n }\n\n /**\n * Processes the tasks in the queue for a given tag while respecting concurrency limits.\n *\n * @param {string} tag - The identifier for the queue to be processed, used to group tasks and manage concurrency controls.\n * @return {void} Does not return a value; it processes tasks asynchronously and manages state internally.\n */\n processQueue(tag: string) {\n const maxAllowed = this.maxConcurrencyPerTag[tag];\n\n while (\n (this.queues[tag]?.length ?? 0) > 0 &&\n (this.runningCounts[tag] ?? 0) < maxAllowed\n ) {\n this.runningCounts[tag] = (this.runningCounts[tag] || 0) + 1;\n const item = this.queues[tag].shift()!;\n this.process(item).then(() => {\n this.runningCounts[tag]--;\n this.processQueue(tag); // Re-check queue\n });\n }\n\n // Clean up if done\n if (\n (this.queues[tag]?.length ?? 0) === 0 &&\n this.runningCounts[tag] === 0\n ) {\n delete this.queues[tag];\n delete this.runningCounts[tag];\n }\n }\n\n /**\n * Processes a given item consisting of a function and a graph node.\n *\n * @param {Array} item - An array where the first element is a processing function and the second element is a graph node.\n * @param {Function} item[0] - The function to process the graph node.\n * @param {GraphNode} item[1] - The graph node to be processed.\n * @return {Promise<void>} A promise that resolves when the processing and cleanup are complete.\n */\n async process(item: [ProcessFunction, GraphNode]) {\n const fn = item[0];\n const node = item[1];\n\n const context = await fn(node);\n\n this.functionIdToPromiseResolve[node.id](context);\n delete this.functionIdToPromiseResolve[node.id];\n }\n}\n","import GraphNode from \"./GraphNode\";\nimport GraphLayer from \"../../interfaces/GraphLayer\";\nimport ThrottleEngine from \"../../engine/ThrottleEngine\";\n\n/**\n * Represents an asynchronous layer of graph nodes within a graph execution framework.\n * Extends the functionality of the base `GraphLayer` class to handle asynchronous node processing.\n */\nexport default class AsyncGraphLayer extends GraphLayer {\n waitingNodes: GraphNode[] = [];\n processingNodes: Set<GraphNode> = new Set();\n\n constructor(index: number) {\n super(index);\n }\n\n /**\n * Adds a node to the graph and tracks it as a waiting node.\n *\n * @param {GraphNode} node - The graph node to be added.\n * @return {void}\n */\n add(node: GraphNode) {\n this.nodes.push(node);\n this.waitingNodes.push(node);\n }\n\n /**\n * Executes the processing of nodes by iterating over the queued `waitingNodes`,\n * processing each node, and managing concurrency limits where applicable.\n * The method returns a mapping of routine execution IDs to arrays of processed nodes or promises.\n *\n * @return {Object} An object where the keys are routine execution IDs and the values\n * represent arrays of processed nodes or promises resolving to processed nodes.\n */\n execute() {\n if (this.waitingNodes.length === 0) {\n return {};\n }\n\n this.start();\n\n const result: {\n [routineExecId: string]: (GraphNode[] | Promise<GraphNode[]>)[];\n } = {};\n\n while (this.waitingNodes.length > 0) {\n const node = this.waitingNodes.shift();\n if (!node) {\n break;\n }\n\n this.processingNodes.add(node);\n\n result[node.routineExecId] ??= [];\n\n let nextNodes;\n if (node?.getConcurrency()) {\n const tag = node.getTag();\n ThrottleEngine.instance.setConcurrencyLimit(tag, node.getConcurrency());\n nextNodes = ThrottleEngine.instance.throttle(\n this.processNode.bind(this),\n node,\n tag,\n );\n } else {\n nextNodes = this.processNode(node);\n }\n\n result[node.routineExecId].push(nextNodes);\n }\n\n if (this.processingNodes.size === 0) {\n this.end();\n }\n\n return result;\n }\n\n /**\n * Processes the given graph node, executes its logic, and handles synchronous or asynchronous outcomes.\n *\n * @param {GraphNode} node - The graph node to be processed.\n * @return {Promise<GraphNode[]> | GraphNode[]} A promise that resolves to an array of next graph nodes if asynchronous,\n * or an array of next graph nodes if synchronous.\n */\n processNode(node: GraphNode): Promise<GraphNode[]> | GraphNode[] {\n node.start();\n\n const nextNodes = node.execute();\n\n if (nextNodes instanceof Promise) {\n return this.processAsync(node, nextNodes);\n }\n\n this.processingNodes.delete(node);\n\n return nextNodes;\n }\n\n /**\n * Processes the given graph node asynchronously and removes it from the processing nodes set.\n *\n * @param {GraphNode} node - The current graph node being processed.\n * @param {Promise<GraphNode[]>} nextNodes - A promise that resolves to an array of the next graph nodes to process.\n * @return {Promise<GraphNode[]>} A promise that resolves to an array of the next graph nodes.\n */\n async processAsync(node: GraphNode, nextNodes: Promise<GraphNode[]>) {\n const result = await nextNodes;\n this.processingNodes.delete(node);\n return result;\n }\n\n /**\n * Cleans up resources used by the instance by resetting relevant properties and invoking the parent class's destroy method.\n *\n * @return {void} No value is returned as the method performs cleanup operations.\n */\n destroy() {\n super.destroy();\n this.waitingNodes = [];\n this.processingNodes = new Set();\n }\n}\n","import GraphBuilder from \"../../interfaces/GraphBuilder\";\nimport { sleep } from \"../../utils/promise\";\nimport AsyncGraphLayer from \"../../graph/execution/AsyncGraphLayer\";\nimport GraphNode from \"../../graph/execution/GraphNode\";\n\n/**\n * The GraphAsyncQueueBuilder class extends the GraphBuilder class and provides functionality\n * for processing a directed acyclic graph (DAG) asynchronously layer by layer. This class\n * is designed to handle asynchronous execution of graph nodes and manage processing for\n * each layer in an iterative manner.\n *\n * The primary responsibility of this class is to compose the graph by processing its layers,\n * executing asynchronous operations (if any), and managing the dependencies between nodes.\n */\nexport default class GraphAsyncQueueBuilder extends GraphBuilder {\n /**\n * This method iterates over a graph structure and processes its layers sequentially.\n * It continues processing each layer until all layers in the graph are completed.\n * The asynchronous behavior ensures the operation provides breathing room for other\n * tasks/processes to execute during its operation.\n *\n * @return {Promise<void>} A promise that resolves when all layers of the graph are processed or rejects if an error occurs.\n */\n async compose() {\n if (!this.graph) {\n return;\n }\n\n const layers = this.graph.getIterator();\n\n while (true) {\n let layer = layers.getFirst();\n if (layer.graphDone()) {\n return;\n }\n\n this.processLayer(layer as AsyncGraphLayer);\n\n while (layers.hasNext()) {\n layer = layers.next();\n this.processLayer(layer as AsyncGraphLayer);\n }\n\n await sleep(0); // Take a breath\n }\n }\n\n /**\n * Processes a given asynchronous graph layer and executes its nodes.\n * Handles promises within the nodes and adds the resolved or processed\n * nodes to the graph.\n *\n * @param {AsyncGraphLayer} layer - The asynchronous graph layer to be processed.\n * @return {void} - This method does not return a value.\n */\n processLayer(layer: AsyncGraphLayer) {\n const nextNodes = layer.execute();\n for (const routineExecId of Object.keys(nextNodes)) {\n const group = nextNodes[routineExecId];\n if (group.some((nodes) => nodes instanceof Promise)) {\n Promise.all(group).then((result) =>\n this.addNodes(result.flat() as GraphNode[]),\n );\n } else {\n this.addNodes(group.flat() as GraphNode[]);\n }\n }\n }\n\n /**\n * Creates a new instance of AsyncGraphLayer, sets its debug configuration,\n * and returns the created layer.\n *\n * @param {number} index - The index to associate with the new AsyncGraphLayer.\n * @return {AsyncGraphLayer} A new instance of AsyncGraphLayer with the specified index and debug configuration.\n */\n createLayer(index: number) {\n const layer = new AsyncGraphLayer(index);\n layer.setDebug(this.debug);\n return layer;\n }\n}\n","import GraphRunStrategy from \"../../interfaces/GraphRunStrategy\";\nimport GraphAsyncQueueBuilder from \"../builders/GraphAsyncQueueBuilder\";\n\n/**\n * The GraphAsyncRun class extends GraphRunStrategy to implement an asynchronous\n * graph execution strategy. It utilizes a GraphAsyncQueueBuilder for building\n * and composing the graph asynchronously before execution.\n */\nexport default class GraphAsyncRun extends GraphRunStrategy {\n constructor() {\n super();\n this.graphBuilder = new GraphAsyncQueueBuilder();\n }\n\n /**\n * Executes the run operation, which involves composing the graph builder,\n * updating the run instance, and resetting the state.\n *\n * @return {Promise<void>} A promise that resolves when the operation completes.\n */\n async run() {\n await this.graphBuilder.compose();\n this.updateRunInstance();\n this.reset();\n }\n\n reset() {\n super.reset();\n }\n\n export(): any {\n return {};\n }\n}\n","import GraphRunStrategy from \"../../interfaces/GraphRunStrategy\";\n\n/**\n * The GraphStandardRun class extends the GraphRunStrategy and provides\n * a concrete implementation of methods to manage and execute a graph run.\n * This class is responsible for orchestrating the graph composition,\n * updating the run instance, and resetting its state after execution.\n */\nexport default class GraphStandardRun extends GraphRunStrategy {\n /**\n * Executes the sequence of operations involving graph composition,\n * instance updating, and reset mechanisms.\n *\n * @return {void} Does not return a value.\n */\n run() {\n this.graphBuilder.compose();\n this.updateRunInstance();\n this.reset();\n }\n\n export(): any {\n return {};\n }\n}\n","import SignalBroker from \"./engine/SignalBroker\";\nimport GraphRunner from \"./engine/GraphRunner\";\nimport GraphRegistry from \"./registry/GraphRegistry\";\nimport Task, { TaskFunction, ThrottleTagGetter } from \"./graph/definition/Task\";\nimport DebounceTask, { DebounceOptions } from \"./graph/definition/DebounceTask\";\nimport EphemeralTask, {\n EphemeralTaskOptions,\n} from \"./graph/definition/EphemeralTask\";\nimport GraphRoutine from \"./graph/definition/GraphRoutine\";\nimport GraphAsyncRun from \"./engine/strategy/GraphAsyncRun\";\nimport GraphStandardRun from \"./engine/strategy/GraphStandardRun\";\nimport { SchemaDefinition } from \"./types/schema\";\nimport { AnyObject } from \"./types/global\";\n\nexport interface TaskOptions {\n concurrency?: number;\n timeout?: number;\n register?: boolean;\n isUnique?: boolean;\n isMeta?: boolean;\n isSubMeta?: boolean;\n isHidden?: boolean;\n getTagCallback?: ThrottleTagGetter;\n inputSchema?: SchemaDefinition;\n validateInputContext?: boolean;\n outputSchema?: SchemaDefinition;\n validateOutputContext?: boolean;\n retryCount?: number;\n retryDelay?: number;\n retryDelayMax?: number;\n retryDelayFactor?: number;\n}\n\nexport type CadenzaMode = \"dev\" | \"debug\" | \"verbose\" | \"production\";\n\n/**\n * Represents the core class of the Cadenza framework managing tasks, meta-tasks, signal emissions, and execution strategies.\n * All core components such as SignalBroker, GraphRunner, and GraphRegistry are initialized through this class, and it provides\n * utility methods to create, register, and manage various task types.\n */\nexport default class Cadenza {\n public static broker: SignalBroker;\n public static runner: GraphRunner;\n public static metaRunner: GraphRunner;\n public static registry: GraphRegistry;\n static isBootstrapped = false;\n static mode: CadenzaMode = \"production\";\n\n /**\n * Initializes the system by setting up the required components such as the\n * signal broker, runners, and graph registry. Ensures the initialization\n * happens only once. Configures debug settings if applicable.\n *\n * @return {void} No value is returned.\n */\n public static bootstrap(): void {\n if (this.isBootstrapped) return;\n this.isBootstrapped = true;\n\n // 1. SignalBroker (empty, for observations)\n this.broker = SignalBroker.instance;\n\n // 2. Runners (now init broker with them)\n this.runner = new GraphRunner();\n this.metaRunner = new GraphRunner(true);\n this.broker.bootstrap(this.runner, this.metaRunner);\n\n if (this.mode === \"debug\" || this.mode === \"dev\") {\n this.broker.setDebug(true);\n this.runner.setDebug(true);\n this.metaRunner.setDebug(true);\n }\n\n // 3. GraphRegistry (seed observes on broker)\n this.registry = GraphRegistry.instance;\n\n // 4. Runners (create meta tasks)\n this.broker.init();\n this.runner.init();\n this.metaRunner.init();\n }\n\n /**\n * Retrieves the available strategies for running graphs.\n *\n * @return {Object} An object containing the available run strategies, where:\n * - PARALLEL: Executes graph runs asynchronously.\n * - SEQUENTIAL: Executes graph runs in a sequential order.\n */\n public static get runStrategy() {\n return {\n PARALLEL: new GraphAsyncRun(),\n SEQUENTIAL: new GraphStandardRun(),\n };\n }\n\n /**\n * Sets the mode for the application and configures the broker and runner settings accordingly.\n *\n * @param {CadenzaMode} mode - The mode to set. It can be one of the following:\n * \"debug\", \"dev\", \"verbose\", or \"production\".\n * Each mode adjusts debug and verbosity settings.\n * @return {void} This method does not return a value.\n */\n public static setMode(mode: CadenzaMode) {\n this.mode = mode;\n\n this.bootstrap();\n\n if (mode === \"debug\" || mode === \"dev\") {\n this.broker.setDebug(true);\n this.runner.setDebug(true);\n }\n\n if (mode === \"verbose\") {\n this.broker.setDebug(true);\n this.broker.setVerbose(true);\n this.runner.setDebug(true);\n this.runner.setVerbose(true);\n }\n\n if (mode === \"production\") {\n this.broker.setDebug(false);\n this.broker.setVerbose(false);\n this.runner.setDebug(false);\n this.runner.setVerbose(false);\n }\n }\n\n /**\n * Validates the given name to ensure it is a non-empty string.\n * Throws an error if the validation fails.\n *\n * @param {string} name - The name to validate.\n * @return {void} This method does not return anything.\n * @throws {Error} If the name is not a non-empty string.\n */\n public static validateName(name: string): void {\n if (!name || typeof name !== \"string\") {\n throw new Error(\"Task or Routine name must be a non-empty string.\");\n }\n // Further uniqueness check delegated to GraphRegistry.register*\n }\n\n /**\n * Executes the specified task or GraphRoutine with the given context using an internal runner.\n *\n * @param {Task | GraphRoutine} task - The task or GraphRoutine to be executed.\n * @param {AnyObject} context - The context in which the task or GraphRoutine should be executed.\n * @return {void}\n *\n * @example\n * ```ts\n * const task = Cadenza.createTask('My task', (ctx) => {\n * console.log('My task executed with context:', ctx);\n * });\n *\n * Cadenza.run(task, { foo: 'bar' });\n *\n * const routine = Cadenza.createRoutine('My routine', [task], 'My routine description');\n *\n * Cadenza.run(routine, { foo: 'bar' });\n * ```\n */\n public static run(task: Task | GraphRoutine, context: AnyObject) {\n this.runner?.run(task, context);\n }\n\n /**\n * Emits an event with the specified name and data payload to the broker.\n *\n * @param {string} event - The name of the event to emit.\n * @param {AnyObject} [data={}] - The data payload associated with the event.\n * @return {void} - No return value.\n *\n * @example\n * This is meant to be used as a global event emitter.\n * If you want to emit an event from within a task, you can use the `emit` method provided to the task function. See {@link TaskFunction}.\n * ```ts\n * Cadenza.emit('main.my_event', { foo: 'bar' });\n * ```\n */\n public static emit(event: string, data: AnyObject = {}) {\n this.broker?.emit(event, data);\n }\n\n public static schedule(\n taskName: string,\n context: AnyObject,\n timeoutMs: number,\n exactDateTime?: Date,\n ) {\n this.broker?.schedule(taskName, context, timeoutMs, exactDateTime);\n }\n\n public static throttle(\n taskName: string,\n context: AnyObject,\n intervalMs: number,\n leading = false,\n startDateTime?: Date,\n ) {\n this.broker?.throttle(\n taskName,\n context,\n intervalMs,\n leading,\n startDateTime,\n );\n }\n\n public static get(taskName: string): Task | undefined {\n return this.registry?.tasks.get(taskName);\n }\n\n /**\n * Creates and registers a new task with the specified parameters and options.\n * Tasks are the basic building blocks of Cadenza graphs and are responsible for executing logic.\n * See {@link Task} for more information.\n *\n * @param {string} name - The unique name of the task.\n * @param {TaskFunction} func - The function to be executed by the task.\n * @param {string} [description] - An optional description for the task.\n * @param {TaskOptions} [options={}] - Configuration options for the task, such as concurrency, timeout, and retry settings.\n * @return {Task} The created task instance.\n *\n * @example\n * You can use arrow functions to create tasks.\n * ```ts\n * const task = Cadenza.createTask('My task', (ctx) => {\n * console.log('My task executed with context:', ctx);\n * }, 'My task description');\n * ```\n *\n * You can also use named functions to create tasks.\n * This is the preferred way to create tasks since it allows for code inspection in the CadenzaUI.\n * ```ts\n * function myTask(ctx) {\n * console.log('My task executed with context:', ctx);\n * }\n *\n * const task = Cadenza.createTask('My task', myTask);\n * ```\n *\n * ** Use the TaskOptions object to configure the task. **\n *\n * With concurrency limit, timeout limit and retry settings.\n * ```ts\n * Cadenza.createTask('My task', (ctx) => {\n * console.log('My task executed with context:', ctx);\n * }, 'My task description', {\n * concurrency: 10,\n * timeout: 10000,\n * retryCount: 3,\n * retryDelay: 1000,\n * retryDelayFactor: 1.5,\n * });\n * ```\n *\n * You can specify the input and output context schemas for the task.\n * ```ts\n * Cadenza.createTask('My task', (ctx) => {\n * return { bar: 'foo' + ctx.foo };\n * }, 'My task description', {\n * inputContextSchema: {\n * type: 'object',\n * properties: {\n * foo: {\n * type: 'string',\n * },\n * },\n * required: ['foo'],\n * },\n * validateInputContext: true, // default is false\n * outputContextSchema: {\n * type: 'object',\n * properties: {\n * bar: {\n * type: 'string',\n * },\n * },\n * required: ['bar'],\n * },\n * validateOutputContext: true, // default is false\n * });\n * ```\n */\n static createTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions = {},\n ): Task {\n this.bootstrap();\n this.validateName(name);\n\n options = {\n concurrency: 0,\n timeout: 0,\n register: true,\n isUnique: false,\n isMeta: false,\n isSubMeta: false,\n isHidden: false,\n getTagCallback: undefined,\n inputSchema: undefined,\n validateInputContext: false,\n outputSchema: undefined,\n validateOutputContext: false,\n retryCount: 0,\n retryDelay: 0,\n retryDelayMax: 0,\n retryDelayFactor: 1,\n ...options,\n };\n\n return new Task(\n name,\n func,\n description,\n options.concurrency,\n options.timeout,\n options.register,\n options.isUnique,\n options.isMeta,\n options.isSubMeta,\n options.isHidden,\n options.getTagCallback,\n options.inputSchema,\n options.validateInputContext,\n options.outputSchema,\n options.validateOutputContext,\n options.retryCount,\n options.retryDelay,\n options.retryDelayMax,\n options.retryDelayFactor,\n );\n }\n\n /**\n * Creates a meta task with the specified name, functionality, description, and options.\n * This is used for creating tasks that lives on the meta layer.\n * The meta layer is a special layer that is executed separately from the business logic layer and is used for extending Cadenzas core functionality.\n * See {@link Task} or {@link createTask} for more information.\n *\n * @param {string} name - The name of the meta task.\n * @param {TaskFunction} func - The function to be executed by the meta task.\n * @param {string} [description] - An optional description of the meta task.\n * @param {TaskOptions} [options={}] - Additional optional task configuration. Automatically sets `isMeta` to true.\n * @return {Task} A task instance configured as a meta task.\n */\n static createMetaTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions = {},\n ): Task {\n options.isMeta = true;\n return this.createTask(name, func, description, options);\n }\n\n /**\n * Creates a unique task by wrapping the provided task function with a uniqueness constraint.\n * Unique tasks are designed to execute once per execution ID, merging parents. This is useful for\n * tasks that require fan-in/joins after parallel branches.\n * See {@link Task} for more information.\n *\n * @param {string} name - The name of the task to be created.\n * @param {TaskFunction} func - The function that contains the logic for the task. It receives joinedContexts as a list in the context (context.joinedContexts).\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions} [options={}] - Optional configuration for the task, such as additional metadata or task options.\n * @return {Task} The task instance that was created with a uniqueness constraint.\n *\n * @example\n * ```ts\n * const splitTask = Cadenza.createTask('Split foos', function* (ctx) {\n * for (const foo of ctx.foos) {\n * yield { foo };\n * }\n * }, 'Splits a list of foos into multiple sub-branches');\n *\n * const processTask = Cadenza.createTask('Process foo', (ctx) => {\n * return { bar: 'foo' + ctx.foo };\n * }, 'Process a foo');\n *\n * const uniqueTask = Cadenza.createUniqueTask('Gather processed foos', (ctx) => {\n * // A unique task will always be provided with a list of contexts (ctx.joinedContexts) from its predecessors.\n * const processedFoos = ctx.joinedContexts.map((c) => c.bar);\n * return { foos: processedFoos };\n * }, 'Gathers together the processed foos.');\n *\n * splitTask.then(\n * processTask.then(\n * uniqueTask,\n * ),\n * );\n *\n * // Give the flow a name using a routine\n * Cadenza.createRoutine(\n * 'Process foos',\n * [splitTask],\n * 'Processes a list of foos'\n * ).doOn('main.received_foos'); // Subscribe to a signal\n *\n * // Trigger the flow from anywhere\n * Cadenza.emit('main.received_foos', { foos: ['foo1', 'foo2', 'foo3'] });\n * ```\n *\n */\n static createUniqueTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions = {},\n ): Task {\n options.isUnique = true;\n return this.createTask(name, func, description, options);\n }\n\n /**\n * Creates a unique meta task with the specified name, function, description, and options.\n * See {@link createUniqueTask} and {@link createMetaTask} for more information.\n *\n * @param {string} name - The name of the task to create.\n * @param {TaskFunction} func - The function to execute when the task is run.\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions} [options={}] - Optional settings for the task. Defaults to an empty object. Automatically sets `isMeta` and `isUnique` to true.\n * @return {Task} The created unique meta task.\n */\n static createUniqueMetaTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions = {},\n ): Task {\n options.isMeta = true;\n options.isUnique = true;\n return this.createUniqueTask(name, func, description, options);\n }\n\n /**\n * Creates a throttled task with a concurrency limit of 1, ensuring that only one instance of the task can run at a time for a specific throttle tag.\n * This is useful for ensuring execution order and preventing race conditions.\n * See {@link Task} for more information.\n *\n * @param {string} name - The name of the task.\n * @param {TaskFunction} func - The function to be executed when the task runs.\n * @param {ThrottleTagGetter} [throttledIdGetter=() => \"default\"] - A function that generates a throttle tag identifier to group tasks for throttling.\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions} [options={}] - Additional options to customize the task behavior.\n * @return {Task} The created throttled task.\n *\n * @example\n * ```ts\n * const task = Cadenza.createThrottledTask(\n * 'My task',\n * async (ctx) => {\n * await new Promise((resolve) => setTimeout(resolve, 1000));\n * console.log('My task executed with context:', ctx);\n * },\n * // Will throttle by the value of ctx.foo to make sure tasks with the same value are executed sequentially\n * (ctx) => ctx.foo,\n * );\n *\n * Cadenza.run(task, { foo: 'bar' }); // (First execution)\n * Cadenza.run(task, { foo: 'bar' }); // This will be executed after the first execution is finished\n * Cadenza.run(task, { foo: 'baz' }); // This will be executed in parallel with the first execution\n * ```\n */\n static createThrottledTask(\n name: string,\n func: TaskFunction,\n throttledIdGetter: ThrottleTagGetter = () => \"default\",\n description?: string,\n options: TaskOptions = {},\n ): Task {\n options.concurrency = 1;\n options.getTagCallback = throttledIdGetter;\n return this.createTask(name, func, description, options);\n }\n\n /**\n * Creates a throttled meta task with the specified configuration.\n * See {@link createThrottledTask} and {@link createMetaTask} for more information.\n *\n * @param {string} name - The name of the throttled meta task.\n * @param {TaskFunction} func - The task function to be executed.\n * @param {ThrottleTagGetter} throttledIdGetter - A function to retrieve the throttling identifier.\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions} [options={}] - Additional options for configuring the task.\n * @return {Task} The created throttled meta task.\n */\n static createThrottledMetaTask(\n name: string,\n func: TaskFunction,\n throttledIdGetter: ThrottleTagGetter,\n description?: string,\n options: TaskOptions = {},\n ): Task {\n options.isMeta = true;\n return this.createThrottledTask(\n name,\n func,\n throttledIdGetter,\n description,\n options,\n );\n }\n\n /**\n * Creates and returns a new debounced task with the specified parameters.\n * This is useful to prevent rapid execution of tasks that may be triggered by multiple events within a certain time frame.\n * See {@link DebounceTask} for more information.\n *\n * @param {string} name - The unique name of the task to be created.\n * @param {TaskFunction} func - The function to be executed by the task.\n * @param {string} [description] - An optional description of the task.\n * @param {number} [debounceTime=1000] - The debounce time in milliseconds to delay the execution of the task.\n * @param {TaskOptions & DebounceOptions} [options={}] - Additional configuration options for the task, including debounce behavior and other task properties.\n * @return {DebounceTask} A new instance of the DebounceTask with the specified configuration.\n *\n * @example\n * ```ts\n * const task = Cadenza.createDebounceTask(\n * 'My debounced task',\n * (ctx) => {\n * console.log('My task executed with context:', ctx);\n * },\n * 'My debounced task description',\n * 100, // Debounce time in milliseconds. Default is 1000\n * {\n * leading: false, // Should the first execution of a burst be executed immediately? Default is false\n * trailing: true, // Should the last execution of a burst be executed? Default is true\n * maxWait: 1000, // Maximum time in milliseconds to wait for the next execution. Default is 0\n * },\n * );\n *\n * Cadenza.run(task, { foo: 'bar' }); // This will not be executed\n * Cadenza.run(task, { foo: 'bar' }); // This will not be executed\n * Cadenza.run(task, { foo: 'baz' }); // This execution will be delayed by 100ms\n * ```\n */\n static createDebounceTask(\n name: string,\n func: TaskFunction,\n description?: string,\n debounceTime: number = 1000,\n options: TaskOptions & DebounceOptions = {},\n ): DebounceTask {\n this.bootstrap();\n this.validateName(name);\n\n options = {\n concurrency: 0,\n timeout: 0,\n register: true,\n leading: false,\n trailing: true,\n maxWait: 0,\n isUnique: false,\n isMeta: false,\n isSubMeta: false,\n isHidden: false,\n inputSchema: undefined,\n validateInputContext: false,\n outputSchema: undefined,\n validateOutputContext: false,\n ...options,\n };\n\n return new DebounceTask(\n name,\n func,\n description,\n debounceTime,\n options.leading,\n options.trailing,\n options.maxWait,\n options.concurrency,\n options.timeout,\n options.register,\n options.isUnique,\n options.isMeta,\n options.isSubMeta,\n options.isHidden,\n options.inputSchema,\n options.validateInputContext,\n options.outputSchema,\n options.validateOutputContext,\n );\n }\n\n /**\n * Creates a debounced meta task with the specified parameters.\n * See {@link createDebounceTask} and {@link createMetaTask} for more information.\n *\n * @param {string} name - The name of the task.\n * @param {TaskFunction} func - The function to be executed by the task.\n * @param {string} [description] - Optional description of the task.\n * @param {number} [debounceTime=1000] - The debounce delay in milliseconds.\n * @param {TaskOptions & DebounceOptions} [options={}] - Additional configuration options for the task.\n * @return {DebounceTask} Returns an instance of the debounced meta task.\n */\n static createDebounceMetaTask(\n name: string,\n func: TaskFunction,\n description?: string,\n debounceTime: number = 1000,\n options: TaskOptions & DebounceOptions = {},\n ): DebounceTask {\n options.isMeta = true;\n return this.createDebounceTask(\n name,\n func,\n description,\n debounceTime,\n options,\n );\n }\n\n /**\n * Creates an ephemeral task with the specified configuration.\n * Ephemeral tasks are designed to self-destruct after execution or a certain condition is met.\n * This is useful for transient tasks such as resolving promises or performing cleanup operations.\n * They are not registered by default.\n * See {@link EphemeralTask} for more information.\n *\n * @param {string} name - The name of the task to be created.\n * @param {TaskFunction} func - The function that defines the logic of the task.\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions & EphemeralTaskOptions} [options={}] - The configuration options for the task, including concurrency, timeouts, and retry policies.\n * @return {EphemeralTask} The created ephemeral task instance.\n *\n * @example\n * By default, ephemeral tasks are executed once and destroyed after execution.\n * ```ts\n * const task = Cadenza.createEphemeralTask('My ephemeral task', (ctx) => {\n * console.log('My task executed with context:', ctx);\n * });\n *\n * Cadenza.run(task); // Executes the task once and destroys it after execution\n * Cadenza.run(task); // Does nothing, since the task is destroyed\n * ```\n *\n * Use destroy condition to conditionally destroy the task\n * ```ts\n * const task = Cadenza.createEphemeralTask(\n * 'My ephemeral task',\n * (ctx) => {\n * console.log('My task executed with context:', ctx);\n * },\n * 'My ephemeral task description',\n * {\n * once: false, // Should the task be executed only once? Default is true\n * destroyCondition: (ctx) => ctx.foo > 10, // Should the task be destroyed after execution? Default is undefined\n * },\n * );\n *\n * Cadenza.run(task, { foo: 5 }); // The task will not be destroyed and can still be executed\n * Cadenza.run(task, { foo: 10 }); // The task will not be destroyed and can still be executed\n * Cadenza.run(task, { foo: 20 }); // The task will be destroyed after execution and cannot be executed anymore\n * Cadenza.run(task, { foo: 30 }); // This will not be executed\n * ```\n *\n * A practical use case for ephemeral tasks is to resolve a promise upon some external event.\n * ```ts\n * const task = Cadenza.createTask('Confirm something', (ctx, emit) => {\n * return new Promise((resolve) => {\n * ctx.foo = uuid();\n *\n * Cadenza.createEphemeralTask(`Resolve promise of ${ctx.foo}`, (c) => {\n * console.log('My task executed with context:', ctx);\n * resolve(c);\n * }).doOn(`socket.confirmation_received:${ctx.foo}`);\n *\n * emit('this_domain.confirmation_requested', ctx);\n * });\n * });\n * ```\n */\n static createEphemeralTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions & EphemeralTaskOptions = {},\n ): EphemeralTask {\n this.bootstrap();\n this.validateName(name);\n\n options = {\n concurrency: 0,\n timeout: 0,\n register: true,\n isUnique: false,\n isMeta: false,\n isSubMeta: false,\n isHidden: false,\n once: true,\n destroyCondition: () => true,\n getTagCallback: undefined,\n inputSchema: undefined,\n validateInputContext: false,\n outputSchema: undefined,\n validateOutputContext: false,\n retryCount: 0,\n retryDelay: 0,\n retryDelayMax: 0,\n retryDelayFactor: 1,\n ...options,\n };\n\n return new EphemeralTask(\n name,\n func,\n description,\n options.once,\n options.destroyCondition,\n options.concurrency,\n options.timeout,\n options.register,\n options.isUnique,\n options.isMeta,\n options.isSubMeta,\n options.isHidden,\n options.getTagCallback,\n options.inputSchema,\n options.validateInputContext,\n options.outputSchema,\n options.validateOutputContext,\n options.retryCount,\n options.retryDelay,\n options.retryDelayMax,\n options.retryDelayFactor,\n );\n }\n\n /**\n * Creates an ephemeral meta task with the specified name, function, description, and options.\n * See {@link createEphemeralTask} and {@link createMetaTask} for more details.\n *\n * @param {string} name - The name of the task to be created.\n * @param {TaskFunction} func - The function to be executed as part of the task.\n * @param {string} [description] - An optional description of the task.\n * @param {TaskOptions & EphemeralTaskOptions} [options={}] - Additional options for configuring the task.\n * @return {EphemeralTask} The created ephemeral meta task.\n */\n static createEphemeralMetaTask(\n name: string,\n func: TaskFunction,\n description?: string,\n options: TaskOptions & EphemeralTaskOptions = {},\n ): EphemeralTask {\n options.isMeta = true;\n return this.createEphemeralTask(name, func, description, options);\n }\n\n /**\n * Creates a new routine with the specified name, tasks, and an optional description.\n * Routines are named entry points to starting tasks and are registered in the GraphRegistry.\n * They are used to group tasks together and provide a high-level structure for organizing and managing the execution of a set of tasks.\n * See {@link GraphRoutine} for more information.\n *\n * @param {string} name - The name of the routine to create.\n * @param {Task[]} tasks - A list of tasks to include in the routine.\n * @param {string} [description=\"\"] - An optional description for the routine.\n * @return {GraphRoutine} A new instance of the GraphRoutine containing the specified tasks and description.\n *\n * @example\n * ```ts\n * const task1 = Cadenza.createTask(\"Task 1\", () => {});\n * const task2 = Cadenza.createTask(\"Task 2\", () => {});\n *\n * task1.then(task2);\n *\n * const routine = Cadenza.createRoutine(\"Some routine\", [task1]);\n *\n * Cadenza.run(routine);\n *\n * // Or, routines can be triggered by signals\n * routine.doOn(\"some.signal\");\n *\n * Cadenza.emit(\"some.signal\", {});\n * ```\n */\n static createRoutine(\n name: string,\n tasks: Task[],\n description: string = \"\",\n ): GraphRoutine {\n this.bootstrap();\n this.validateName(name);\n if (tasks.length === 0) {\n throw new Error(`Routine '${name}' created with no starting tasks.`);\n }\n return new GraphRoutine(name, tasks, description);\n }\n\n /**\n * Creates a meta routine with a given name, tasks, and optional description.\n * Routines are named entry points to starting tasks and are registered in the GraphRegistry.\n * They are used to group tasks together and provide a high-level structure for organizing and managing the execution of a set of tasks.\n * See {@link GraphRoutine} and {@link createRoutine} for more information.\n *\n * @param {string} name - The name of the routine to be created.\n * @param {Task[]} tasks - An array of tasks that the routine will consist of.\n * @param {string} [description=\"\"] - An optional description for the routine.\n * @return {GraphRoutine} A new instance of the `GraphRoutine` representing the created routine.\n * @throws {Error} If no starting tasks are provided.\n */\n static createMetaRoutine(\n name: string,\n tasks: Task[],\n description: string = \"\",\n ): GraphRoutine {\n this.bootstrap();\n this.validateName(name);\n if (tasks.length === 0) {\n throw new Error(`Routine '${name}' created with no starting tasks.`);\n }\n return new GraphRoutine(name, tasks, description, true);\n }\n\n static reset() {\n this.broker?.reset();\n this.registry?.reset();\n this.isBootstrapped = false;\n }\n}\n","import Task from \"./Task\";\n\nexport default class SignalTask extends Task {\n constructor(signal: string, description: string = \"\") {\n super(signal, () => true, description);\n\n this.signalsToEmitAfter.add(signal);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOO,SAAS,gBACd,OACA,YAAsC,MAAM,OACzC;AACH,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,oBAAI,QAAkB;AAEtC,QAAM,QAA2D,CAAC;AAClE,QAAM,SAAS,MAAM,QAAQ,KAAK,IAAI,CAAC,IAAI,CAAC;AAE5C,QAAM,KAAK,EAAE,QAAQ,OAAO,QAAQ,OAAO,CAAC;AAC5C,UAAQ,IAAI,OAAO,MAAM;AAEzB,SAAO,MAAM,QAAQ;AACnB,UAAM,EAAE,QAAQ,QAAQ,IAAI,IAAI,MAAM,IAAI;AAC1C,UAAM,gBAAgB,QAAQ,SAAY,OAAO,GAAG,IAAI;AAExD;AAAA;AAAA,MAEE,QAAQ,kBACR,QAAQ,qBACR,QAAQ,UACR,QAAQ,aACR,QAAQ,WACR,QAAQ,cACR,QAAQ,gBACR,QAAQ;AAAA,MACR;AACA,aAAO,GAAG,IAAI;AACd;AAAA,IACF;AAEA,eAAW,CAAC,GAAG,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AAC/C,UAA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rE;AACA,WAAO,IAAI,aAAa,MAAM,OAAO,WAAW;AAAA,EAClD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,OAAO,kBACL,MACA,OACA,cAAsB,IACR;AACd,SAAK,UAAU;AACf,SAAK,aAAa,IAAI;AACtB,QAAI,MAAM,WAAW,GAAG;AACtB,YAAM,IAAI,MAAM,YAAY,IAAI,mCAAmC;AAAA,IACrE;AACA,WAAO,IAAI,aAAa,MAAM,OAAO,aAAa,IAAI;AAAA,EACxD;AAAA,EAEA,OAAO,QAAQ;AACb,SAAK,QAAQ,MAAM;AACnB,SAAK,UAAU,MAAM;AACrB,SAAK,iBAAiB;AAAA,EACxB;AACF;AAnxBqB,QAKZ,iBAAiB;AALL,QAMZ,OAAoB;;;AC5C7B,IAAqB,aAArB,cAAwC,KAAK;AAAA,EAC3C,YAAY,QAAgB,cAAsB,IAAI;AACpD,UAAM,QAAQ,MAAM,MAAM,WAAW;AAErC,SAAK,mBAAmB,IAAI,MAAM;AAAA,EACpC;AACF;;;AhCiBA,IAAO,gBAAQ;","names":["uuid","import_uuid","import_uuid","task","uuid","import_uuid","import_uuid","uuid","uuid","context","result","outputValidation","tasks","import_uuid","uuid","uuid"]}
|