@xtr-dev/payload-automation 0.0.32 → 0.0.34
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.
|
@@ -788,17 +788,24 @@ export class WorkflowExecutor {
|
|
|
788
788
|
for (const workflow of workflows.docs){
|
|
789
789
|
// Check if this workflow has a matching trigger
|
|
790
790
|
const triggers = workflow.triggers;
|
|
791
|
-
this.logger.
|
|
791
|
+
this.logger.info({
|
|
792
792
|
workflowId: workflow.id,
|
|
793
793
|
workflowName: workflow.name,
|
|
794
794
|
triggerCount: triggers?.length || 0,
|
|
795
795
|
triggers: triggers?.map((t)=>({
|
|
796
796
|
type: t.type,
|
|
797
|
+
parameters: t.parameters,
|
|
797
798
|
collection: t.parameters?.collection,
|
|
798
799
|
collectionSlug: t.parameters?.collectionSlug,
|
|
799
|
-
operation: t.parameters?.operation
|
|
800
|
-
|
|
801
|
-
|
|
800
|
+
operation: t.parameters?.operation,
|
|
801
|
+
// Debug matching criteria
|
|
802
|
+
typeMatch: t.type === 'collection-trigger',
|
|
803
|
+
collectionMatch: t.parameters?.collection === collection || t.parameters?.collectionSlug === collection,
|
|
804
|
+
operationMatch: t.parameters?.operation === operation
|
|
805
|
+
})),
|
|
806
|
+
targetCollection: collection,
|
|
807
|
+
targetOperation: operation
|
|
808
|
+
}, 'Checking workflow triggers with detailed matching info');
|
|
802
809
|
const matchingTriggers = triggers?.filter((trigger)=>trigger.type === 'collection-trigger' && (trigger.parameters?.collection === collection || trigger.parameters?.collectionSlug === collection) && trigger.parameters?.operation === operation) || [];
|
|
803
810
|
this.logger.info({
|
|
804
811
|
workflowId: workflow.id,
|
|
@@ -833,7 +840,7 @@ export class WorkflowExecutor {
|
|
|
833
840
|
};
|
|
834
841
|
// Check trigger condition if present
|
|
835
842
|
if (trigger.condition) {
|
|
836
|
-
this.logger.
|
|
843
|
+
this.logger.info({
|
|
837
844
|
collection,
|
|
838
845
|
operation,
|
|
839
846
|
condition: trigger.condition,
|
|
@@ -841,8 +848,10 @@ export class WorkflowExecutor {
|
|
|
841
848
|
docFields: doc ? Object.keys(doc) : [],
|
|
842
849
|
previousDocId: previousDoc?.id,
|
|
843
850
|
workflowId: workflow.id,
|
|
844
|
-
workflowName: workflow.name
|
|
845
|
-
|
|
851
|
+
workflowName: workflow.name,
|
|
852
|
+
docStatus: doc?.status,
|
|
853
|
+
previousDocStatus: previousDoc?.status
|
|
854
|
+
}, 'Evaluating trigger condition before execution');
|
|
846
855
|
const conditionMet = this.evaluateCondition(trigger.condition, context);
|
|
847
856
|
if (!conditionMet) {
|
|
848
857
|
this.logger.info({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/workflow-executor.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\n\n// We need to reference the generated types dynamically since they're not available at build time\n// Using generic types and casting where necessary\nexport type PayloadWorkflow = {\n id: number\n name: string\n description?: string | null\n triggers?: Array<{\n type?: string | null\n condition?: string | null\n parameters?: {\n collectionSlug?: string | null\n operation?: string | null\n webhookPath?: string | null\n cronExpression?: string | null\n timezone?: string | null\n global?: string | null\n globalOperation?: string | null\n [key: string]: unknown\n } | null\n [key: string]: unknown\n }> | null\n steps?: Array<{\n step?: string | null\n name?: string | null\n input?: unknown\n dependencies?: string[] | null\n condition?: string | null\n [key: string]: unknown\n }> | null\n [key: string]: unknown\n}\n\nimport { JSONPath } from 'jsonpath-plus'\n\n// Helper type to extract workflow step data from the generated types\nexport type WorkflowStep = NonNullable<PayloadWorkflow['steps']>[0] & {\n name: string // Ensure name is always present for our execution logic\n}\n\n// Helper type to extract workflow trigger data from the generated types \nexport type WorkflowTrigger = NonNullable<PayloadWorkflow['triggers']>[0] & {\n type: string // Ensure type is always present for our execution logic\n}\n\nexport interface ExecutionContext {\n steps: Record<string, {\n error?: string\n input: unknown\n output: unknown\n state: 'failed' | 'pending' | 'running' | 'succeeded'\n _startTime?: number\n executionInfo?: {\n completed: boolean\n success: boolean\n executedAt: string\n duration: number\n failureReason?: string\n }\n errorDetails?: {\n stepId: string\n errorType: string\n duration: number\n attempts: number\n finalError: string\n context: {\n url?: string\n method?: string\n timeout?: number\n statusCode?: number\n headers?: Record<string, string>\n [key: string]: any\n }\n timestamp: string\n }\n }>\n trigger: {\n collection?: string\n data?: unknown\n doc?: unknown\n headers?: Record<string, string>\n operation?: string\n path?: string\n previousDoc?: unknown\n req?: PayloadRequest\n triggeredAt?: string\n type: string\n user?: {\n collection?: string\n email?: string\n id?: string\n }\n }\n}\n\nexport class WorkflowExecutor {\n constructor(\n private payload: Payload,\n private logger: Payload['logger']\n ) {}\n\n /**\n * Evaluate a step condition using JSONPath\n */\n private evaluateStepCondition(condition: string, context: ExecutionContext): boolean {\n return this.evaluateCondition(condition, context)\n }\n\n /**\n * Execute a single workflow step\n */\n private async executeStep(\n step: WorkflowStep,\n stepIndex: number,\n context: ExecutionContext,\n req: PayloadRequest,\n workflowRunId?: number | string\n ): Promise<void> {\n const stepName = step.name || 'step-' + stepIndex\n\n this.logger.info({\n hasStep: 'step' in step,\n step: JSON.stringify(step),\n stepName\n }, 'Executing step')\n\n // Check step condition if present\n if (step.condition) {\n this.logger.debug({\n condition: step.condition,\n stepName,\n availableSteps: Object.keys(context.steps),\n completedSteps: Object.entries(context.steps)\n .filter(([_, s]) => s.state === 'succeeded')\n .map(([name]) => name),\n triggerType: context.trigger?.type\n }, 'Evaluating step condition')\n\n const conditionMet = this.evaluateStepCondition(step.condition, context)\n\n if (!conditionMet) {\n this.logger.info({\n condition: step.condition,\n stepName,\n contextSnapshot: JSON.stringify({\n stepOutputs: Object.entries(context.steps).reduce((acc, [name, step]) => {\n acc[name] = { state: step.state, hasOutput: !!step.output }\n return acc\n }, {} as Record<string, any>),\n triggerData: context.trigger?.data ? 'present' : 'absent'\n })\n }, 'Step condition not met, skipping')\n\n // Mark step as completed but skipped\n context.steps[stepName] = {\n error: undefined,\n input: undefined,\n output: { reason: 'Condition not met', skipped: true },\n state: 'succeeded'\n }\n\n // Update workflow run context if needed\n if (workflowRunId) {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n }\n\n return\n }\n\n this.logger.info({\n condition: step.condition,\n stepName,\n contextSnapshot: JSON.stringify({\n stepOutputs: Object.entries(context.steps).reduce((acc, [name, step]) => {\n acc[name] = { state: step.state, hasOutput: !!step.output }\n return acc\n }, {} as Record<string, any>),\n triggerData: context.trigger?.data ? 'present' : 'absent'\n })\n }, 'Step condition met, proceeding with execution')\n }\n\n // Initialize step context\n context.steps[stepName] = {\n error: undefined,\n input: undefined,\n output: undefined,\n state: 'running',\n _startTime: Date.now() // Track execution start time for independent duration tracking\n }\n\n // Move taskSlug declaration outside try block so it's accessible in catch\n const taskSlug = step.step // Use the 'step' field for task type\n\n try {\n // Extract input data from step - PayloadCMS flattens inputSchema fields to step level\n const inputFields: Record<string, unknown> = {}\n \n // Get all fields except the core step fields\n const coreFields = ['step', 'name', 'dependencies', 'condition']\n for (const [key, value] of Object.entries(step)) {\n if (!coreFields.includes(key)) {\n inputFields[key] = value\n }\n }\n \n // Resolve input data using JSONPath\n const resolvedInput = this.resolveStepInput(inputFields, context)\n context.steps[stepName].input = resolvedInput\n\n if (!taskSlug) {\n throw new Error(`Step ${stepName} is missing a task type`)\n }\n\n this.logger.info({\n hasInput: !!resolvedInput,\n hasReq: !!req,\n stepName,\n taskSlug\n }, 'Queueing task')\n\n const job = await this.payload.jobs.queue({\n input: resolvedInput,\n req,\n task: taskSlug\n })\n\n // Run the specific job immediately and wait for completion\n this.logger.info({ jobId: job.id }, 'Running job immediately using runByID')\n const runResults = await this.payload.jobs.runByID({\n id: job.id,\n req\n })\n \n this.logger.info({ \n jobId: job.id,\n runResult: runResults,\n hasResult: !!runResults\n }, 'Job run completed')\n\n // Give a small delay to ensure job is fully processed\n await new Promise(resolve => setTimeout(resolve, 100))\n\n // Get the job result\n const completedJob = await this.payload.findByID({\n id: job.id,\n collection: 'payload-jobs',\n req\n })\n\n this.logger.info({\n jobId: job.id,\n totalTried: completedJob.totalTried,\n hasError: completedJob.hasError,\n taskStatus: completedJob.taskStatus ? Object.keys(completedJob.taskStatus) : 'null'\n }, 'Retrieved job results')\n\n const taskStatus = completedJob.taskStatus?.[completedJob.taskSlug]?.[completedJob.totalTried]\n const isComplete = taskStatus?.complete === true\n const hasError = completedJob.hasError || !isComplete\n\n // Extract error information from job if available\n let errorMessage: string | undefined\n if (hasError) {\n // Try to get error from the latest log entry\n if (completedJob.log && completedJob.log.length > 0) {\n const latestLog = completedJob.log[completedJob.log.length - 1]\n errorMessage = latestLog.error?.message || latestLog.error\n }\n\n // Fallback to top-level error\n if (!errorMessage && completedJob.error) {\n errorMessage = completedJob.error.message || completedJob.error\n }\n\n // Try to get error from task output if available\n if (!errorMessage && taskStatus?.output?.error) {\n errorMessage = taskStatus.output.error\n }\n \n // Check if task handler returned with state='failed'\n if (!errorMessage && taskStatus?.state === 'failed') {\n errorMessage = 'Task handler returned a failed state'\n // Try to get more specific error from output\n if (taskStatus.output?.error) {\n errorMessage = taskStatus.output.error\n }\n }\n\n // Check for network errors in the job data\n if (!errorMessage && completedJob.result) {\n const result = completedJob.result\n if (result.error) {\n errorMessage = result.error\n }\n }\n\n // Final fallback to generic message with more detail\n if (!errorMessage) {\n const jobDetails = {\n taskSlug,\n hasError: completedJob.hasError,\n taskStatus: taskStatus?.complete,\n totalTried: completedJob.totalTried\n }\n errorMessage = `Task ${taskSlug} failed without detailed error information. Job details: ${JSON.stringify(jobDetails)}`\n }\n }\n\n const result: {\n error: string | undefined\n output: unknown\n state: 'failed' | 'succeeded'\n } = {\n error: errorMessage,\n output: taskStatus?.output || {},\n state: isComplete ? 'succeeded' : 'failed'\n }\n\n // Store the output and error\n context.steps[stepName].output = result.output\n context.steps[stepName].state = result.state\n if (result.error) {\n context.steps[stepName].error = result.error\n }\n\n // Independent execution tracking (not dependent on PayloadCMS task status)\n context.steps[stepName].executionInfo = {\n completed: true, // Step execution completed (regardless of success/failure)\n success: result.state === 'succeeded',\n executedAt: new Date().toISOString(),\n duration: Date.now() - (context.steps[stepName]._startTime || Date.now())\n }\n\n // For failed steps, try to extract detailed error information from the job logs\n // This approach is more reliable than external storage and persists with the workflow\n if (result.state === 'failed') {\n const errorDetails = this.extractErrorDetailsFromJob(completedJob, context.steps[stepName], stepName)\n if (errorDetails) {\n context.steps[stepName].errorDetails = errorDetails\n \n this.logger.info({\n stepName,\n errorType: errorDetails.errorType,\n duration: errorDetails.duration,\n attempts: errorDetails.attempts\n }, 'Extracted detailed error information for failed step')\n }\n }\n\n this.logger.debug({context}, 'Step execution context')\n\n if (result.state !== 'succeeded') {\n throw new Error(result.error || `Step ${stepName} failed`)\n }\n\n this.logger.info({\n output: result.output,\n stepName\n }, 'Step completed')\n\n // Update workflow run with current step results if workflowRunId is provided\n if (workflowRunId) {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n }\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n context.steps[stepName].state = 'failed'\n context.steps[stepName].error = errorMessage\n\n // Independent execution tracking for failed steps\n context.steps[stepName].executionInfo = {\n completed: true, // Execution attempted and completed (even if it failed)\n success: false,\n executedAt: new Date().toISOString(),\n duration: Date.now() - (context.steps[stepName]._startTime || Date.now()),\n failureReason: errorMessage\n }\n\n this.logger.error({\n error: errorMessage,\n input: context.steps[stepName].input,\n stepName,\n taskSlug\n }, 'Step execution failed')\n\n // Update workflow run with current step results if workflowRunId is provided\n if (workflowRunId) {\n try {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n } catch (updateError) {\n this.logger.error({\n error: updateError instanceof Error ? updateError.message : 'Unknown error',\n stepName\n }, 'Failed to update workflow run context after step failure')\n }\n }\n\n throw error\n }\n }\n\n /**\n * Resolve step execution order based on dependencies\n */\n private resolveExecutionOrder(steps: WorkflowStep[]): WorkflowStep[][] {\n const stepMap = new Map<string, WorkflowStep>()\n const dependencyGraph = new Map<string, string[]>()\n const indegree = new Map<string, number>()\n\n // Build the step map and dependency graph\n for (const step of steps) {\n const stepName = step.name || `step-${steps.indexOf(step)}`\n const dependencies = step.dependencies || []\n\n stepMap.set(stepName, { ...step, name: stepName, dependencies })\n dependencyGraph.set(stepName, dependencies)\n indegree.set(stepName, dependencies.length)\n }\n\n // Topological sort to determine execution batches\n const executionBatches: WorkflowStep[][] = []\n const processed = new Set<string>()\n\n while (processed.size < steps.length) {\n const currentBatch: WorkflowStep[] = []\n\n // Find all steps with no remaining dependencies\n for (const [stepName, inDegree] of indegree.entries()) {\n if (inDegree === 0 && !processed.has(stepName)) {\n const step = stepMap.get(stepName)\n if (step) {\n currentBatch.push(step)\n }\n }\n }\n\n if (currentBatch.length === 0) {\n throw new Error('Circular dependency detected in workflow steps')\n }\n\n executionBatches.push(currentBatch)\n\n // Update indegrees for next iteration\n for (const step of currentBatch) {\n processed.add(step.name)\n\n // Reduce indegree for steps that depend on completed steps\n for (const [otherStepName, dependencies] of dependencyGraph.entries()) {\n if (dependencies.includes(step.name) && !processed.has(otherStepName)) {\n indegree.set(otherStepName, (indegree.get(otherStepName) || 0) - 1)\n }\n }\n }\n }\n\n return executionBatches\n }\n\n /**\n * Resolve step input using JSONPath expressions\n */\n private resolveStepInput(config: Record<string, unknown>, context: ExecutionContext): Record<string, unknown> {\n const resolved: Record<string, unknown> = {}\n\n this.logger.debug({\n configKeys: Object.keys(config),\n contextSteps: Object.keys(context.steps),\n triggerType: context.trigger?.type\n }, 'Starting step input resolution')\n\n for (const [key, value] of Object.entries(config)) {\n if (typeof value === 'string' && value.startsWith('$')) {\n // This is a JSONPath expression\n this.logger.debug({\n key,\n jsonPath: value,\n availableSteps: Object.keys(context.steps),\n hasTriggerData: !!context.trigger?.data,\n hasTriggerDoc: !!context.trigger?.doc\n }, 'Resolving JSONPath expression')\n\n try {\n const result = JSONPath({\n json: context,\n path: value,\n wrap: false\n })\n \n this.logger.debug({\n key,\n jsonPath: value,\n result: JSON.stringify(result).substring(0, 200),\n resultType: Array.isArray(result) ? 'array' : typeof result\n }, 'JSONPath resolved successfully')\n \n resolved[key] = result\n } catch (error) {\n this.logger.warn({\n error: error instanceof Error ? error.message : 'Unknown error',\n key,\n path: value,\n contextSnapshot: JSON.stringify(context).substring(0, 500)\n }, 'Failed to resolve JSONPath')\n resolved[key] = value // Keep original value if resolution fails\n }\n } else if (typeof value === 'object' && value !== null) {\n // Recursively resolve nested objects\n this.logger.debug({\n key,\n nestedKeys: Object.keys(value as Record<string, unknown>)\n }, 'Recursively resolving nested object')\n \n resolved[key] = this.resolveStepInput(value as Record<string, unknown>, context)\n } else {\n // Keep literal values as-is\n resolved[key] = value\n }\n }\n\n this.logger.debug({\n resolvedKeys: Object.keys(resolved),\n originalKeys: Object.keys(config)\n }, 'Step input resolution completed')\n\n return resolved\n }\n\n /**\n * Safely serialize an object, handling circular references and non-serializable values\n */\n private safeSerialize(obj: unknown): unknown {\n const seen = new WeakSet()\n \n const serialize = (value: unknown): unknown => {\n if (value === null || typeof value !== 'object') {\n return value\n }\n \n if (seen.has(value as object)) {\n return '[Circular Reference]'\n }\n \n seen.add(value as object)\n \n if (Array.isArray(value)) {\n return value.map(serialize)\n }\n \n const result: Record<string, unknown> = {}\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n try {\n // Skip non-serializable properties that are likely internal database objects\n if (key === 'table' || key === 'schema' || key === '_' || key === '__') {\n continue\n }\n result[key] = serialize(val)\n } catch {\n // Skip properties that can't be accessed or serialized\n result[key] = '[Non-serializable]'\n }\n }\n \n return result\n }\n \n return serialize(obj)\n }\n\n /**\n * Extracts detailed error information from job logs and input\n */\n private extractErrorDetailsFromJob(job: any, stepContext: any, stepName: string) {\n try {\n // Get error information from multiple sources\n const input = stepContext.input || {}\n const logs = job.log || []\n const latestLog = logs[logs.length - 1]\n \n // Extract error message from job error or log\n const errorMessage = job.error?.message || latestLog?.error?.message || 'Unknown error'\n \n // For timeout scenarios, check if it's a timeout based on duration and timeout setting\n let errorType = this.classifyErrorType(errorMessage)\n \n // Special handling for HTTP timeouts - if task failed and duration exceeds timeout, it's likely a timeout\n if (errorType === 'unknown' && input.timeout && stepContext.executionInfo?.duration) {\n const timeoutMs = parseInt(input.timeout) || 30000\n const actualDuration = stepContext.executionInfo.duration\n \n // If execution duration is close to or exceeds timeout, classify as timeout\n if (actualDuration >= (timeoutMs * 0.9)) { // 90% of timeout threshold\n errorType = 'timeout'\n this.logger.debug({\n timeoutMs,\n actualDuration,\n stepName\n }, 'Classified error as timeout based on duration analysis')\n }\n }\n \n // Calculate duration from execution info if available\n const duration = stepContext.executionInfo?.duration || 0\n \n // Extract attempt count from logs\n const attempts = job.totalTried || 1\n \n return {\n stepId: `${stepName}-${Date.now()}`,\n errorType,\n duration,\n attempts,\n finalError: errorMessage,\n context: {\n url: input.url,\n method: input.method,\n timeout: input.timeout,\n statusCode: latestLog?.output?.status,\n headers: input.headers\n },\n timestamp: new Date().toISOString()\n }\n } catch (error) {\n this.logger.warn({\n error: error instanceof Error ? error.message : 'Unknown error',\n stepName\n }, 'Failed to extract error details from job')\n return null\n }\n }\n\n /**\n * Classifies error types based on error messages\n */\n private classifyErrorType(errorMessage: string): string {\n if (errorMessage.includes('timeout') || errorMessage.includes('ETIMEDOUT')) {\n return 'timeout'\n }\n if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('getaddrinfo')) {\n return 'dns'\n }\n if (errorMessage.includes('ECONNREFUSED') || errorMessage.includes('ECONNRESET')) {\n return 'connection'\n }\n if (errorMessage.includes('network') || errorMessage.includes('fetch')) {\n return 'network'\n }\n return 'unknown'\n }\n\n /**\n * Update workflow run with current context\n */\n private async updateWorkflowRunContext(\n workflowRunId: number | string,\n context: ExecutionContext,\n req: PayloadRequest\n ): Promise<void> {\n const serializeContext = () => ({\n steps: this.safeSerialize(context.steps),\n trigger: {\n type: context.trigger.type,\n collection: context.trigger.collection,\n data: this.safeSerialize(context.trigger.data),\n doc: this.safeSerialize(context.trigger.doc),\n operation: context.trigger.operation,\n previousDoc: this.safeSerialize(context.trigger.previousDoc),\n triggeredAt: context.trigger.triggeredAt,\n user: context.trigger.req?.user\n }\n })\n\n await this.payload.update({\n id: workflowRunId,\n collection: 'workflow-runs',\n data: {\n context: serializeContext()\n },\n req\n })\n }\n\n /**\n * Evaluate a condition using JSONPath and comparison operators\n */\n public evaluateCondition(condition: string, context: ExecutionContext): boolean {\n this.logger.debug({\n condition,\n contextKeys: Object.keys(context),\n triggerType: context.trigger?.type,\n triggerData: context.trigger?.data,\n triggerDoc: context.trigger?.doc ? 'present' : 'absent'\n }, 'Starting condition evaluation')\n\n try {\n // Check if this is a comparison expression\n const comparisonMatch = condition.match(/^(.+?)\\s*(==|!=|>|<|>=|<=)\\s*(.+)$/)\n \n if (comparisonMatch) {\n const [, leftExpr, operator, rightExpr] = comparisonMatch\n \n // Evaluate left side (should be JSONPath)\n const leftValue = this.resolveJSONPathValue(leftExpr.trim(), context)\n \n // Parse right side (could be string, number, boolean, or JSONPath)\n const rightValue = this.parseConditionValue(rightExpr.trim(), context)\n \n this.logger.debug({\n condition,\n leftExpr: leftExpr.trim(),\n leftValue,\n operator,\n rightExpr: rightExpr.trim(),\n rightValue,\n leftType: typeof leftValue,\n rightType: typeof rightValue\n }, 'Evaluating comparison condition')\n \n // Perform comparison\n let result: boolean\n switch (operator) {\n case '==':\n result = leftValue === rightValue\n break\n case '!=':\n result = leftValue !== rightValue\n break\n case '>':\n result = Number(leftValue) > Number(rightValue)\n break\n case '<':\n result = Number(leftValue) < Number(rightValue)\n break\n case '>=':\n result = Number(leftValue) >= Number(rightValue)\n break\n case '<=':\n result = Number(leftValue) <= Number(rightValue)\n break\n default:\n throw new Error(`Unknown comparison operator: ${operator}`)\n }\n \n this.logger.debug({\n condition,\n result,\n leftValue,\n rightValue,\n operator\n }, 'Comparison condition evaluation completed')\n \n return result\n } else {\n // Treat as simple JSONPath boolean evaluation\n const result = JSONPath({\n json: context,\n path: condition,\n wrap: false\n })\n\n this.logger.debug({\n condition,\n result,\n resultType: Array.isArray(result) ? 'array' : typeof result,\n resultLength: Array.isArray(result) ? result.length : undefined\n }, 'JSONPath boolean evaluation result')\n\n // Handle different result types\n let finalResult: boolean\n if (Array.isArray(result)) {\n finalResult = result.length > 0 && Boolean(result[0])\n } else {\n finalResult = Boolean(result)\n }\n\n this.logger.debug({\n condition,\n finalResult,\n originalResult: result\n }, 'Boolean condition evaluation completed')\n\n return finalResult\n }\n } catch (error) {\n this.logger.warn({\n condition,\n error: error instanceof Error ? error.message : 'Unknown error',\n errorStack: error instanceof Error ? error.stack : undefined\n }, 'Failed to evaluate condition')\n\n // If condition evaluation fails, assume false\n return false\n }\n }\n \n /**\n * Resolve a JSONPath value from the context\n */\n private resolveJSONPathValue(expr: string, context: ExecutionContext): any {\n if (expr.startsWith('$')) {\n const result = JSONPath({\n json: context,\n path: expr,\n wrap: false\n })\n // Return first result if array, otherwise the result itself\n return Array.isArray(result) && result.length > 0 ? result[0] : result\n }\n return expr\n }\n \n /**\n * Parse a condition value (string literal, number, boolean, or JSONPath)\n */\n private parseConditionValue(expr: string, context: ExecutionContext): any {\n // Handle string literals\n if ((expr.startsWith('\"') && expr.endsWith('\"')) || (expr.startsWith(\"'\") && expr.endsWith(\"'\"))) {\n return expr.slice(1, -1) // Remove quotes\n }\n \n // Handle boolean literals\n if (expr === 'true') return true\n if (expr === 'false') return false\n \n // Handle number literals\n if (/^-?\\d+(\\.\\d+)?$/.test(expr)) {\n return Number(expr)\n }\n \n // Handle JSONPath expressions\n if (expr.startsWith('$')) {\n return this.resolveJSONPathValue(expr, context)\n }\n \n // Return as string if nothing else matches\n return expr\n }\n\n /**\n * Execute a workflow with the given context\n */\n async execute(workflow: PayloadWorkflow, context: ExecutionContext, req: PayloadRequest): Promise<void> {\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Starting workflow execution')\n\n const serializeContext = () => ({\n steps: this.safeSerialize(context.steps),\n trigger: {\n type: context.trigger.type,\n collection: context.trigger.collection,\n data: this.safeSerialize(context.trigger.data),\n doc: this.safeSerialize(context.trigger.doc),\n operation: context.trigger.operation,\n previousDoc: this.safeSerialize(context.trigger.previousDoc),\n triggeredAt: context.trigger.triggeredAt,\n user: context.trigger.req?.user\n }\n })\n\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n contextSummary: {\n triggerType: context.trigger.type,\n triggerCollection: context.trigger.collection,\n triggerOperation: context.trigger.operation,\n hasDoc: !!context.trigger.doc,\n userEmail: context.trigger.req?.user?.email\n }\n }, 'About to create workflow run record')\n\n // Create a workflow run record\n let workflowRun;\n try {\n workflowRun = await this.payload.create({\n collection: 'workflow-runs',\n data: {\n context: serializeContext(),\n startedAt: new Date().toISOString(),\n status: 'running',\n triggeredBy: context.trigger.req?.user?.email || 'system',\n workflow: workflow.id,\n workflowVersion: 1 // Default version since generated type doesn't have _version field\n },\n req\n })\n\n this.logger.info({\n workflowRunId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow run record created successfully')\n } catch (error) {\n this.logger.error({\n error: error instanceof Error ? error.message : 'Unknown error',\n errorStack: error instanceof Error ? error.stack : undefined,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Failed to create workflow run record')\n throw error\n }\n\n try {\n // Resolve execution order based on dependencies\n const executionBatches = this.resolveExecutionOrder(workflow.steps as WorkflowStep[] || [])\n\n this.logger.info({\n batchSizes: executionBatches.map(batch => batch.length),\n totalBatches: executionBatches.length\n }, 'Resolved step execution order')\n\n // Execute each batch in sequence, but steps within each batch in parallel\n for (let batchIndex = 0; batchIndex < executionBatches.length; batchIndex++) {\n const batch = executionBatches[batchIndex]\n\n this.logger.info({\n batchIndex,\n stepCount: batch.length,\n stepNames: batch.map(s => s.name)\n }, 'Executing batch')\n\n // Execute all steps in this batch in parallel\n const batchPromises = batch.map((step, stepIndex) =>\n this.executeStep(step, stepIndex, context, req, workflowRun.id)\n )\n\n // Wait for all steps in the current batch to complete\n await Promise.all(batchPromises)\n\n this.logger.info({\n batchIndex,\n stepCount: batch.length\n }, 'Batch completed')\n }\n\n // Update workflow run as completed\n await this.payload.update({\n id: workflowRun.id,\n collection: 'workflow-runs',\n data: {\n completedAt: new Date().toISOString(),\n context: serializeContext(),\n status: 'completed'\n },\n req\n })\n\n this.logger.info({\n runId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow execution completed')\n\n } catch (error) {\n // Update workflow run as failed\n await this.payload.update({\n id: workflowRun.id,\n collection: 'workflow-runs',\n data: {\n completedAt: new Date().toISOString(),\n context: serializeContext(),\n error: error instanceof Error ? error.message : 'Unknown error',\n status: 'failed'\n },\n req\n })\n\n this.logger.error({\n error: error instanceof Error ? error.message : 'Unknown error',\n runId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow execution failed')\n\n throw error\n }\n }\n\n /**\n * Find and execute workflows triggered by a collection operation\n */\n async executeTriggeredWorkflows(\n collection: string,\n operation: 'create' | 'delete' | 'read' | 'update',\n doc: unknown,\n previousDoc: unknown,\n req: PayloadRequest\n ): Promise<void> {\n console.log('🚨 EXECUTOR: executeTriggeredWorkflows called!')\n console.log('🚨 EXECUTOR: Collection =', collection)\n console.log('🚨 EXECUTOR: Operation =', operation)\n console.log('🚨 EXECUTOR: Doc ID =', (doc as any)?.id)\n console.log('🚨 EXECUTOR: Has payload?', !!this.payload)\n console.log('🚨 EXECUTOR: Has logger?', !!this.logger)\n \n this.logger.info({\n collection,\n operation,\n docId: (doc as any)?.id\n }, 'executeTriggeredWorkflows called')\n \n try {\n // Find workflows with matching triggers\n const workflows = await this.payload.find({\n collection: 'workflows',\n depth: 2, // Include steps and triggers\n limit: 100,\n req\n })\n \n this.logger.info({\n workflowCount: workflows.docs.length\n }, 'Found workflows to check')\n\n for (const workflow of workflows.docs) {\n // Check if this workflow has a matching trigger\n const triggers = workflow.triggers as Array<{\n condition?: string\n type: string\n parameters?: {\n collection?: string\n collectionSlug?: string\n operation?: string\n [key: string]: any\n }\n }>\n \n this.logger.debug({\n workflowId: workflow.id,\n workflowName: workflow.name,\n triggerCount: triggers?.length || 0,\n triggers: triggers?.map(t => ({\n type: t.type,\n collection: t.parameters?.collection,\n collectionSlug: t.parameters?.collectionSlug,\n operation: t.parameters?.operation\n }))\n }, 'Checking workflow triggers')\n\n const matchingTriggers = triggers?.filter(trigger =>\n trigger.type === 'collection-trigger' &&\n (trigger.parameters?.collection === collection || trigger.parameters?.collectionSlug === collection) &&\n trigger.parameters?.operation === operation\n ) || []\n \n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n matchingTriggerCount: matchingTriggers.length,\n targetCollection: collection,\n targetOperation: operation\n }, 'Matching triggers found')\n\n for (const trigger of matchingTriggers) {\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n triggerDetails: {\n type: trigger.type,\n collection: trigger.parameters?.collection,\n collectionSlug: trigger.parameters?.collectionSlug,\n operation: trigger.parameters?.operation,\n hasCondition: !!trigger.condition\n }\n }, 'Processing matching trigger - about to execute workflow')\n\n // Create execution context for condition evaluation\n const context: ExecutionContext = {\n steps: {},\n trigger: {\n type: 'collection',\n collection,\n doc,\n operation,\n previousDoc,\n req\n }\n }\n\n // Check trigger condition if present\n if (trigger.condition) {\n this.logger.debug({\n collection,\n operation,\n condition: trigger.condition,\n docId: (doc as any)?.id,\n docFields: doc ? Object.keys(doc) : [],\n previousDocId: (previousDoc as any)?.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Evaluating collection trigger condition')\n\n const conditionMet = this.evaluateCondition(trigger.condition, context)\n\n if (!conditionMet) {\n this.logger.info({\n collection,\n condition: trigger.condition,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name,\n docSnapshot: JSON.stringify(doc).substring(0, 200)\n }, 'Trigger condition not met, skipping workflow')\n continue\n }\n\n this.logger.info({\n collection,\n condition: trigger.condition,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name,\n docSnapshot: JSON.stringify(doc).substring(0, 200)\n }, 'Trigger condition met')\n }\n\n this.logger.info({\n collection,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Triggering workflow')\n\n // Execute the workflow\n await this.execute(workflow as PayloadWorkflow, context, req)\n }\n }\n } catch (error) {\n this.logger.error({ error: error instanceof Error ? error.message : 'Unknown error' }, 'Workflow execution failed')\n this.logger.error({\n collection,\n error: error instanceof Error ? error.message : 'Unknown error',\n operation\n }, 'Failed to execute triggered workflows')\n }\n }\n}\n"],"names":["JSONPath","WorkflowExecutor","payload","logger","evaluateStepCondition","condition","context","evaluateCondition","executeStep","step","stepIndex","req","workflowRunId","stepName","name","info","hasStep","JSON","stringify","debug","availableSteps","Object","keys","steps","completedSteps","entries","filter","_","s","state","map","triggerType","trigger","type","conditionMet","contextSnapshot","stepOutputs","reduce","acc","hasOutput","output","triggerData","data","error","undefined","input","reason","skipped","updateWorkflowRunContext","_startTime","Date","now","taskSlug","inputFields","coreFields","key","value","includes","resolvedInput","resolveStepInput","Error","hasInput","hasReq","job","jobs","queue","task","jobId","id","runResults","runByID","runResult","hasResult","Promise","resolve","setTimeout","completedJob","findByID","collection","totalTried","hasError","taskStatus","isComplete","complete","errorMessage","log","length","latestLog","message","result","jobDetails","executionInfo","completed","success","executedAt","toISOString","duration","errorDetails","extractErrorDetailsFromJob","errorType","attempts","failureReason","updateError","resolveExecutionOrder","stepMap","Map","dependencyGraph","indegree","indexOf","dependencies","set","executionBatches","processed","Set","size","currentBatch","inDegree","has","get","push","add","otherStepName","config","resolved","configKeys","contextSteps","startsWith","jsonPath","hasTriggerData","hasTriggerDoc","doc","json","path","wrap","substring","resultType","Array","isArray","warn","nestedKeys","resolvedKeys","originalKeys","safeSerialize","obj","seen","WeakSet","serialize","val","stepContext","logs","classifyErrorType","timeout","timeoutMs","parseInt","actualDuration","stepId","finalError","url","method","statusCode","status","headers","timestamp","serializeContext","operation","previousDoc","triggeredAt","user","update","contextKeys","triggerDoc","comparisonMatch","match","leftExpr","operator","rightExpr","leftValue","resolveJSONPathValue","trim","rightValue","parseConditionValue","leftType","rightType","Number","resultLength","finalResult","Boolean","originalResult","errorStack","stack","expr","endsWith","slice","test","execute","workflow","workflowId","workflowName","contextSummary","triggerCollection","triggerOperation","hasDoc","userEmail","email","workflowRun","create","startedAt","triggeredBy","workflowVersion","batchSizes","batch","totalBatches","batchIndex","stepCount","stepNames","batchPromises","all","completedAt","runId","executeTriggeredWorkflows","console","docId","workflows","find","depth","limit","workflowCount","docs","triggers","triggerCount","t","parameters","collectionSlug","matchingTriggers","matchingTriggerCount","targetCollection","targetOperation","triggerDetails","hasCondition","docFields","previousDocId","docSnapshot"],"mappings":"AAkCA,SAASA,QAAQ,QAAQ,gBAAe;AA8DxC,OAAO,MAAMC;;;IACX,YACE,AAAQC,OAAgB,EACxB,AAAQC,MAAyB,CACjC;aAFQD,UAAAA;aACAC,SAAAA;IACP;IAEH;;GAEC,GACD,AAAQC,sBAAsBC,SAAiB,EAAEC,OAAyB,EAAW;QACnF,OAAO,IAAI,CAACC,iBAAiB,CAACF,WAAWC;IAC3C;IAEA;;GAEC,GACD,MAAcE,YACZC,IAAkB,EAClBC,SAAiB,EACjBJ,OAAyB,EACzBK,GAAmB,EACnBC,aAA+B,EAChB;QACf,MAAMC,WAAWJ,KAAKK,IAAI,IAAI,UAAUJ;QAExC,IAAI,CAACP,MAAM,CAACY,IAAI,CAAC;YACfC,SAAS,UAAUP;YACnBA,MAAMQ,KAAKC,SAAS,CAACT;YACrBI;QACF,GAAG;QAEH,kCAAkC;QAClC,IAAIJ,KAAKJ,SAAS,EAAE;YAClB,IAAI,CAACF,MAAM,CAACgB,KAAK,CAAC;gBAChBd,WAAWI,KAAKJ,SAAS;gBACzBQ;gBACAO,gBAAgBC,OAAOC,IAAI,CAAChB,QAAQiB,KAAK;gBACzCC,gBAAgBH,OAAOI,OAAO,CAACnB,QAAQiB,KAAK,EACzCG,MAAM,CAAC,CAAC,CAACC,GAAGC,EAAE,GAAKA,EAAEC,KAAK,KAAK,aAC/BC,GAAG,CAAC,CA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E;wBACvBiI,cAAcF,SAASrL,IAAI;oBAC7B,GAAG;oBAEH,uBAAuB;oBACvB,MAAM,IAAI,CAACoL,OAAO,CAACC,UAA6B7L,SAASK;gBAC3D;YACF;QACF,EAAE,OAAOgC,OAAO;YACd,IAAI,CAACxC,MAAM,CAACwC,KAAK,CAAC;gBAAEA,OAAOA,iBAAiBiB,QAAQjB,MAAM6C,OAAO,GAAG;YAAgB,GAAG;YACvF,IAAI,CAACrF,MAAM,CAACwC,KAAK,CAAC;gBAChBmC;gBACAnC,OAAOA,iBAAiBiB,QAAQjB,MAAM6C,OAAO,GAAG;gBAChD4E;YACF,GAAG;QACL;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/core/workflow-executor.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\n\n// We need to reference the generated types dynamically since they're not available at build time\n// Using generic types and casting where necessary\nexport type PayloadWorkflow = {\n id: number\n name: string\n description?: string | null\n triggers?: Array<{\n type?: string | null\n condition?: string | null\n parameters?: {\n collectionSlug?: string | null\n operation?: string | null\n webhookPath?: string | null\n cronExpression?: string | null\n timezone?: string | null\n global?: string | null\n globalOperation?: string | null\n [key: string]: unknown\n } | null\n [key: string]: unknown\n }> | null\n steps?: Array<{\n step?: string | null\n name?: string | null\n input?: unknown\n dependencies?: string[] | null\n condition?: string | null\n [key: string]: unknown\n }> | null\n [key: string]: unknown\n}\n\nimport { JSONPath } from 'jsonpath-plus'\n\n// Helper type to extract workflow step data from the generated types\nexport type WorkflowStep = NonNullable<PayloadWorkflow['steps']>[0] & {\n name: string // Ensure name is always present for our execution logic\n}\n\n// Helper type to extract workflow trigger data from the generated types \nexport type WorkflowTrigger = NonNullable<PayloadWorkflow['triggers']>[0] & {\n type: string // Ensure type is always present for our execution logic\n}\n\nexport interface ExecutionContext {\n steps: Record<string, {\n error?: string\n input: unknown\n output: unknown\n state: 'failed' | 'pending' | 'running' | 'succeeded'\n _startTime?: number\n executionInfo?: {\n completed: boolean\n success: boolean\n executedAt: string\n duration: number\n failureReason?: string\n }\n errorDetails?: {\n stepId: string\n errorType: string\n duration: number\n attempts: number\n finalError: string\n context: {\n url?: string\n method?: string\n timeout?: number\n statusCode?: number\n headers?: Record<string, string>\n [key: string]: any\n }\n timestamp: string\n }\n }>\n trigger: {\n collection?: string\n data?: unknown\n doc?: unknown\n headers?: Record<string, string>\n operation?: string\n path?: string\n previousDoc?: unknown\n req?: PayloadRequest\n triggeredAt?: string\n type: string\n user?: {\n collection?: string\n email?: string\n id?: string\n }\n }\n}\n\nexport class WorkflowExecutor {\n constructor(\n private payload: Payload,\n private logger: Payload['logger']\n ) {}\n\n /**\n * Evaluate a step condition using JSONPath\n */\n private evaluateStepCondition(condition: string, context: ExecutionContext): boolean {\n return this.evaluateCondition(condition, context)\n }\n\n /**\n * Execute a single workflow step\n */\n private async executeStep(\n step: WorkflowStep,\n stepIndex: number,\n context: ExecutionContext,\n req: PayloadRequest,\n workflowRunId?: number | string\n ): Promise<void> {\n const stepName = step.name || 'step-' + stepIndex\n\n this.logger.info({\n hasStep: 'step' in step,\n step: JSON.stringify(step),\n stepName\n }, 'Executing step')\n\n // Check step condition if present\n if (step.condition) {\n this.logger.debug({\n condition: step.condition,\n stepName,\n availableSteps: Object.keys(context.steps),\n completedSteps: Object.entries(context.steps)\n .filter(([_, s]) => s.state === 'succeeded')\n .map(([name]) => name),\n triggerType: context.trigger?.type\n }, 'Evaluating step condition')\n\n const conditionMet = this.evaluateStepCondition(step.condition, context)\n\n if (!conditionMet) {\n this.logger.info({\n condition: step.condition,\n stepName,\n contextSnapshot: JSON.stringify({\n stepOutputs: Object.entries(context.steps).reduce((acc, [name, step]) => {\n acc[name] = { state: step.state, hasOutput: !!step.output }\n return acc\n }, {} as Record<string, any>),\n triggerData: context.trigger?.data ? 'present' : 'absent'\n })\n }, 'Step condition not met, skipping')\n\n // Mark step as completed but skipped\n context.steps[stepName] = {\n error: undefined,\n input: undefined,\n output: { reason: 'Condition not met', skipped: true },\n state: 'succeeded'\n }\n\n // Update workflow run context if needed\n if (workflowRunId) {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n }\n\n return\n }\n\n this.logger.info({\n condition: step.condition,\n stepName,\n contextSnapshot: JSON.stringify({\n stepOutputs: Object.entries(context.steps).reduce((acc, [name, step]) => {\n acc[name] = { state: step.state, hasOutput: !!step.output }\n return acc\n }, {} as Record<string, any>),\n triggerData: context.trigger?.data ? 'present' : 'absent'\n })\n }, 'Step condition met, proceeding with execution')\n }\n\n // Initialize step context\n context.steps[stepName] = {\n error: undefined,\n input: undefined,\n output: undefined,\n state: 'running',\n _startTime: Date.now() // Track execution start time for independent duration tracking\n }\n\n // Move taskSlug declaration outside try block so it's accessible in catch\n const taskSlug = step.step // Use the 'step' field for task type\n\n try {\n // Extract input data from step - PayloadCMS flattens inputSchema fields to step level\n const inputFields: Record<string, unknown> = {}\n \n // Get all fields except the core step fields\n const coreFields = ['step', 'name', 'dependencies', 'condition']\n for (const [key, value] of Object.entries(step)) {\n if (!coreFields.includes(key)) {\n inputFields[key] = value\n }\n }\n \n // Resolve input data using JSONPath\n const resolvedInput = this.resolveStepInput(inputFields, context)\n context.steps[stepName].input = resolvedInput\n\n if (!taskSlug) {\n throw new Error(`Step ${stepName} is missing a task type`)\n }\n\n this.logger.info({\n hasInput: !!resolvedInput,\n hasReq: !!req,\n stepName,\n taskSlug\n }, 'Queueing task')\n\n const job = await this.payload.jobs.queue({\n input: resolvedInput,\n req,\n task: taskSlug\n })\n\n // Run the specific job immediately and wait for completion\n this.logger.info({ jobId: job.id }, 'Running job immediately using runByID')\n const runResults = await this.payload.jobs.runByID({\n id: job.id,\n req\n })\n \n this.logger.info({ \n jobId: job.id,\n runResult: runResults,\n hasResult: !!runResults\n }, 'Job run completed')\n\n // Give a small delay to ensure job is fully processed\n await new Promise(resolve => setTimeout(resolve, 100))\n\n // Get the job result\n const completedJob = await this.payload.findByID({\n id: job.id,\n collection: 'payload-jobs',\n req\n })\n\n this.logger.info({\n jobId: job.id,\n totalTried: completedJob.totalTried,\n hasError: completedJob.hasError,\n taskStatus: completedJob.taskStatus ? Object.keys(completedJob.taskStatus) : 'null'\n }, 'Retrieved job results')\n\n const taskStatus = completedJob.taskStatus?.[completedJob.taskSlug]?.[completedJob.totalTried]\n const isComplete = taskStatus?.complete === true\n const hasError = completedJob.hasError || !isComplete\n\n // Extract error information from job if available\n let errorMessage: string | undefined\n if (hasError) {\n // Try to get error from the latest log entry\n if (completedJob.log && completedJob.log.length > 0) {\n const latestLog = completedJob.log[completedJob.log.length - 1]\n errorMessage = latestLog.error?.message || latestLog.error\n }\n\n // Fallback to top-level error\n if (!errorMessage && completedJob.error) {\n errorMessage = completedJob.error.message || completedJob.error\n }\n\n // Try to get error from task output if available\n if (!errorMessage && taskStatus?.output?.error) {\n errorMessage = taskStatus.output.error\n }\n \n // Check if task handler returned with state='failed'\n if (!errorMessage && taskStatus?.state === 'failed') {\n errorMessage = 'Task handler returned a failed state'\n // Try to get more specific error from output\n if (taskStatus.output?.error) {\n errorMessage = taskStatus.output.error\n }\n }\n\n // Check for network errors in the job data\n if (!errorMessage && completedJob.result) {\n const result = completedJob.result\n if (result.error) {\n errorMessage = result.error\n }\n }\n\n // Final fallback to generic message with more detail\n if (!errorMessage) {\n const jobDetails = {\n taskSlug,\n hasError: completedJob.hasError,\n taskStatus: taskStatus?.complete,\n totalTried: completedJob.totalTried\n }\n errorMessage = `Task ${taskSlug} failed without detailed error information. Job details: ${JSON.stringify(jobDetails)}`\n }\n }\n\n const result: {\n error: string | undefined\n output: unknown\n state: 'failed' | 'succeeded'\n } = {\n error: errorMessage,\n output: taskStatus?.output || {},\n state: isComplete ? 'succeeded' : 'failed'\n }\n\n // Store the output and error\n context.steps[stepName].output = result.output\n context.steps[stepName].state = result.state\n if (result.error) {\n context.steps[stepName].error = result.error\n }\n\n // Independent execution tracking (not dependent on PayloadCMS task status)\n context.steps[stepName].executionInfo = {\n completed: true, // Step execution completed (regardless of success/failure)\n success: result.state === 'succeeded',\n executedAt: new Date().toISOString(),\n duration: Date.now() - (context.steps[stepName]._startTime || Date.now())\n }\n\n // For failed steps, try to extract detailed error information from the job logs\n // This approach is more reliable than external storage and persists with the workflow\n if (result.state === 'failed') {\n const errorDetails = this.extractErrorDetailsFromJob(completedJob, context.steps[stepName], stepName)\n if (errorDetails) {\n context.steps[stepName].errorDetails = errorDetails\n \n this.logger.info({\n stepName,\n errorType: errorDetails.errorType,\n duration: errorDetails.duration,\n attempts: errorDetails.attempts\n }, 'Extracted detailed error information for failed step')\n }\n }\n\n this.logger.debug({context}, 'Step execution context')\n\n if (result.state !== 'succeeded') {\n throw new Error(result.error || `Step ${stepName} failed`)\n }\n\n this.logger.info({\n output: result.output,\n stepName\n }, 'Step completed')\n\n // Update workflow run with current step results if workflowRunId is provided\n if (workflowRunId) {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n }\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n context.steps[stepName].state = 'failed'\n context.steps[stepName].error = errorMessage\n\n // Independent execution tracking for failed steps\n context.steps[stepName].executionInfo = {\n completed: true, // Execution attempted and completed (even if it failed)\n success: false,\n executedAt: new Date().toISOString(),\n duration: Date.now() - (context.steps[stepName]._startTime || Date.now()),\n failureReason: errorMessage\n }\n\n this.logger.error({\n error: errorMessage,\n input: context.steps[stepName].input,\n stepName,\n taskSlug\n }, 'Step execution failed')\n\n // Update workflow run with current step results if workflowRunId is provided\n if (workflowRunId) {\n try {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n } catch (updateError) {\n this.logger.error({\n error: updateError instanceof Error ? updateError.message : 'Unknown error',\n stepName\n }, 'Failed to update workflow run context after step failure')\n }\n }\n\n throw error\n }\n }\n\n /**\n * Resolve step execution order based on dependencies\n */\n private resolveExecutionOrder(steps: WorkflowStep[]): WorkflowStep[][] {\n const stepMap = new Map<string, WorkflowStep>()\n const dependencyGraph = new Map<string, string[]>()\n const indegree = new Map<string, number>()\n\n // Build the step map and dependency graph\n for (const step of steps) {\n const stepName = step.name || `step-${steps.indexOf(step)}`\n const dependencies = step.dependencies || []\n\n stepMap.set(stepName, { ...step, name: stepName, dependencies })\n dependencyGraph.set(stepName, dependencies)\n indegree.set(stepName, dependencies.length)\n }\n\n // Topological sort to determine execution batches\n const executionBatches: WorkflowStep[][] = []\n const processed = new Set<string>()\n\n while (processed.size < steps.length) {\n const currentBatch: WorkflowStep[] = []\n\n // Find all steps with no remaining dependencies\n for (const [stepName, inDegree] of indegree.entries()) {\n if (inDegree === 0 && !processed.has(stepName)) {\n const step = stepMap.get(stepName)\n if (step) {\n currentBatch.push(step)\n }\n }\n }\n\n if (currentBatch.length === 0) {\n throw new Error('Circular dependency detected in workflow steps')\n }\n\n executionBatches.push(currentBatch)\n\n // Update indegrees for next iteration\n for (const step of currentBatch) {\n processed.add(step.name)\n\n // Reduce indegree for steps that depend on completed steps\n for (const [otherStepName, dependencies] of dependencyGraph.entries()) {\n if (dependencies.includes(step.name) && !processed.has(otherStepName)) {\n indegree.set(otherStepName, (indegree.get(otherStepName) || 0) - 1)\n }\n }\n }\n }\n\n return executionBatches\n }\n\n /**\n * Resolve step input using JSONPath expressions\n */\n private resolveStepInput(config: Record<string, unknown>, context: ExecutionContext): Record<string, unknown> {\n const resolved: Record<string, unknown> = {}\n\n this.logger.debug({\n configKeys: Object.keys(config),\n contextSteps: Object.keys(context.steps),\n triggerType: context.trigger?.type\n }, 'Starting step input resolution')\n\n for (const [key, value] of Object.entries(config)) {\n if (typeof value === 'string' && value.startsWith('$')) {\n // This is a JSONPath expression\n this.logger.debug({\n key,\n jsonPath: value,\n availableSteps: Object.keys(context.steps),\n hasTriggerData: !!context.trigger?.data,\n hasTriggerDoc: !!context.trigger?.doc\n }, 'Resolving JSONPath expression')\n\n try {\n const result = JSONPath({\n json: context,\n path: value,\n wrap: false\n })\n \n this.logger.debug({\n key,\n jsonPath: value,\n result: JSON.stringify(result).substring(0, 200),\n resultType: Array.isArray(result) ? 'array' : typeof result\n }, 'JSONPath resolved successfully')\n \n resolved[key] = result\n } catch (error) {\n this.logger.warn({\n error: error instanceof Error ? error.message : 'Unknown error',\n key,\n path: value,\n contextSnapshot: JSON.stringify(context).substring(0, 500)\n }, 'Failed to resolve JSONPath')\n resolved[key] = value // Keep original value if resolution fails\n }\n } else if (typeof value === 'object' && value !== null) {\n // Recursively resolve nested objects\n this.logger.debug({\n key,\n nestedKeys: Object.keys(value as Record<string, unknown>)\n }, 'Recursively resolving nested object')\n \n resolved[key] = this.resolveStepInput(value as Record<string, unknown>, context)\n } else {\n // Keep literal values as-is\n resolved[key] = value\n }\n }\n\n this.logger.debug({\n resolvedKeys: Object.keys(resolved),\n originalKeys: Object.keys(config)\n }, 'Step input resolution completed')\n\n return resolved\n }\n\n /**\n * Safely serialize an object, handling circular references and non-serializable values\n */\n private safeSerialize(obj: unknown): unknown {\n const seen = new WeakSet()\n \n const serialize = (value: unknown): unknown => {\n if (value === null || typeof value !== 'object') {\n return value\n }\n \n if (seen.has(value as object)) {\n return '[Circular Reference]'\n }\n \n seen.add(value as object)\n \n if (Array.isArray(value)) {\n return value.map(serialize)\n }\n \n const result: Record<string, unknown> = {}\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n try {\n // Skip non-serializable properties that are likely internal database objects\n if (key === 'table' || key === 'schema' || key === '_' || key === '__') {\n continue\n }\n result[key] = serialize(val)\n } catch {\n // Skip properties that can't be accessed or serialized\n result[key] = '[Non-serializable]'\n }\n }\n \n return result\n }\n \n return serialize(obj)\n }\n\n /**\n * Extracts detailed error information from job logs and input\n */\n private extractErrorDetailsFromJob(job: any, stepContext: any, stepName: string) {\n try {\n // Get error information from multiple sources\n const input = stepContext.input || {}\n const logs = job.log || []\n const latestLog = logs[logs.length - 1]\n \n // Extract error message from job error or log\n const errorMessage = job.error?.message || latestLog?.error?.message || 'Unknown error'\n \n // For timeout scenarios, check if it's a timeout based on duration and timeout setting\n let errorType = this.classifyErrorType(errorMessage)\n \n // Special handling for HTTP timeouts - if task failed and duration exceeds timeout, it's likely a timeout\n if (errorType === 'unknown' && input.timeout && stepContext.executionInfo?.duration) {\n const timeoutMs = parseInt(input.timeout) || 30000\n const actualDuration = stepContext.executionInfo.duration\n \n // If execution duration is close to or exceeds timeout, classify as timeout\n if (actualDuration >= (timeoutMs * 0.9)) { // 90% of timeout threshold\n errorType = 'timeout'\n this.logger.debug({\n timeoutMs,\n actualDuration,\n stepName\n }, 'Classified error as timeout based on duration analysis')\n }\n }\n \n // Calculate duration from execution info if available\n const duration = stepContext.executionInfo?.duration || 0\n \n // Extract attempt count from logs\n const attempts = job.totalTried || 1\n \n return {\n stepId: `${stepName}-${Date.now()}`,\n errorType,\n duration,\n attempts,\n finalError: errorMessage,\n context: {\n url: input.url,\n method: input.method,\n timeout: input.timeout,\n statusCode: latestLog?.output?.status,\n headers: input.headers\n },\n timestamp: new Date().toISOString()\n }\n } catch (error) {\n this.logger.warn({\n error: error instanceof Error ? error.message : 'Unknown error',\n stepName\n }, 'Failed to extract error details from job')\n return null\n }\n }\n\n /**\n * Classifies error types based on error messages\n */\n private classifyErrorType(errorMessage: string): string {\n if (errorMessage.includes('timeout') || errorMessage.includes('ETIMEDOUT')) {\n return 'timeout'\n }\n if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('getaddrinfo')) {\n return 'dns'\n }\n if (errorMessage.includes('ECONNREFUSED') || errorMessage.includes('ECONNRESET')) {\n return 'connection'\n }\n if (errorMessage.includes('network') || errorMessage.includes('fetch')) {\n return 'network'\n }\n return 'unknown'\n }\n\n /**\n * Update workflow run with current context\n */\n private async updateWorkflowRunContext(\n workflowRunId: number | string,\n context: ExecutionContext,\n req: PayloadRequest\n ): Promise<void> {\n const serializeContext = () => ({\n steps: this.safeSerialize(context.steps),\n trigger: {\n type: context.trigger.type,\n collection: context.trigger.collection,\n data: this.safeSerialize(context.trigger.data),\n doc: this.safeSerialize(context.trigger.doc),\n operation: context.trigger.operation,\n previousDoc: this.safeSerialize(context.trigger.previousDoc),\n triggeredAt: context.trigger.triggeredAt,\n user: context.trigger.req?.user\n }\n })\n\n await this.payload.update({\n id: workflowRunId,\n collection: 'workflow-runs',\n data: {\n context: serializeContext()\n },\n req\n })\n }\n\n /**\n * Evaluate a condition using JSONPath and comparison operators\n */\n public evaluateCondition(condition: string, context: ExecutionContext): boolean {\n this.logger.debug({\n condition,\n contextKeys: Object.keys(context),\n triggerType: context.trigger?.type,\n triggerData: context.trigger?.data,\n triggerDoc: context.trigger?.doc ? 'present' : 'absent'\n }, 'Starting condition evaluation')\n\n try {\n // Check if this is a comparison expression\n const comparisonMatch = condition.match(/^(.+?)\\s*(==|!=|>|<|>=|<=)\\s*(.+)$/)\n \n if (comparisonMatch) {\n const [, leftExpr, operator, rightExpr] = comparisonMatch\n \n // Evaluate left side (should be JSONPath)\n const leftValue = this.resolveJSONPathValue(leftExpr.trim(), context)\n \n // Parse right side (could be string, number, boolean, or JSONPath)\n const rightValue = this.parseConditionValue(rightExpr.trim(), context)\n \n this.logger.debug({\n condition,\n leftExpr: leftExpr.trim(),\n leftValue,\n operator,\n rightExpr: rightExpr.trim(),\n rightValue,\n leftType: typeof leftValue,\n rightType: typeof rightValue\n }, 'Evaluating comparison condition')\n \n // Perform comparison\n let result: boolean\n switch (operator) {\n case '==':\n result = leftValue === rightValue\n break\n case '!=':\n result = leftValue !== rightValue\n break\n case '>':\n result = Number(leftValue) > Number(rightValue)\n break\n case '<':\n result = Number(leftValue) < Number(rightValue)\n break\n case '>=':\n result = Number(leftValue) >= Number(rightValue)\n break\n case '<=':\n result = Number(leftValue) <= Number(rightValue)\n break\n default:\n throw new Error(`Unknown comparison operator: ${operator}`)\n }\n \n this.logger.debug({\n condition,\n result,\n leftValue,\n rightValue,\n operator\n }, 'Comparison condition evaluation completed')\n \n return result\n } else {\n // Treat as simple JSONPath boolean evaluation\n const result = JSONPath({\n json: context,\n path: condition,\n wrap: false\n })\n\n this.logger.debug({\n condition,\n result,\n resultType: Array.isArray(result) ? 'array' : typeof result,\n resultLength: Array.isArray(result) ? result.length : undefined\n }, 'JSONPath boolean evaluation result')\n\n // Handle different result types\n let finalResult: boolean\n if (Array.isArray(result)) {\n finalResult = result.length > 0 && Boolean(result[0])\n } else {\n finalResult = Boolean(result)\n }\n\n this.logger.debug({\n condition,\n finalResult,\n originalResult: result\n }, 'Boolean condition evaluation completed')\n\n return finalResult\n }\n } catch (error) {\n this.logger.warn({\n condition,\n error: error instanceof Error ? error.message : 'Unknown error',\n errorStack: error instanceof Error ? error.stack : undefined\n }, 'Failed to evaluate condition')\n\n // If condition evaluation fails, assume false\n return false\n }\n }\n \n /**\n * Resolve a JSONPath value from the context\n */\n private resolveJSONPathValue(expr: string, context: ExecutionContext): any {\n if (expr.startsWith('$')) {\n const result = JSONPath({\n json: context,\n path: expr,\n wrap: false\n })\n // Return first result if array, otherwise the result itself\n return Array.isArray(result) && result.length > 0 ? result[0] : result\n }\n return expr\n }\n \n /**\n * Parse a condition value (string literal, number, boolean, or JSONPath)\n */\n private parseConditionValue(expr: string, context: ExecutionContext): any {\n // Handle string literals\n if ((expr.startsWith('\"') && expr.endsWith('\"')) || (expr.startsWith(\"'\") && expr.endsWith(\"'\"))) {\n return expr.slice(1, -1) // Remove quotes\n }\n \n // Handle boolean literals\n if (expr === 'true') return true\n if (expr === 'false') return false\n \n // Handle number literals\n if (/^-?\\d+(\\.\\d+)?$/.test(expr)) {\n return Number(expr)\n }\n \n // Handle JSONPath expressions\n if (expr.startsWith('$')) {\n return this.resolveJSONPathValue(expr, context)\n }\n \n // Return as string if nothing else matches\n return expr\n }\n\n /**\n * Execute a workflow with the given context\n */\n async execute(workflow: PayloadWorkflow, context: ExecutionContext, req: PayloadRequest): Promise<void> {\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Starting workflow execution')\n\n const serializeContext = () => ({\n steps: this.safeSerialize(context.steps),\n trigger: {\n type: context.trigger.type,\n collection: context.trigger.collection,\n data: this.safeSerialize(context.trigger.data),\n doc: this.safeSerialize(context.trigger.doc),\n operation: context.trigger.operation,\n previousDoc: this.safeSerialize(context.trigger.previousDoc),\n triggeredAt: context.trigger.triggeredAt,\n user: context.trigger.req?.user\n }\n })\n\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n contextSummary: {\n triggerType: context.trigger.type,\n triggerCollection: context.trigger.collection,\n triggerOperation: context.trigger.operation,\n hasDoc: !!context.trigger.doc,\n userEmail: context.trigger.req?.user?.email\n }\n }, 'About to create workflow run record')\n\n // Create a workflow run record\n let workflowRun;\n try {\n workflowRun = await this.payload.create({\n collection: 'workflow-runs',\n data: {\n context: serializeContext(),\n startedAt: new Date().toISOString(),\n status: 'running',\n triggeredBy: context.trigger.req?.user?.email || 'system',\n workflow: workflow.id,\n workflowVersion: 1 // Default version since generated type doesn't have _version field\n },\n req\n })\n\n this.logger.info({\n workflowRunId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow run record created successfully')\n } catch (error) {\n this.logger.error({\n error: error instanceof Error ? error.message : 'Unknown error',\n errorStack: error instanceof Error ? error.stack : undefined,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Failed to create workflow run record')\n throw error\n }\n\n try {\n // Resolve execution order based on dependencies\n const executionBatches = this.resolveExecutionOrder(workflow.steps as WorkflowStep[] || [])\n\n this.logger.info({\n batchSizes: executionBatches.map(batch => batch.length),\n totalBatches: executionBatches.length\n }, 'Resolved step execution order')\n\n // Execute each batch in sequence, but steps within each batch in parallel\n for (let batchIndex = 0; batchIndex < executionBatches.length; batchIndex++) {\n const batch = executionBatches[batchIndex]\n\n this.logger.info({\n batchIndex,\n stepCount: batch.length,\n stepNames: batch.map(s => s.name)\n }, 'Executing batch')\n\n // Execute all steps in this batch in parallel\n const batchPromises = batch.map((step, stepIndex) =>\n this.executeStep(step, stepIndex, context, req, workflowRun.id)\n )\n\n // Wait for all steps in the current batch to complete\n await Promise.all(batchPromises)\n\n this.logger.info({\n batchIndex,\n stepCount: batch.length\n }, 'Batch completed')\n }\n\n // Update workflow run as completed\n await this.payload.update({\n id: workflowRun.id,\n collection: 'workflow-runs',\n data: {\n completedAt: new Date().toISOString(),\n context: serializeContext(),\n status: 'completed'\n },\n req\n })\n\n this.logger.info({\n runId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow execution completed')\n\n } catch (error) {\n // Update workflow run as failed\n await this.payload.update({\n id: workflowRun.id,\n collection: 'workflow-runs',\n data: {\n completedAt: new Date().toISOString(),\n context: serializeContext(),\n error: error instanceof Error ? error.message : 'Unknown error',\n status: 'failed'\n },\n req\n })\n\n this.logger.error({\n error: error instanceof Error ? error.message : 'Unknown error',\n runId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow execution failed')\n\n throw error\n }\n }\n\n /**\n * Find and execute workflows triggered by a collection operation\n */\n async executeTriggeredWorkflows(\n collection: string,\n operation: 'create' | 'delete' | 'read' | 'update',\n doc: unknown,\n previousDoc: unknown,\n req: PayloadRequest\n ): Promise<void> {\n console.log('🚨 EXECUTOR: executeTriggeredWorkflows called!')\n console.log('🚨 EXECUTOR: Collection =', collection)\n console.log('🚨 EXECUTOR: Operation =', operation)\n console.log('🚨 EXECUTOR: Doc ID =', (doc as any)?.id)\n console.log('🚨 EXECUTOR: Has payload?', !!this.payload)\n console.log('🚨 EXECUTOR: Has logger?', !!this.logger)\n \n this.logger.info({\n collection,\n operation,\n docId: (doc as any)?.id\n }, 'executeTriggeredWorkflows called')\n \n try {\n // Find workflows with matching triggers\n const workflows = await this.payload.find({\n collection: 'workflows',\n depth: 2, // Include steps and triggers\n limit: 100,\n req\n })\n \n this.logger.info({\n workflowCount: workflows.docs.length\n }, 'Found workflows to check')\n\n for (const workflow of workflows.docs) {\n // Check if this workflow has a matching trigger\n const triggers = workflow.triggers as Array<{\n condition?: string\n type: string\n parameters?: {\n collection?: string\n collectionSlug?: string\n operation?: string\n [key: string]: any\n }\n }>\n \n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n triggerCount: triggers?.length || 0,\n triggers: triggers?.map(t => ({\n type: t.type,\n parameters: t.parameters,\n collection: t.parameters?.collection,\n collectionSlug: t.parameters?.collectionSlug,\n operation: t.parameters?.operation,\n // Debug matching criteria\n typeMatch: t.type === 'collection-trigger',\n collectionMatch: (t.parameters?.collection === collection || t.parameters?.collectionSlug === collection),\n operationMatch: t.parameters?.operation === operation\n })),\n targetCollection: collection,\n targetOperation: operation\n }, 'Checking workflow triggers with detailed matching info')\n\n const matchingTriggers = triggers?.filter(trigger =>\n trigger.type === 'collection-trigger' &&\n (trigger.parameters?.collection === collection || trigger.parameters?.collectionSlug === collection) &&\n trigger.parameters?.operation === operation\n ) || []\n \n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n matchingTriggerCount: matchingTriggers.length,\n targetCollection: collection,\n targetOperation: operation\n }, 'Matching triggers found')\n\n for (const trigger of matchingTriggers) {\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n triggerDetails: {\n type: trigger.type,\n collection: trigger.parameters?.collection,\n collectionSlug: trigger.parameters?.collectionSlug,\n operation: trigger.parameters?.operation,\n hasCondition: !!trigger.condition\n }\n }, 'Processing matching trigger - about to execute workflow')\n\n // Create execution context for condition evaluation\n const context: ExecutionContext = {\n steps: {},\n trigger: {\n type: 'collection',\n collection,\n doc,\n operation,\n previousDoc,\n req\n }\n }\n\n // Check trigger condition if present\n if (trigger.condition) {\n this.logger.info({\n collection,\n operation,\n condition: trigger.condition,\n docId: (doc as any)?.id,\n docFields: doc ? Object.keys(doc) : [],\n previousDocId: (previousDoc as any)?.id,\n workflowId: workflow.id,\n workflowName: workflow.name,\n docStatus: (doc as any)?.status,\n previousDocStatus: (previousDoc as any)?.status\n }, 'Evaluating trigger condition before execution')\n\n const conditionMet = this.evaluateCondition(trigger.condition, context)\n\n if (!conditionMet) {\n this.logger.info({\n collection,\n condition: trigger.condition,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name,\n docSnapshot: JSON.stringify(doc).substring(0, 200)\n }, 'Trigger condition not met, skipping workflow')\n continue\n }\n\n this.logger.info({\n collection,\n condition: trigger.condition,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name,\n docSnapshot: JSON.stringify(doc).substring(0, 200)\n }, 'Trigger condition met')\n }\n\n this.logger.info({\n collection,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Triggering workflow')\n\n // Execute the workflow\n await this.execute(workflow as PayloadWorkflow, context, req)\n }\n }\n } catch (error) {\n this.logger.error({ error: error instanceof Error ? error.message : 'Unknown error' }, 'Workflow execution failed')\n this.logger.error({\n collection,\n error: error instanceof Error ? error.message : 'Unknown error',\n operation\n }, 'Failed to execute triggered workflows')\n }\n }\n}\n"],"names":["JSONPath","WorkflowExecutor","payload","logger","evaluateStepCondition","condition","context","evaluateCondition","executeStep","step","stepIndex","req","workflowRunId","stepName","name","info","hasStep","JSON","stringify","debug","availableSteps","Object","keys","steps","completedSteps","entries","filter","_","s","state","map","triggerType","trigger","type","conditionMet","contextSnapshot","stepOutputs","reduce","acc","hasOutput","output","triggerData","data","error","undefined","input","reason","skipped","updateWorkflowRunContext","_startTime","Date","now","taskSlug","inputFields","coreFields","key","value","includes","resolvedInput","resolveStepInput","Error","hasInput","hasReq","job","jobs","queue","task","jobId","id","runResults","runByID","runResult","hasResult","Promise","resolve","setTimeout","completedJob","findByID","collection","totalTried","hasError","taskStatus","isComplete","complete","errorMessage","log","length","latestLog","message","result","jobDetails","executionInfo","completed","success","executedAt","toISOString","duration","errorDetails","extractErrorDetailsFromJob","errorType","attempts","failureReason","updateError","resolveExecutionOrder","stepMap","Map","dependencyGraph","indegree","indexOf","dependencies","set","executionBatches","processed","Set","size","currentBatch","inDegree","has","get","push","add","otherStepName","config","resolved","configKeys","contextSteps","startsWith","jsonPath","hasTriggerData","hasTriggerDoc","doc","json","path","wrap","substring","resultType","Array","isArray","warn","nestedKeys","resolvedKeys","originalKeys","safeSerialize","obj","seen","WeakSet","serialize","val","stepContext","logs","classifyErrorType","timeout","timeoutMs","parseInt","actualDuration","stepId","finalError","url","method","statusCode","status","headers","timestamp","serializeContext","operation","previousDoc","triggeredAt","user","update","contextKeys","triggerDoc","comparisonMatch","match","leftExpr","operator","rightExpr","leftValue","resolveJSONPathValue","trim","rightValue","parseConditionValue","leftType","rightType","Number","resultLength","finalResult","Boolean","originalResult","errorStack","stack","expr","endsWith","slice","test","execute","workflow","workflowId","workflowName","contextSummary","triggerCollection","triggerOperation","hasDoc","userEmail","email","workflowRun","create","startedAt","triggeredBy","workflowVersion","batchSizes","batch","totalBatches","batchIndex","stepCount","stepNames","batchPromises","all","completedAt","runId","executeTriggeredWorkflows","console","docId","workflows","find","depth","limit","workflowCount","docs","triggers","triggerCount","t","parameters","collectionSlug","typeMatch","collectionMatch","operationMatch","targetCollection","targetOperation","matchingTriggers","matchingTriggerCount","triggerDetails","hasCondition","docFields","previousDocId","docStatus","previousDocStatus","docSnapshot"],"mappings":"AAkCA,SAASA,QAAQ,QAAQ,gBAAe;AA8DxC,OAAO,MAAMC;;;IACX,YACE,AAAQC,OAAgB,EACxB,AAAQC,MAAyB,CACjC;aAFQD,UAAAA;aACAC,SAAAA;IACP;IAEH;;GAEC,GACD,AAAQC,sBAAsBC,SAAiB,EAAEC,OAAyB,EAAW;QACnF,OAAO,IAAI,CAACC,iBAAiB,CAACF,WAAWC;IAC3C;IAEA;;GAEC,GACD,MAAcE,YACZC,IAAkB,EAClBC,SAAiB,EACjBJ,OAAyB,EACzBK,GAAmB,EACnBC,aAA+B,EAChB;QACf,MAAMC,WAAWJ,KAAKK,IAAI,IAAI,UAAUJ;QAExC,IAAI,CAACP,MAAM,CAACY,IAAI,CAAC;YACfC,SAAS,UAAUP;YACnBA,MAAMQ,KAAKC,SAAS,CAACT;YACrBI;QACF,GAAG;QAEH,kCAAkC;QAClC,IAAIJ,KAAKJ,SAAS,EAAE;YAClB,IAAI,CAACF,MAAM,CAACgB,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AI,CAAC/B,MAAM,CAACY,IAAI,CAAC;gCACf+D;gCACAzE,WAAW2B,QAAQ3B,SAAS;gCAC5B+J;gCACAgC,YAAYD,SAAS/H,EAAE;gCACvBiI,cAAcF,SAASrL,IAAI;gCAC3BwO,aAAarO,KAAKC,SAAS,CAACgH,KAAKI,SAAS,CAAC,GAAG;4BAChD,GAAG;4BACH;wBACF;wBAEA,IAAI,CAACnI,MAAM,CAACY,IAAI,CAAC;4BACf+D;4BACAzE,WAAW2B,QAAQ3B,SAAS;4BAC5B+J;4BACAgC,YAAYD,SAAS/H,EAAE;4BACvBiI,cAAcF,SAASrL,IAAI;4BAC3BwO,aAAarO,KAAKC,SAAS,CAACgH,KAAKI,SAAS,CAAC,GAAG;wBAChD,GAAG;oBACL;oBAEA,IAAI,CAACnI,MAAM,CAACY,IAAI,CAAC;wBACf+D;wBACAsF;wBACAgC,YAAYD,SAAS/H,EAAE;wBACvBiI,cAAcF,SAASrL,IAAI;oBAC7B,GAAG;oBAEH,uBAAuB;oBACvB,MAAM,IAAI,CAACoL,OAAO,CAACC,UAA6B7L,SAASK;gBAC3D;YACF;QACF,EAAE,OAAOgC,OAAO;YACd,IAAI,CAACxC,MAAM,CAACwC,KAAK,CAAC;gBAAEA,OAAOA,iBAAiBiB,QAAQjB,MAAM6C,OAAO,GAAG;YAAgB,GAAG;YACvF,IAAI,CAACrF,MAAM,CAACwC,KAAK,CAAC;gBAChBmC;gBACAnC,OAAOA,iBAAiBiB,QAAQjB,MAAM6C,OAAO,GAAG;gBAChD4E;YACF,GAAG;QACL;IACF;AACF"}
|
package/dist/plugin/index.js
CHANGED
|
@@ -126,7 +126,7 @@ export const workflowsPlugin = (pluginOptions)=>(config)=>{
|
|
|
126
126
|
continue;
|
|
127
127
|
}
|
|
128
128
|
const collection = config.collections[collectionIndex];
|
|
129
|
-
logger.
|
|
129
|
+
logger.debug(`Found collection '${triggerSlug}' - modifying its hooks...`);
|
|
130
130
|
// Initialize hooks if needed
|
|
131
131
|
if (!collection.hooks) {
|
|
132
132
|
collection.hooks = {};
|
|
@@ -209,7 +209,7 @@ export const workflowsPlugin = (pluginOptions)=>(config)=>{
|
|
|
209
209
|
});
|
|
210
210
|
// Add the hook to the collection config
|
|
211
211
|
collection.hooks.afterChange.push(automationHook);
|
|
212
|
-
logger.
|
|
212
|
+
logger.debug(`Added automation hook to '${triggerSlug}' - hook count: ${collection.hooks.afterChange.length}`);
|
|
213
213
|
}
|
|
214
214
|
}
|
|
215
215
|
if (!config.jobs) {
|
|
@@ -218,7 +218,7 @@ export const workflowsPlugin = (pluginOptions)=>(config)=>{
|
|
|
218
218
|
};
|
|
219
219
|
}
|
|
220
220
|
const configLogger = getConfigLogger();
|
|
221
|
-
configLogger.
|
|
221
|
+
configLogger.debug(`Configuring workflow plugin with ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers`);
|
|
222
222
|
// Generate cron tasks for workflows with cron triggers
|
|
223
223
|
generateCronTasks(config);
|
|
224
224
|
for (const step of pluginOptions.steps){
|
package/dist/plugin/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type {Config} from 'payload'\n\nimport type {CollectionTriggerConfigCrud, WorkflowsPluginConfig} from \"./config-types.js\"\n\nimport {createWorkflowCollection} from '../collections/Workflow.js'\nimport {WorkflowRunsCollection} from '../collections/WorkflowRuns.js'\nimport {WorkflowExecutor} from '../core/workflow-executor.js'\nimport {generateCronTasks, registerCronJobs} from './cron-scheduler.js'\nimport {initCollectionHooks} from \"./init-collection-hooks.js\"\nimport {initGlobalHooks} from \"./init-global-hooks.js\"\nimport {initStepTasks} from \"./init-step-tasks.js\"\nimport {initWebhookEndpoint} from \"./init-webhook.js\"\nimport {initWorkflowHooks} from './init-workflow-hooks.js'\nimport {getConfigLogger, initializeLogger} from './logger.js'\n\nexport {getLogger} from './logger.js'\n\n// Improved executor registry with proper error handling and logging\ninterface ExecutorRegistry {\n executor: null | WorkflowExecutor\n isInitialized: boolean\n logger: any | null\n}\n\nconst executorRegistry: ExecutorRegistry = {\n executor: null,\n isInitialized: false,\n logger: null\n}\n\nconst setWorkflowExecutor = (executor: WorkflowExecutor, logger: any) => {\n executorRegistry.executor = executor\n executorRegistry.logger = logger\n executorRegistry.isInitialized = true\n\n logger.info('Workflow executor initialized and registered successfully')\n}\n\nconst getExecutorRegistry = (): ExecutorRegistry => {\n return executorRegistry\n}\n\n// Helper function to create failed workflow runs for tracking errors\nconst createFailedWorkflowRun = async (args: any, errorMessage: string, logger: any) => {\n try {\n // Only create failed workflow runs if we have enough context\n if (!args?.req?.payload || !args?.collection?.slug) {\n return\n }\n\n // Find workflows that should have been triggered\n const workflows = await args.req.payload.find({\n collection: 'workflows',\n limit: 10,\n req: args.req,\n where: {\n 'triggers.collectionSlug': {\n equals: args.collection.slug\n },\n 'triggers.operation': {\n equals: args.operation\n },\n 'triggers.type': {\n equals: 'collection-trigger'\n }\n }\n })\n\n // Create failed workflow runs for each matching workflow\n for (const workflow of workflows.docs) {\n await args.req.payload.create({\n collection: 'workflow-runs',\n data: {\n completedAt: new Date().toISOString(),\n context: {\n steps: {},\n trigger: {\n type: 'collection',\n collection: args.collection.slug,\n doc: args.doc,\n operation: args.operation,\n previousDoc: args.previousDoc,\n triggeredAt: new Date().toISOString()\n }\n },\n error: `Hook execution failed: ${errorMessage}`,\n inputs: {},\n logs: [{\n level: 'error',\n message: `Hook execution failed: ${errorMessage}`,\n timestamp: new Date().toISOString()\n }],\n outputs: {},\n startedAt: new Date().toISOString(),\n status: 'failed',\n steps: [],\n triggeredBy: args?.req?.user?.email || 'system',\n workflow: workflow.id,\n workflowVersion: 1\n },\n req: args.req\n })\n }\n\n if (workflows.docs.length > 0) {\n logger.info({\n errorMessage,\n workflowCount: workflows.docs.length\n }, 'Created failed workflow runs for hook execution error')\n }\n\n } catch (error) {\n // Don't let workflow run creation failures break the original operation\n logger.warn({\n error: error instanceof Error ? error.message : 'Unknown error'\n }, 'Failed to create failed workflow run record')\n }\n}\n\nconst applyCollectionsConfig = <T extends string>(pluginOptions: WorkflowsPluginConfig<T>, config: Config) => {\n // Add workflow collections\n if (!config.collections) {\n config.collections = []\n }\n\n config.collections.push(\n createWorkflowCollection(pluginOptions),\n WorkflowRunsCollection\n )\n}\n\n// Removed config-phase hook registration - user collections don't exist during config phase\n\n\nexport const workflowsPlugin =\n <TSlug extends string>(pluginOptions: WorkflowsPluginConfig<TSlug>) =>\n (config: Config): Config => {\n // If the plugin is disabled, return config unchanged\n if (pluginOptions.enabled === false) {\n return config\n }\n\n applyCollectionsConfig<TSlug>(pluginOptions, config)\n\n // CRITICAL: Modify existing collection configs BEFORE PayloadCMS processes them\n // This is the ONLY time we can add hooks that will actually work\n const logger = getConfigLogger()\n logger.info('Attempting to modify collection configs before PayloadCMS initialization...')\n\n if (config.collections && pluginOptions.collectionTriggers) {\n for (const [triggerSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) {\n if (!triggerConfig) {continue}\n\n // Find the collection config that matches\n const collectionIndex = config.collections.findIndex(c => c.slug === triggerSlug)\n if (collectionIndex === -1) {\n logger.warn(`Collection '${triggerSlug}' not found in config.collections`)\n continue\n }\n\n const collection = config.collections[collectionIndex]\n logger.info(`Found collection '${triggerSlug}' - modifying its hooks...`)\n\n // Initialize hooks if needed\n if (!collection.hooks) {\n collection.hooks = {}\n }\n if (!collection.hooks.afterChange) {\n collection.hooks.afterChange = []\n }\n\n // Create a reliable hook function with proper dependency injection\n const automationHook = Object.assign(\n async function payloadAutomationHook(args: any) {\n const registry = getExecutorRegistry()\n\n // Use proper logger if available, fallback to args.req.payload.logger\n const logger = registry.logger || args?.req?.payload?.logger || console\n\n try {\n logger.info({\n collection: args?.collection?.slug,\n docId: args?.doc?.id,\n hookType: 'automation',\n operation: args?.operation\n }, 'Collection automation hook triggered')\n\n if (!registry.isInitialized) {\n logger.warn('Workflow executor not yet initialized, attempting lazy initialization')\n \n try {\n // Try to create executor if we have a payload instance\n if (args.req?.payload) {\n logger.info('Creating workflow executor via lazy initialization')\n const { WorkflowExecutor } = await import('../core/workflow-executor.js')\n const executor = new WorkflowExecutor(args.req.payload, logger)\n setWorkflowExecutor(executor, logger)\n logger.info('Lazy initialization successful')\n } else {\n logger.error('Cannot lazy initialize - no payload instance available')\n await createFailedWorkflowRun(args, 'Workflow executor not initialized and lazy initialization failed - no payload instance', logger)\n return undefined\n }\n } catch (error) {\n logger.error('Lazy initialization failed:', error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n await createFailedWorkflowRun(args, `Workflow executor lazy initialization failed: ${errorMessage}`, logger)\n return undefined\n }\n }\n\n // Re-check registry after potential lazy initialization\n const updatedRegistry = getExecutorRegistry()\n if (!updatedRegistry.executor) {\n logger.error('Workflow executor is null despite being marked as initialized')\n // Create a failed workflow run to track this issue\n await createFailedWorkflowRun(args, 'Executor not available after initialization', logger)\n return undefined\n }\n\n logger.debug('Executing triggered workflows...')\n await updatedRegistry.executor.executeTriggeredWorkflows(\n args.collection.slug,\n args.operation,\n args.doc,\n args.previousDoc,\n args.req\n )\n\n logger.info({\n collection: args?.collection?.slug,\n docId: args?.doc?.id,\n operation: args?.operation\n }, 'Workflow execution completed successfully')\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error({\n collection: args?.collection?.slug,\n docId: args?.doc?.id,\n error: errorMessage,\n errorStack: error instanceof Error ? error.stack : undefined,\n operation: args?.operation\n }, 'Hook execution failed')\n\n // Create a failed workflow run to track this error\n try {\n await createFailedWorkflowRun(args, errorMessage, logger)\n } catch (createError) {\n logger.error({\n error: createError instanceof Error ? createError.message : 'Unknown error'\n }, 'Failed to create workflow run for hook error')\n }\n\n // Don't throw to prevent breaking the original operation\n }\n\n return undefined\n },\n {\n __isAutomationHook: true,\n __version: '0.0.22'\n }\n )\n\n // Add the hook to the collection config\n collection.hooks.afterChange.push(automationHook)\n logger.info(`Added automation hook to '${triggerSlug}' - hook count: ${collection.hooks.afterChange.length}`)\n }\n }\n\n if (!config.jobs) {\n config.jobs = {tasks: []}\n }\n\n const configLogger = getConfigLogger()\n configLogger.info(`Configuring workflow plugin with ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers`)\n\n // Generate cron tasks for workflows with cron triggers\n generateCronTasks(config)\n\n for (const step of pluginOptions.steps) {\n if (!config.jobs?.tasks?.find(task => task.slug === step.slug)) {\n configLogger.debug(`Registering task: ${step.slug}`)\n config.jobs?.tasks?.push(step)\n } else {\n configLogger.debug(`Task ${step.slug} already registered, skipping`)\n }\n }\n\n // Initialize webhook endpoint\n initWebhookEndpoint(config, pluginOptions.webhookPrefix || 'webhook')\n\n // Set up onInit to register collection hooks and initialize features\n const incomingOnInit = config.onInit\n config.onInit = async (payload) => {\n configLogger.info(`onInit called - collections: ${Object.keys(payload.collections).length}`)\n\n // Execute any existing onInit functions first\n if (incomingOnInit) {\n configLogger.debug('Executing existing onInit function')\n await incomingOnInit(payload)\n }\n\n // Initialize the logger with the payload instance\n const logger = initializeLogger(payload)\n logger.info('Logger initialized with payload instance')\n\n // Log collection trigger configuration\n logger.info(`Plugin configuration: ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers, ${pluginOptions.steps?.length || 0} steps`)\n\n // Create workflow executor instance\n console.log('🚨 CREATING WORKFLOW EXECUTOR INSTANCE')\n const executor = new WorkflowExecutor(payload, logger)\n console.log('🚨 EXECUTOR CREATED:', typeof executor)\n console.log('🚨 EXECUTOR METHODS:', Object.getOwnPropertyNames(Object.getPrototypeOf(executor)))\n\n // Register executor with proper dependency injection\n setWorkflowExecutor(executor, logger)\n\n // Hooks are now registered during config phase - just log status\n logger.info('Hooks were registered during config phase - executor now available')\n\n logger.info('Initializing global hooks...')\n initGlobalHooks(payload, logger, executor)\n\n logger.info('Initializing workflow hooks...')\n initWorkflowHooks(payload, logger)\n\n logger.info('Initializing step tasks...')\n initStepTasks(pluginOptions, payload, logger)\n\n // Register cron jobs for workflows with cron triggers\n logger.info('Registering cron jobs...')\n await registerCronJobs(payload, logger)\n\n logger.info('Plugin initialized successfully - all hooks registered')\n }\n\n return config\n }\n"],"names":["createWorkflowCollection","WorkflowRunsCollection","WorkflowExecutor","generateCronTasks","registerCronJobs","initGlobalHooks","initStepTasks","initWebhookEndpoint","initWorkflowHooks","getConfigLogger","initializeLogger","getLogger","executorRegistry","executor","isInitialized","logger","setWorkflowExecutor","info","getExecutorRegistry","createFailedWorkflowRun","args","errorMessage","req","payload","collection","slug","workflows","find","limit","where","equals","operation","workflow","docs","create","data","completedAt","Date","toISOString","context","steps","trigger","type","doc","previousDoc","triggeredAt","error","inputs","logs","level","message","timestamp","outputs","startedAt","status","triggeredBy","user","email","id","workflowVersion","length","workflowCount","warn","Error","applyCollectionsConfig","pluginOptions","config","collections","push","workflowsPlugin","enabled","collectionTriggers","triggerSlug","triggerConfig","Object","entries","collectionIndex","findIndex","c","hooks","afterChange","automationHook","assign","payloadAutomationHook","registry","console","docId","hookType","undefined","String","updatedRegistry","debug","executeTriggeredWorkflows","errorStack","stack","createError","__isAutomationHook","__version","jobs","tasks","configLogger","keys","step","task","webhookPrefix","incomingOnInit","onInit","log","getOwnPropertyNames","getPrototypeOf"],"mappings":"AAIA,SAAQA,wBAAwB,QAAO,6BAA4B;AACnE,SAAQC,sBAAsB,QAAO,iCAAgC;AACrE,SAAQC,gBAAgB,QAAO,+BAA8B;AAC7D,SAAQC,iBAAiB,EAAEC,gBAAgB,QAAO,sBAAqB;AAEvE,SAAQC,eAAe,QAAO,yBAAwB;AACtD,SAAQC,aAAa,QAAO,uBAAsB;AAClD,SAAQC,mBAAmB,QAAO,oBAAmB;AACrD,SAAQC,iBAAiB,QAAO,2BAA0B;AAC1D,SAAQC,eAAe,EAAEC,gBAAgB,QAAO,cAAa;AAE7D,SAAQC,SAAS,QAAO,cAAa;AASrC,MAAMC,mBAAqC;IACzCC,UAAU;IACVC,eAAe;IACfC,QAAQ;AACV;AAEA,MAAMC,sBAAsB,CAACH,UAA4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C,6BAA6B,EAAEyD,OAAO2B,IAAI,CAAC9E,QAAQ4C,WAAW,EAAEP,MAAM,EAAE;YAE3F,8CAA8C;YAC9C,IAAI6C,gBAAgB;gBAClBL,aAAaT,KAAK,CAAC;gBACnB,MAAMc,eAAelF;YACvB;YAEA,kDAAkD;YAClD,MAAMR,SAASL,iBAAiBa;YAChCR,OAAOE,IAAI,CAAC;YAEZ,uCAAuC;YACvCF,OAAOE,IAAI,CAAC,CAAC,sBAAsB,EAAEyD,OAAO2B,IAAI,CAACpC,cAAcM,kBAAkB,IAAI,CAAC,GAAGX,MAAM,CAAC,sBAAsB,EAAEK,cAAczB,KAAK,EAAEoB,UAAU,EAAE,MAAM,CAAC;YAEhK,oCAAoC;YACpCyB,QAAQsB,GAAG,CAAC;YACZ,MAAM9F,WAAW,IAAIX,iBAAiBqB,SAASR;YAC/CsE,QAAQsB,GAAG,CAAC,wBAAwB,OAAO9F;YAC3CwE,QAAQsB,GAAG,CAAC,wBAAwBjC,OAAOkC,mBAAmB,CAAClC,OAAOmC,cAAc,CAAChG;YAErF,qDAAqD;YACrDG,oBAAoBH,UAAUE;YAE9B,iEAAiE;YACjEA,OAAOE,IAAI,CAAC;YAEZF,OAAOE,IAAI,CAAC;YACZZ,gBAAgBkB,SAASR,QAAQF;YAEjCE,OAAOE,IAAI,CAAC;YACZT,kBAAkBe,SAASR;YAE3BA,OAAOE,IAAI,CAAC;YACZX,cAAc2D,eAAe1C,SAASR;YAEtC,sDAAsD;YACtDA,OAAOE,IAAI,CAAC;YACZ,MAAMb,iBAAiBmB,SAASR;YAEhCA,OAAOE,IAAI,CAAC;QACd;QAEA,OAAOiD;IACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type {Config} from 'payload'\n\nimport type {CollectionTriggerConfigCrud, WorkflowsPluginConfig} from \"./config-types.js\"\n\nimport {createWorkflowCollection} from '../collections/Workflow.js'\nimport {WorkflowRunsCollection} from '../collections/WorkflowRuns.js'\nimport {WorkflowExecutor} from '../core/workflow-executor.js'\nimport {generateCronTasks, registerCronJobs} from './cron-scheduler.js'\nimport {initCollectionHooks} from \"./init-collection-hooks.js\"\nimport {initGlobalHooks} from \"./init-global-hooks.js\"\nimport {initStepTasks} from \"./init-step-tasks.js\"\nimport {initWebhookEndpoint} from \"./init-webhook.js\"\nimport {initWorkflowHooks} from './init-workflow-hooks.js'\nimport {getConfigLogger, initializeLogger} from './logger.js'\n\nexport {getLogger} from './logger.js'\n\n// Improved executor registry with proper error handling and logging\ninterface ExecutorRegistry {\n executor: null | WorkflowExecutor\n isInitialized: boolean\n logger: any | null\n}\n\nconst executorRegistry: ExecutorRegistry = {\n executor: null,\n isInitialized: false,\n logger: null\n}\n\nconst setWorkflowExecutor = (executor: WorkflowExecutor, logger: any) => {\n executorRegistry.executor = executor\n executorRegistry.logger = logger\n executorRegistry.isInitialized = true\n\n logger.info('Workflow executor initialized and registered successfully')\n}\n\nconst getExecutorRegistry = (): ExecutorRegistry => {\n return executorRegistry\n}\n\n// Helper function to create failed workflow runs for tracking errors\nconst createFailedWorkflowRun = async (args: any, errorMessage: string, logger: any) => {\n try {\n // Only create failed workflow runs if we have enough context\n if (!args?.req?.payload || !args?.collection?.slug) {\n return\n }\n\n // Find workflows that should have been triggered\n const workflows = await args.req.payload.find({\n collection: 'workflows',\n limit: 10,\n req: args.req,\n where: {\n 'triggers.collectionSlug': {\n equals: args.collection.slug\n },\n 'triggers.operation': {\n equals: args.operation\n },\n 'triggers.type': {\n equals: 'collection-trigger'\n }\n }\n })\n\n // Create failed workflow runs for each matching workflow\n for (const workflow of workflows.docs) {\n await args.req.payload.create({\n collection: 'workflow-runs',\n data: {\n completedAt: new Date().toISOString(),\n context: {\n steps: {},\n trigger: {\n type: 'collection',\n collection: args.collection.slug,\n doc: args.doc,\n operation: args.operation,\n previousDoc: args.previousDoc,\n triggeredAt: new Date().toISOString()\n }\n },\n error: `Hook execution failed: ${errorMessage}`,\n inputs: {},\n logs: [{\n level: 'error',\n message: `Hook execution failed: ${errorMessage}`,\n timestamp: new Date().toISOString()\n }],\n outputs: {},\n startedAt: new Date().toISOString(),\n status: 'failed',\n steps: [],\n triggeredBy: args?.req?.user?.email || 'system',\n workflow: workflow.id,\n workflowVersion: 1\n },\n req: args.req\n })\n }\n\n if (workflows.docs.length > 0) {\n logger.info({\n errorMessage,\n workflowCount: workflows.docs.length\n }, 'Created failed workflow runs for hook execution error')\n }\n\n } catch (error) {\n // Don't let workflow run creation failures break the original operation\n logger.warn({\n error: error instanceof Error ? error.message : 'Unknown error'\n }, 'Failed to create failed workflow run record')\n }\n}\n\nconst applyCollectionsConfig = <T extends string>(pluginOptions: WorkflowsPluginConfig<T>, config: Config) => {\n // Add workflow collections\n if (!config.collections) {\n config.collections = []\n }\n\n config.collections.push(\n createWorkflowCollection(pluginOptions),\n WorkflowRunsCollection\n )\n}\n\n// Removed config-phase hook registration - user collections don't exist during config phase\n\n\nexport const workflowsPlugin =\n <TSlug extends string>(pluginOptions: WorkflowsPluginConfig<TSlug>) =>\n (config: Config): Config => {\n // If the plugin is disabled, return config unchanged\n if (pluginOptions.enabled === false) {\n return config\n }\n\n applyCollectionsConfig<TSlug>(pluginOptions, config)\n\n // CRITICAL: Modify existing collection configs BEFORE PayloadCMS processes them\n // This is the ONLY time we can add hooks that will actually work\n const logger = getConfigLogger()\n logger.info('Attempting to modify collection configs before PayloadCMS initialization...')\n\n if (config.collections && pluginOptions.collectionTriggers) {\n for (const [triggerSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) {\n if (!triggerConfig) {continue}\n\n // Find the collection config that matches\n const collectionIndex = config.collections.findIndex(c => c.slug === triggerSlug)\n if (collectionIndex === -1) {\n logger.warn(`Collection '${triggerSlug}' not found in config.collections`)\n continue\n }\n\n const collection = config.collections[collectionIndex]\n logger.debug(`Found collection '${triggerSlug}' - modifying its hooks...`)\n\n // Initialize hooks if needed\n if (!collection.hooks) {\n collection.hooks = {}\n }\n if (!collection.hooks.afterChange) {\n collection.hooks.afterChange = []\n }\n\n // Create a reliable hook function with proper dependency injection\n const automationHook = Object.assign(\n async function payloadAutomationHook(args: any) {\n const registry = getExecutorRegistry()\n\n // Use proper logger if available, fallback to args.req.payload.logger\n const logger = registry.logger || args?.req?.payload?.logger || console\n\n try {\n logger.info({\n collection: args?.collection?.slug,\n docId: args?.doc?.id,\n hookType: 'automation',\n operation: args?.operation\n }, 'Collection automation hook triggered')\n\n if (!registry.isInitialized) {\n logger.warn('Workflow executor not yet initialized, attempting lazy initialization')\n \n try {\n // Try to create executor if we have a payload instance\n if (args.req?.payload) {\n logger.info('Creating workflow executor via lazy initialization')\n const { WorkflowExecutor } = await import('../core/workflow-executor.js')\n const executor = new WorkflowExecutor(args.req.payload, logger)\n setWorkflowExecutor(executor, logger)\n logger.info('Lazy initialization successful')\n } else {\n logger.error('Cannot lazy initialize - no payload instance available')\n await createFailedWorkflowRun(args, 'Workflow executor not initialized and lazy initialization failed - no payload instance', logger)\n return undefined\n }\n } catch (error) {\n logger.error('Lazy initialization failed:', error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n await createFailedWorkflowRun(args, `Workflow executor lazy initialization failed: ${errorMessage}`, logger)\n return undefined\n }\n }\n\n // Re-check registry after potential lazy initialization\n const updatedRegistry = getExecutorRegistry()\n if (!updatedRegistry.executor) {\n logger.error('Workflow executor is null despite being marked as initialized')\n // Create a failed workflow run to track this issue\n await createFailedWorkflowRun(args, 'Executor not available after initialization', logger)\n return undefined\n }\n\n logger.debug('Executing triggered workflows...')\n await updatedRegistry.executor.executeTriggeredWorkflows(\n args.collection.slug,\n args.operation,\n args.doc,\n args.previousDoc,\n args.req\n )\n\n logger.info({\n collection: args?.collection?.slug,\n docId: args?.doc?.id,\n operation: args?.operation\n }, 'Workflow execution completed successfully')\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error({\n collection: args?.collection?.slug,\n docId: args?.doc?.id,\n error: errorMessage,\n errorStack: error instanceof Error ? error.stack : undefined,\n operation: args?.operation\n }, 'Hook execution failed')\n\n // Create a failed workflow run to track this error\n try {\n await createFailedWorkflowRun(args, errorMessage, logger)\n } catch (createError) {\n logger.error({\n error: createError instanceof Error ? createError.message : 'Unknown error'\n }, 'Failed to create workflow run for hook error')\n }\n\n // Don't throw to prevent breaking the original operation\n }\n\n return undefined\n },\n {\n __isAutomationHook: true,\n __version: '0.0.22'\n }\n )\n\n // Add the hook to the collection config\n collection.hooks.afterChange.push(automationHook)\n logger.debug(`Added automation hook to '${triggerSlug}' - hook count: ${collection.hooks.afterChange.length}`)\n }\n }\n\n if (!config.jobs) {\n config.jobs = {tasks: []}\n }\n\n const configLogger = getConfigLogger()\n configLogger.debug(`Configuring workflow plugin with ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers`)\n\n // Generate cron tasks for workflows with cron triggers\n generateCronTasks(config)\n\n for (const step of pluginOptions.steps) {\n if (!config.jobs?.tasks?.find(task => task.slug === step.slug)) {\n configLogger.debug(`Registering task: ${step.slug}`)\n config.jobs?.tasks?.push(step)\n } else {\n configLogger.debug(`Task ${step.slug} already registered, skipping`)\n }\n }\n\n // Initialize webhook endpoint\n initWebhookEndpoint(config, pluginOptions.webhookPrefix || 'webhook')\n\n // Set up onInit to register collection hooks and initialize features\n const incomingOnInit = config.onInit\n config.onInit = async (payload) => {\n configLogger.info(`onInit called - collections: ${Object.keys(payload.collections).length}`)\n\n // Execute any existing onInit functions first\n if (incomingOnInit) {\n configLogger.debug('Executing existing onInit function')\n await incomingOnInit(payload)\n }\n\n // Initialize the logger with the payload instance\n const logger = initializeLogger(payload)\n logger.info('Logger initialized with payload instance')\n\n // Log collection trigger configuration\n logger.info(`Plugin configuration: ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers, ${pluginOptions.steps?.length || 0} steps`)\n\n // Create workflow executor instance\n console.log('🚨 CREATING WORKFLOW EXECUTOR INSTANCE')\n const executor = new WorkflowExecutor(payload, logger)\n console.log('🚨 EXECUTOR CREATED:', typeof executor)\n console.log('🚨 EXECUTOR METHODS:', Object.getOwnPropertyNames(Object.getPrototypeOf(executor)))\n\n // Register executor with proper dependency injection\n setWorkflowExecutor(executor, logger)\n\n // Hooks are now registered during config phase - just log status\n logger.info('Hooks were registered during config phase - executor now available')\n\n logger.info('Initializing global hooks...')\n initGlobalHooks(payload, logger, executor)\n\n logger.info('Initializing workflow hooks...')\n initWorkflowHooks(payload, logger)\n\n logger.info('Initializing step tasks...')\n initStepTasks(pluginOptions, payload, logger)\n\n // Register cron jobs for workflows with cron triggers\n logger.info('Registering cron jobs...')\n await registerCronJobs(payload, logger)\n\n logger.info('Plugin initialized successfully - all hooks registered')\n }\n\n return config\n }\n"],"names":["createWorkflowCollection","WorkflowRunsCollection","WorkflowExecutor","generateCronTasks","registerCronJobs","initGlobalHooks","initStepTasks","initWebhookEndpoint","initWorkflowHooks","getConfigLogger","initializeLogger","getLogger","executorRegistry","executor","isInitialized","logger","setWorkflowExecutor","info","getExecutorRegistry","createFailedWorkflowRun","args","errorMessage","req","payload","collection","slug","workflows","find","limit","where","equals","operation","workflow","docs","create","data","completedAt","Date","toISOString","context","steps","trigger","type","doc","previousDoc","triggeredAt","error","inputs","logs","level","message","timestamp","outputs","startedAt","status","triggeredBy","user","email","id","workflowVersion","length","workflowCount","warn","Error","applyCollectionsConfig","pluginOptions","config","collections","push","workflowsPlugin","enabled","collectionTriggers","triggerSlug","triggerConfig","Object","entries","collectionIndex","findIndex","c","debug","hooks","afterChange","automationHook","assign","payloadAutomationHook","registry","console","docId","hookType","undefined","String","updatedRegistry","executeTriggeredWorkflows","errorStack","stack","createError","__isAutomationHook","__version","jobs","tasks","configLogger","keys","step","task","webhookPrefix","incomingOnInit","onInit","log","getOwnPropertyNames","getPrototypeOf"],"mappings":"AAIA,SAAQA,wBAAwB,QAAO,6BAA4B;AACnE,SAAQC,sBAAsB,QAAO,iCAAgC;AACrE,SAAQC,gBAAgB,QAAO,+BAA8B;AAC7D,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I,CAAC;YACZX,cAAc2D,eAAe1C,SAASR;YAEtC,sDAAsD;YACtDA,OAAOE,IAAI,CAAC;YACZ,MAAMb,iBAAiBmB,SAASR;YAEhCA,OAAOE,IAAI,CAAC;QACd;QAEA,OAAOiD;IACT,EAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xtr-dev/payload-automation",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.34",
|
|
4
4
|
"description": "PayloadCMS Automation Plugin - Comprehensive workflow automation system with visual workflow building, execution tracking, and step types",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|