|
| 1 | +import { createLogger } from '@/lib/logs/console-logger' |
| 2 | +import { useWorkflowRegistry } from '@/stores/workflows/registry/store' |
| 3 | +import { useSubBlockStore } from '@/stores/workflows/subblock/store' |
| 4 | +import { useWorkflowStore } from '@/stores/workflows/workflow/store' |
| 5 | +import { importWorkflowFromYaml } from '@/stores/workflows/yaml/importer' |
| 6 | +import type { EditorFormat } from './workflow-text-editor' |
| 7 | + |
| 8 | +const logger = createLogger('WorkflowApplier') |
| 9 | + |
| 10 | +export interface ApplyResult { |
| 11 | + success: boolean |
| 12 | + errors: string[] |
| 13 | + warnings: string[] |
| 14 | + appliedOperations: number |
| 15 | +} |
| 16 | + |
| 17 | +/** |
| 18 | + * Apply workflow changes by using the existing importer for YAML |
| 19 | + * or direct state replacement for JSON |
| 20 | + */ |
| 21 | +export async function applyWorkflowDiff( |
| 22 | + content: string, |
| 23 | + format: EditorFormat |
| 24 | +): Promise<ApplyResult> { |
| 25 | + try { |
| 26 | + const { activeWorkflowId } = useWorkflowRegistry.getState() |
| 27 | + |
| 28 | + if (!activeWorkflowId) { |
| 29 | + return { |
| 30 | + success: false, |
| 31 | + errors: ['No active workflow found'], |
| 32 | + warnings: [], |
| 33 | + appliedOperations: 0, |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + if (format === 'yaml') { |
| 38 | + // Use the existing YAML importer which handles ID mapping and complete state replacement |
| 39 | + const workflowActions = { |
| 40 | + addBlock: () => {}, // Not used in this path |
| 41 | + addEdge: () => {}, // Not used in this path |
| 42 | + applyAutoLayout: () => { |
| 43 | + // Trigger auto layout after import |
| 44 | + setTimeout(() => { |
| 45 | + window.dispatchEvent(new CustomEvent('trigger-auto-layout')) |
| 46 | + }, 100) |
| 47 | + }, |
| 48 | + setSubBlockValue: () => {}, // Not used in this path |
| 49 | + getExistingBlocks: () => useWorkflowStore.getState().blocks, |
| 50 | + } |
| 51 | + |
| 52 | + const result = await importWorkflowFromYaml(content, workflowActions) |
| 53 | + |
| 54 | + return { |
| 55 | + success: result.success, |
| 56 | + errors: result.errors, |
| 57 | + warnings: result.warnings, |
| 58 | + appliedOperations: result.success ? 1 : 0, // One complete import operation |
| 59 | + } |
| 60 | + } |
| 61 | + // Handle JSON format - complete state replacement |
| 62 | + let parsedData: any |
| 63 | + try { |
| 64 | + parsedData = JSON.parse(content) |
| 65 | + } catch (error) { |
| 66 | + return { |
| 67 | + success: false, |
| 68 | + errors: [`Invalid JSON: ${error instanceof Error ? error.message : 'Parse error'}`], |
| 69 | + warnings: [], |
| 70 | + appliedOperations: 0, |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + // Validate JSON structure |
| 75 | + if (!parsedData.state || !parsedData.state.blocks) { |
| 76 | + return { |
| 77 | + success: false, |
| 78 | + errors: ['Invalid JSON structure: missing state.blocks'], |
| 79 | + warnings: [], |
| 80 | + appliedOperations: 0, |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + // Extract workflow state and subblock values |
| 85 | + const newWorkflowState = { |
| 86 | + blocks: parsedData.state.blocks, |
| 87 | + edges: parsedData.state.edges || [], |
| 88 | + loops: parsedData.state.loops || {}, |
| 89 | + parallels: parsedData.state.parallels || {}, |
| 90 | + lastSaved: Date.now(), |
| 91 | + isDeployed: parsedData.state.isDeployed || false, |
| 92 | + deployedAt: parsedData.state.deployedAt, |
| 93 | + deploymentStatuses: parsedData.state.deploymentStatuses || {}, |
| 94 | + hasActiveSchedule: parsedData.state.hasActiveSchedule || false, |
| 95 | + hasActiveWebhook: parsedData.state.hasActiveWebhook || false, |
| 96 | + } |
| 97 | + |
| 98 | + // Update local workflow state |
| 99 | + useWorkflowStore.setState(newWorkflowState) |
| 100 | + |
| 101 | + // Update subblock values if provided |
| 102 | + if (parsedData.subBlockValues) { |
| 103 | + useSubBlockStore.setState((state: any) => ({ |
| 104 | + workflowValues: { |
| 105 | + ...state.workflowValues, |
| 106 | + [activeWorkflowId]: parsedData.subBlockValues, |
| 107 | + }, |
| 108 | + })) |
| 109 | + } |
| 110 | + |
| 111 | + // Update workflow metadata if provided |
| 112 | + if (parsedData.workflow) { |
| 113 | + const { updateWorkflow } = useWorkflowRegistry.getState() |
| 114 | + const metadata = parsedData.workflow |
| 115 | + |
| 116 | + updateWorkflow(activeWorkflowId, { |
| 117 | + name: metadata.name, |
| 118 | + description: metadata.description, |
| 119 | + color: metadata.color, |
| 120 | + }) |
| 121 | + } |
| 122 | + |
| 123 | + // Save to database |
| 124 | + try { |
| 125 | + const response = await fetch(`/api/workflows/${activeWorkflowId}/state`, { |
| 126 | + method: 'PUT', |
| 127 | + headers: { |
| 128 | + 'Content-Type': 'application/json', |
| 129 | + }, |
| 130 | + body: JSON.stringify(newWorkflowState), |
| 131 | + }) |
| 132 | + |
| 133 | + if (!response.ok) { |
| 134 | + const errorData = await response.json() |
| 135 | + logger.error('Failed to save workflow state:', errorData.error) |
| 136 | + return { |
| 137 | + success: false, |
| 138 | + errors: [`Database save failed: ${errorData.error || 'Unknown error'}`], |
| 139 | + warnings: [], |
| 140 | + appliedOperations: 0, |
| 141 | + } |
| 142 | + } |
| 143 | + } catch (error) { |
| 144 | + logger.error('Failed to save workflow state:', error) |
| 145 | + return { |
| 146 | + success: false, |
| 147 | + errors: [ |
| 148 | + `Failed to save workflow state: ${error instanceof Error ? error.message : 'Unknown error'}`, |
| 149 | + ], |
| 150 | + warnings: [], |
| 151 | + appliedOperations: 0, |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + // Trigger auto layout |
| 156 | + setTimeout(() => { |
| 157 | + window.dispatchEvent(new CustomEvent('trigger-auto-layout')) |
| 158 | + }, 100) |
| 159 | + |
| 160 | + return { |
| 161 | + success: true, |
| 162 | + errors: [], |
| 163 | + warnings: [], |
| 164 | + appliedOperations: 1, // One complete state replacement |
| 165 | + } |
| 166 | + } catch (error) { |
| 167 | + logger.error('Failed to apply workflow changes:', error) |
| 168 | + return { |
| 169 | + success: false, |
| 170 | + errors: [`Apply failed: ${error instanceof Error ? error.message : 'Unknown error'}`], |
| 171 | + warnings: [], |
| 172 | + appliedOperations: 0, |
| 173 | + } |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +/** |
| 178 | + * Preview what changes would be applied (simplified for the new approach) |
| 179 | + */ |
| 180 | +export function previewWorkflowDiff( |
| 181 | + content: string, |
| 182 | + format: EditorFormat |
| 183 | +): { |
| 184 | + summary: string |
| 185 | + operations: Array<{ |
| 186 | + type: string |
| 187 | + description: string |
| 188 | + }> |
| 189 | +} { |
| 190 | + try { |
| 191 | + if (format === 'yaml') { |
| 192 | + // For YAML, we would do a complete import |
| 193 | + return { |
| 194 | + summary: 'Complete workflow replacement from YAML', |
| 195 | + operations: [ |
| 196 | + { |
| 197 | + type: 'complete_replacement', |
| 198 | + description: 'Replace entire workflow with YAML content', |
| 199 | + }, |
| 200 | + ], |
| 201 | + } |
| 202 | + } |
| 203 | + // For JSON, we would do a complete state replacement |
| 204 | + let parsedData: any |
| 205 | + try { |
| 206 | + parsedData = JSON.parse(content) |
| 207 | + } catch (error) { |
| 208 | + return { |
| 209 | + summary: 'Invalid JSON format', |
| 210 | + operations: [], |
| 211 | + } |
| 212 | + } |
| 213 | + |
| 214 | + const operations = [] |
| 215 | + |
| 216 | + if (parsedData.state?.blocks) { |
| 217 | + const blockCount = Object.keys(parsedData.state.blocks).length |
| 218 | + operations.push({ |
| 219 | + type: 'replace_blocks', |
| 220 | + description: `Replace workflow with ${blockCount} blocks`, |
| 221 | + }) |
| 222 | + } |
| 223 | + |
| 224 | + if (parsedData.state?.edges) { |
| 225 | + const edgeCount = parsedData.state.edges.length |
| 226 | + operations.push({ |
| 227 | + type: 'replace_edges', |
| 228 | + description: `Replace connections with ${edgeCount} edges`, |
| 229 | + }) |
| 230 | + } |
| 231 | + |
| 232 | + if (parsedData.subBlockValues) { |
| 233 | + operations.push({ |
| 234 | + type: 'replace_values', |
| 235 | + description: 'Replace all input values', |
| 236 | + }) |
| 237 | + } |
| 238 | + |
| 239 | + if (parsedData.workflow) { |
| 240 | + operations.push({ |
| 241 | + type: 'update_metadata', |
| 242 | + description: 'Update workflow metadata', |
| 243 | + }) |
| 244 | + } |
| 245 | + |
| 246 | + return { |
| 247 | + summary: 'Complete workflow state replacement from JSON', |
| 248 | + operations, |
| 249 | + } |
| 250 | + } catch (error) { |
| 251 | + return { |
| 252 | + summary: 'Error analyzing changes', |
| 253 | + operations: [], |
| 254 | + } |
| 255 | + } |
| 256 | +} |
0 commit comments