export type WorkflowBlockExecutor = "core" | "pro"; export type WorkflowBlockNativeSupport = "supported" | "preflight-skip"; export type WorkflowBlockType = | "manual" | "event" | "if" | "switch" | "httpRequest" | "log" | "alertUser" | "doNothing" | "waitForInput" | "rowGet" | "rowCreate" | "rowUpdate" | "rowDelete" | "iterator" | "variable" | "email"; export type WorkflowBlockContract = { value: WorkflowBlockType; executor: WorkflowBlockExecutor; nativeSupport: WorkflowBlockNativeSupport; requiredInputs: readonly string[]; }; type WorkflowReferenceKind = "variables" | "credentials"; type WorkflowReferenceMap = Record>; export type WorkflowReferenceSummary = { variables: string[]; credentials: string[]; byBlock: { blockId: string; variables: string[]; credentials: string[]; }[]; }; export type WorkflowPreflightBlock = { id: string; type?: string; input?: unknown; conditionGroups?: readonly { index?: number; conditions?: readonly { variable?: unknown; value?: unknown; }[]; }[]; }; export type WorkflowNativeCapabilityBlock = WorkflowPreflightBlock & { type: string; isTrigger?: boolean; conditionsGroups?: WorkflowPreflightBlock["conditionGroups"]; toBlocks?: readonly { id: string; condition?: string | null; }[]; }; export type WorkflowPreflightWorkflow = { blocks: readonly WorkflowPreflightBlock[]; }; export type WorkflowRequiredInputIssue = { blockId: string; blockType: WorkflowBlockType; missingInputs: string[]; }; export type WorkflowPreflightInput = { workflow: WorkflowPreflightWorkflow; variables: readonly string[]; credentials: readonly string[]; }; export type WorkflowPreflightResult = { missingVariables: string[]; missingCredentials: string[]; missingRequiredInputs: WorkflowRequiredInputIssue[]; }; export const NATIVE_WORKFLOW_TRIGGER_SUPPORTED_BLOCK_TYPES = [ "manual", "event", "if", "switch", "httpRequest", "log", "alertUser", "doNothing", "rowGet", "iterator", "variable", "email", ] as const satisfies readonly WorkflowBlockType[]; export const workflowBlockContracts = [ { value: "manual", executor: "core", nativeSupport: "supported", requiredInputs: [] }, { value: "event", executor: "core", nativeSupport: "supported", requiredInputs: ["event"] }, { value: "if", executor: "core", nativeSupport: "supported", requiredInputs: [] }, { value: "switch", executor: "core", nativeSupport: "supported", requiredInputs: [] }, { value: "httpRequest", executor: "core", nativeSupport: "supported", requiredInputs: ["url", "method"] }, { value: "log", executor: "core", nativeSupport: "supported", requiredInputs: ["message"] }, { value: "alertUser", executor: "core", nativeSupport: "supported", requiredInputs: ["message"] }, { value: "doNothing", executor: "core", nativeSupport: "supported", requiredInputs: [] }, { value: "waitForInput", executor: "pro", nativeSupport: "preflight-skip", requiredInputs: [] }, { value: "rowGet", executor: "pro", nativeSupport: "supported", requiredInputs: ["entity", "id"] }, { value: "rowCreate", executor: "pro", nativeSupport: "preflight-skip", requiredInputs: ["entity", "row"] }, { value: "rowUpdate", executor: "pro", nativeSupport: "preflight-skip", requiredInputs: ["entity", "id", "data"] }, { value: "rowDelete", executor: "pro", nativeSupport: "preflight-skip", requiredInputs: ["entity", "id"] }, { value: "iterator", executor: "core", nativeSupport: "supported", requiredInputs: ["variableName"] }, { value: "variable", executor: "core", nativeSupport: "supported", requiredInputs: ["variableName", "value"] }, { value: "email", executor: "pro", nativeSupport: "supported", requiredInputs: ["provider", "to", "subject", "body"] }, ] as const satisfies readonly WorkflowBlockContract[]; export const CORE_WORKFLOW_BLOCK_TYPES = workflowBlockContracts.filter((contract) => contract.executor === "core").map((contract) => contract.value); export const PRO_WORKFLOW_BLOCK_TYPES = workflowBlockContracts.filter((contract) => contract.executor === "pro").map((contract) => contract.value); export function getWorkflowBlockContract(value: WorkflowBlockType): WorkflowBlockContract { const contract = workflowBlockContracts.find((candidate) => candidate.value === value); if (!contract) { throw new Error(`Unknown workflow block contract: ${value}`); } return contract; } const WORKFLOW_DIRECT_REFERENCE_REGEX = /{{{?\s*\$(vars|credentials)\.([a-zA-Z0-9_-]+)\s*}}}?/g; const WORKFLOW_LOOKUP_REFERENCE_REGEX = /{{{?\s*lookup\s+\$(vars|credentials)\s+["']([a-zA-Z0-9_-]+)["']\s*}}}?/g; const WORKFLOW_WITH_BLOCK_REGEX = /{{#with\s+\$(vars|credentials)\s*}}([\s\S]*?){{\/with}}/g; const WORKFLOW_WITH_REFERENCE_REGEX = /{{{?\s*([a-zA-Z0-9_-]+)\s*}}}?/g; function createReferenceMap(): WorkflowReferenceMap { return { variables: new Set(), credentials: new Set(), }; } function addReference(target: WorkflowReferenceMap, type: string, name: string) { if (type === "vars") { target.variables.add(name); } else if (type === "credentials") { target.credentials.add(name); } } function scanString(target: WorkflowReferenceMap, value: string) { for (const match of value.matchAll(WORKFLOW_DIRECT_REFERENCE_REGEX)) { addReference(target, match[1], match[2]); } for (const match of value.matchAll(WORKFLOW_LOOKUP_REFERENCE_REGEX)) { addReference(target, match[1], match[2]); } for (const withMatch of value.matchAll(WORKFLOW_WITH_BLOCK_REGEX)) { const type = withMatch[1]; const body = withMatch[2] ?? ""; for (const referenceMatch of body.matchAll(WORKFLOW_WITH_REFERENCE_REGEX)) { addReference(target, type, referenceMatch[1]); } } } function scanValue(target: WorkflowReferenceMap, value: unknown) { if (typeof value === "string") { scanString(target, value); return; } if (Array.isArray(value)) { value.forEach((item) => scanValue(target, item)); return; } if (value && typeof value === "object") { Object.values(value).forEach((item) => scanValue(target, item)); } } function toSortedArray(values: Set) { return Array.from(values).sort((a, b) => a.localeCompare(b)); } function getLocalVariableNames(blocks: readonly WorkflowPreflightBlock[]) { return new Set( blocks .filter((block) => block.type === "variable") .map((block) => (isRecord(block.input) ? block.input.variableName : undefined)) .filter((value): value is string => typeof value === "string" && value.length > 0) ); } function isRecord(value: unknown): value is Record { return Boolean(value) && typeof value === "object" && !Array.isArray(value); } function extractBlockReferences(block: WorkflowPreflightBlock): WorkflowReferenceMap { const references = createReferenceMap(); scanValue(references, block.input); block.conditionGroups?.forEach((group) => { group.conditions?.forEach((condition) => { scanValue(references, condition.variable); scanValue(references, condition.value); }); }); return references; } function isWorkflowBlockType(value: string | undefined): value is WorkflowBlockType { return workflowBlockContracts.some((contract) => contract.value === value); } function hasRequiredInputValue(value: unknown) { if (typeof value === "string") { return value.trim().length > 0; } return value !== undefined && value !== null; } export function extractWorkflowReferences(workflow: WorkflowPreflightWorkflow): WorkflowReferenceSummary { const references = createReferenceMap(); const localVariables = getLocalVariableNames(workflow.blocks); const byBlock = workflow.blocks.map((block) => { const blockReferences = extractBlockReferences(block); localVariables.forEach((name) => blockReferences.variables.delete(name)); blockReferences.variables.forEach((name) => references.variables.add(name)); blockReferences.credentials.forEach((name) => references.credentials.add(name)); return { blockId: block.id, variables: toSortedArray(blockReferences.variables), credentials: toSortedArray(blockReferences.credentials), }; }); return { variables: toSortedArray(references.variables), credentials: toSortedArray(references.credentials), byBlock, }; } export function getMissingWorkflowReferences({ workflow, variables, credentials, }: { workflow: WorkflowPreflightWorkflow; variables: readonly string[]; credentials: readonly string[]; }) { const references = extractWorkflowReferences(workflow); const availableVariables = new Set(variables); const availableCredentials = new Set(credentials); return { missingVariables: references.variables.filter((name) => !availableVariables.has(name)), missingCredentials: references.credentials.filter((name) => !availableCredentials.has(name)), }; } export function validateWorkflowRequiredInputs(workflow: WorkflowPreflightWorkflow): WorkflowRequiredInputIssue[] { return workflow.blocks.flatMap((block) => { if (!isWorkflowBlockType(block.type)) { return []; } const input = isRecord(block.input) ? block.input : {}; const missingInputs = getWorkflowBlockContract(block.type).requiredInputs.filter((name) => !hasRequiredInputValue(input[name])); if (missingInputs.length === 0) { return []; } return [{ blockId: block.id, blockType: block.type, missingInputs }]; }); } export function preflightWorkflow({ workflow, variables, credentials }: WorkflowPreflightInput): WorkflowPreflightResult { return { ...getMissingWorkflowReferences({ workflow, variables, credentials }), missingRequiredInputs: validateWorkflowRequiredInputs(workflow), }; } function parseNativeCapabilityBlockInput(input: unknown): unknown { if (typeof input !== "string") { return input; } try { const parsed = JSON.parse(input); if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { return parsed; } } catch { // Invalid persisted input is handled by block-specific validation. } return {}; } function getNativeCapabilityConditionGroups(block: WorkflowNativeCapabilityBlock): WorkflowPreflightBlock["conditionGroups"] { return block.conditionGroups ?? block.conditionsGroups; } export function getNativeWorkflowTriggerCapabilityErrors(blocks: ReadonlyArray): string[] { const errors: string[] = []; if (!blocks.some((block) => block.isTrigger === true)) { errors.push("missing trigger block"); } for (const block of blocks) { if (!NATIVE_WORKFLOW_TRIGGER_SUPPORTED_BLOCK_TYPES.includes(block.type as (typeof NATIVE_WORKFLOW_TRIGGER_SUPPORTED_BLOCK_TYPES)[number])) { errors.push(`unsupported block type "${block.type}" on block ${block.id}`); } const credentialReferences = extractWorkflowReferences({ blocks: [ { id: block.id, type: block.type, input: parseNativeCapabilityBlockInput(block.input), conditionGroups: getNativeCapabilityConditionGroups(block), }, ], }).byBlock[0]?.credentials ?? []; for (const credentialName of credentialReferences) { errors.push(`unsupported credential reference "${credentialName}" on block ${block.id}`); } if (block.type === "if") { const conditionsGroups = getNativeCapabilityConditionGroups(block) ?? []; if (conditionsGroups.length !== 1) { errors.push(`if block ${block.id} must have exactly one condition group`); } else if ((conditionsGroups[0]?.conditions?.length ?? 0) === 0) { errors.push(`if block ${block.id} must have at least one condition`); } const edgeConditions = new Set((block.toBlocks ?? []).map((edge) => edge.condition)); if (!edgeConditions.has("true")) { errors.push(`if block ${block.id} is missing true edge`); } if (!edgeConditions.has("false")) { errors.push(`if block ${block.id} is missing false edge`); } } if (block.type === "switch") { const conditionsGroups = getNativeCapabilityConditionGroups(block) ?? []; const edgeConditions = new Set((block.toBlocks ?? []).map((edge) => edge.condition)); if (!edgeConditions.has("default")) { errors.push(`switch block ${block.id} is missing default edge`); } for (const conditionGroup of conditionsGroups) { if ((conditionGroup.conditions?.length ?? 0) === 0) { errors.push(`switch block ${block.id} condition group ${(conditionGroup.index ?? 0) + 1} must have at least one condition`); } const caseCondition = `case${(conditionGroup.index ?? 0) + 1}`; if (!edgeConditions.has(caseCondition)) { errors.push(`switch block ${block.id} is missing ${caseCondition} edge`); } } } for (const edge of block.toBlocks ?? []) { if (typeof edge.condition === "string" && edge.condition.trim().length > 0) { if (block.type === "if" && (edge.condition === "true" || edge.condition === "false")) { continue; } if (block.type === "switch" && (edge.condition === "default" || /^case\d+$/u.test(edge.condition))) { continue; } if (block.type === "iterator" && (edge.condition === "loopNext" || edge.condition === "loopEnd")) { continue; } errors.push(`unsupported conditional edge "${edge.id}" from block ${block.id}`); } } } return errors; }