File size: 1,974 Bytes
d9494a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { workflowActionSchema } from '@/workflow/schemas/workflow-action-schema';
import { workflowTriggerSchema } from '@/workflow/schemas/workflow-trigger-schema';
import { isDefined } from '@/utils';
import {
  type ValidatableWorkflow,
  type WorkflowValidationIssue,
} from '@/workflow/validation/types/workflow-validation.type';
import { type z } from 'zod';

const formatZodPath = (path: PropertyKey[]): string =>
  path.map((segment) => String(segment)).join('.');

const formatZodIssue = (issue: z.ZodIssue): string => {
  const path = formatZodPath(issue.path);
  const base = path.length > 0 ? `${path}: ${issue.message}` : issue.message;

  if (issue.code === 'invalid_type' && path.length > 0) {
    return `${base}. Ensure the field "${path}" exists at the correct nesting level in the step object (not inside "input").`;
  }

  return base;
};

const formatZodIssues = (zodError: z.ZodError): string[] =>
  zodError.issues.map(formatZodIssue);

export const validateWorkflowStepParams = ({
  trigger,
  steps,
}: ValidatableWorkflow): WorkflowValidationIssue[] => {
  const issues: WorkflowValidationIssue[] = [];

  if (isDefined(trigger)) {
    const triggerResult = workflowTriggerSchema.safeParse(trigger);

    if (!triggerResult.success) {
      for (const message of formatZodIssues(triggerResult.error)) {
        issues.push({
          severity: 'error',
          code: 'INVALID_TRIGGER_PARAMS',
          message: `Trigger configuration is invalid - ${message}`,
        });
      }
    }
  }

  for (const step of steps ?? []) {
    const stepResult = workflowActionSchema.safeParse(step);

    if (!stepResult.success) {
      for (const message of formatZodIssues(stepResult.error)) {
        issues.push({
          severity: 'error',
          code: 'INVALID_STEP_PARAMS',
          message: `Step "${step.name ?? step.id}" configuration is invalid - ${message}`,
          stepId: step.id,
        });
      }
    }
  }

  return issues;
};