snow-flow 1.2.3 → 1.3.0

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.
@@ -0,0 +1,677 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * Flow Structure Builder - ServiceNow Flow Record Utilities
5
+ * Converts flow JSON to proper ServiceNow records with correct sys_ids and logic chains
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.ACTION_TYPE_IDS = void 0;
9
+ exports.generateSysId = generateSysId;
10
+ exports.generateFlowComponents = generateFlowComponents;
11
+ exports.createActionInstances = createActionInstances;
12
+ exports.buildLogicChain = buildLogicChain;
13
+ exports.generateFlowXML = generateFlowXML;
14
+ exports.validateFlowComponents = validateFlowComponents;
15
+ exports.convertToFlowDefinition = convertToFlowDefinition;
16
+ exports.createTestFlowComponents = createTestFlowComponents;
17
+ exports.extractSysIds = extractSysIds;
18
+ exports.generateFlowUpdate = generateFlowUpdate;
19
+ const uuid_1 = require("uuid");
20
+ /**
21
+ * Known ServiceNow action type sys_ids for proper flow creation
22
+ */
23
+ exports.ACTION_TYPE_IDS = {
24
+ // Core Flow Actions
25
+ notification: '716281160b100300d97d8bf637673ac7',
26
+ approval: 'e3a61c920b200300d97d8bf637673a30',
27
+ script: '43c8cf0e0b200300d97d8bf637673ab4',
28
+ condition: 'a6e0f8890b200300d97d8bf637673a4a',
29
+ create_record: '7b8cf0e20b200300d97d8bf637673a50',
30
+ update_record: '8c9d0f230b200300d97d8bf637673a60',
31
+ ask_for_approval: 'e3a61c920b200300d97d8bf637673a30',
32
+ send_email: '716281160b100300d97d8bf637673ac7',
33
+ // Integration Actions
34
+ rest_step: 'f4b5c6d70b200300d97d8bf637673a80',
35
+ web_service: 'a5b6c7d80b200300d97d8bf637673a90',
36
+ // Utility Actions
37
+ wait: '9e0f1a2b0b200300d97d8bf637673aa0',
38
+ log: '0f1a2b3c0b200300d97d8bf637673ab0',
39
+ set_variable: '1a2b3c4d0b200300d97d8bf637673ac0',
40
+ // Default fallback
41
+ default: '43c8cf0e0b200300d97d8bf637673ab4' // script action
42
+ };
43
+ /**
44
+ * Generate a ServiceNow-compatible sys_id
45
+ */
46
+ function generateSysId() {
47
+ return (0, uuid_1.v4)().replace(/-/g, '');
48
+ }
49
+ /**
50
+ * Generate ServiceNow flow components from flow definition
51
+ * Converts flow JSON to proper ServiceNow records with all required components
52
+ */
53
+ function generateFlowComponents(flowDefinition, flowSysId) {
54
+ const flowId = flowSysId || generateSysId();
55
+ console.log('🏗️ Generating ServiceNow flow components...');
56
+ console.log(`📋 Flow: ${flowDefinition.name}`);
57
+ console.log(`🆔 Flow sys_id: ${flowId}`);
58
+ // 1. Create main flow record
59
+ const flowRecord = {
60
+ sys_id: flowId,
61
+ name: flowDefinition.name,
62
+ description: flowDefinition.description,
63
+ internal_name: sanitizeInternalName(flowDefinition.name),
64
+ type: 'flow',
65
+ status: 'published',
66
+ active: true,
67
+ run_as: 'system',
68
+ sys_class_name: 'sys_hub_flow',
69
+ table: flowDefinition.table,
70
+ category: 'custom',
71
+ flow_definition: JSON.stringify({
72
+ name: flowDefinition.name,
73
+ description: flowDefinition.description,
74
+ trigger: flowDefinition.trigger,
75
+ activities: flowDefinition.activities,
76
+ variables: flowDefinition.variables,
77
+ connections: flowDefinition.connections
78
+ })
79
+ };
80
+ // 2. Create trigger instance
81
+ const triggerInstance = createTriggerInstance(flowId, flowDefinition.trigger);
82
+ // 3. Create action instances for each activity
83
+ const actionInstances = createActionInstances(flowDefinition.activities, flowId);
84
+ // 4. Build logic chain (connections between components)
85
+ const logicChain = buildLogicChain(flowDefinition.activities, triggerInstance, actionInstances);
86
+ // 5. Create flow variables
87
+ const variables = createFlowVariables(flowDefinition.variables, flowId);
88
+ // 6. Create connections for visual flow representation
89
+ const connections = createFlowConnections(flowDefinition.connections, logicChain);
90
+ console.log(`✅ Generated components:`);
91
+ console.log(` • Flow record: ${flowRecord.sys_id}`);
92
+ console.log(` • Trigger: ${triggerInstance.sys_id}`);
93
+ console.log(` • Actions: ${actionInstances.length}`);
94
+ console.log(` • Logic chain: ${logicChain.length} entries`);
95
+ console.log(` • Variables: ${variables.length}`);
96
+ console.log(` • Connections: ${connections.length}`);
97
+ return {
98
+ flowRecord,
99
+ triggerInstance,
100
+ actionInstances,
101
+ logicChain,
102
+ variables,
103
+ connections
104
+ };
105
+ }
106
+ /**
107
+ * Create trigger instance record
108
+ */
109
+ function createTriggerInstance(flowId, trigger) {
110
+ const triggerSysId = generateSysId();
111
+ return {
112
+ sys_id: triggerSysId,
113
+ flow: flowId,
114
+ name: `${trigger.type}_trigger`,
115
+ type: trigger.type,
116
+ table: trigger.table,
117
+ condition: trigger.condition || '',
118
+ active: true,
119
+ order: 0,
120
+ sys_class_name: 'sys_hub_trigger_instance',
121
+ // Additional fields for proper trigger configuration
122
+ trigger_type: trigger.type,
123
+ trigger_table: trigger.table,
124
+ filter: trigger.condition || '',
125
+ when: getTriggerWhen(trigger.type)
126
+ };
127
+ }
128
+ /**
129
+ * Create action instances for all activities
130
+ */
131
+ function createActionInstances(activities, flowSysId) {
132
+ console.log(`🔧 Creating ${activities.length} action instances...`);
133
+ return activities.map((activity, index) => {
134
+ const actionSysId = generateSysId();
135
+ const actionTypeId = getActionTypeId(activity.type);
136
+ console.log(` • ${activity.name} (${activity.type}) → ${actionSysId}`);
137
+ return {
138
+ sys_id: actionSysId,
139
+ flow: flowSysId,
140
+ name: activity.name,
141
+ label: activity.name,
142
+ action_type: actionTypeId,
143
+ order: (index + 1) * 100, // ServiceNow uses 100-based ordering
144
+ active: true,
145
+ sys_class_name: 'sys_hub_action_instance',
146
+ // Activity-specific configuration
147
+ inputs: JSON.stringify(activity.inputs || {}),
148
+ outputs: JSON.stringify(activity.outputs || {}),
149
+ condition: activity.condition || '',
150
+ // Reference fields
151
+ artifact_reference: activity.artifact_reference || '',
152
+ subflow_reference: activity.subflow_reference || '',
153
+ // Position for Flow Designer visual representation
154
+ x: 100 + (index * 200), // Horizontal spacing
155
+ y: 200, // Vertical position
156
+ // Additional ServiceNow fields
157
+ description: `${activity.type} action: ${activity.name}`,
158
+ configuration: JSON.stringify(buildActionConfiguration(activity))
159
+ };
160
+ });
161
+ }
162
+ /**
163
+ * Build logic chain connecting trigger → actions → end
164
+ * Creates sys_hub_flow_logic records for proper flow execution
165
+ */
166
+ function buildLogicChain(activities, triggerInstance, actionInstances) {
167
+ console.log('🔗 Building logic chain...');
168
+ const logicChain = [];
169
+ // 1. Connect trigger to first action (or end if no actions)
170
+ if (actionInstances.length > 0) {
171
+ logicChain.push(createLogicEntry(triggerInstance.sys_id, actionInstances[0].sys_id, triggerInstance.flow, 'trigger_to_first_action', 0));
172
+ console.log(` • Trigger → ${actionInstances[0].name}`);
173
+ }
174
+ else {
175
+ // Direct trigger to end
176
+ logicChain.push(createLogicEntry(triggerInstance.sys_id, 'END', triggerInstance.flow, 'trigger_to_end', 0));
177
+ console.log(` • Trigger → END (no actions)`);
178
+ }
179
+ // 2. Connect actions in sequence
180
+ for (let i = 0; i < actionInstances.length - 1; i++) {
181
+ const currentAction = actionInstances[i];
182
+ const nextAction = actionInstances[i + 1];
183
+ logicChain.push(createLogicEntry(currentAction.sys_id, nextAction.sys_id, triggerInstance.flow, `action_${i}_to_action_${i + 1}`, i + 1));
184
+ console.log(` • ${currentAction.name} → ${nextAction.name}`);
185
+ }
186
+ // 3. Connect last action to end
187
+ if (actionInstances.length > 0) {
188
+ const lastAction = actionInstances[actionInstances.length - 1];
189
+ logicChain.push(createLogicEntry(lastAction.sys_id, 'END', triggerInstance.flow, 'last_action_to_end', actionInstances.length));
190
+ console.log(` • ${lastAction.name} → END`);
191
+ }
192
+ console.log(`✅ Built logic chain with ${logicChain.length} connections`);
193
+ return logicChain;
194
+ }
195
+ /**
196
+ * Create a single logic entry (sys_hub_flow_logic record)
197
+ */
198
+ function createLogicEntry(fromSysId, toSysId, flowId, name, order) {
199
+ return {
200
+ sys_id: generateSysId(),
201
+ flow: flowId,
202
+ name: name,
203
+ from_element: fromSysId,
204
+ to_element: toSysId === 'END' ? '' : toSysId,
205
+ order: order * 100,
206
+ active: true,
207
+ sys_class_name: 'sys_hub_flow_logic',
208
+ // Visual positioning for Flow Designer
209
+ from_x: 100 + (order * 200),
210
+ from_y: 200,
211
+ to_x: toSysId === 'END' ? 100 + ((order + 1) * 200) : 100 + ((order + 1) * 200),
212
+ to_y: 200,
213
+ // Connection properties
214
+ condition: '',
215
+ label: '',
216
+ connection_type: 'sequence'
217
+ };
218
+ }
219
+ /**
220
+ * Create flow variables from variable definitions
221
+ */
222
+ function createFlowVariables(variables, flowId) {
223
+ return variables.map((variable, index) => ({
224
+ sys_id: generateSysId(),
225
+ flow: flowId,
226
+ name: variable.name || variable.id,
227
+ label: variable.label || variable.name || variable.id,
228
+ type: variable.type || 'string',
229
+ input: variable.input || false,
230
+ output: variable.output || false,
231
+ default_value: variable.default_value || '',
232
+ description: variable.description || '',
233
+ order: index * 100,
234
+ sys_class_name: 'sys_hub_flow_variable'
235
+ }));
236
+ }
237
+ /**
238
+ * Create visual connections for Flow Designer
239
+ */
240
+ function createFlowConnections(connections, logicChain) {
241
+ // The logic chain already handles the actual execution flow
242
+ // This creates additional visual connections if specified
243
+ return connections.map((connection, index) => ({
244
+ sys_id: generateSysId(),
245
+ name: connection.name || `connection_${index}`,
246
+ from: connection.from,
247
+ to: connection.to,
248
+ condition: connection.condition || 'always',
249
+ label: connection.label || '',
250
+ sys_class_name: 'sys_hub_flow_connection'
251
+ }));
252
+ }
253
+ /**
254
+ * Get the correct action type sys_id for an activity type
255
+ */
256
+ function getActionTypeId(activityType) {
257
+ const normalizedType = activityType.toLowerCase().replace(/[^a-z_]/g, '_');
258
+ // Direct mapping
259
+ if (exports.ACTION_TYPE_IDS[normalizedType]) {
260
+ return exports.ACTION_TYPE_IDS[normalizedType];
261
+ }
262
+ // Fuzzy matching for common variations
263
+ if (normalizedType.includes('email') || normalizedType.includes('mail')) {
264
+ return exports.ACTION_TYPE_IDS.notification;
265
+ }
266
+ if (normalizedType.includes('approval') || normalizedType.includes('approve')) {
267
+ return exports.ACTION_TYPE_IDS.approval;
268
+ }
269
+ if (normalizedType.includes('script') || normalizedType.includes('code')) {
270
+ return exports.ACTION_TYPE_IDS.script;
271
+ }
272
+ if (normalizedType.includes('condition') || normalizedType.includes('if')) {
273
+ return exports.ACTION_TYPE_IDS.condition;
274
+ }
275
+ if (normalizedType.includes('create') && normalizedType.includes('record')) {
276
+ return exports.ACTION_TYPE_IDS.create_record;
277
+ }
278
+ if (normalizedType.includes('update') && normalizedType.includes('record')) {
279
+ return exports.ACTION_TYPE_IDS.update_record;
280
+ }
281
+ if (normalizedType.includes('rest') || normalizedType.includes('api')) {
282
+ return exports.ACTION_TYPE_IDS.rest_step;
283
+ }
284
+ if (normalizedType.includes('wait') || normalizedType.includes('delay')) {
285
+ return exports.ACTION_TYPE_IDS.wait;
286
+ }
287
+ if (normalizedType.includes('log')) {
288
+ return exports.ACTION_TYPE_IDS.log;
289
+ }
290
+ // Default to script action
291
+ console.warn(`⚠️ Unknown action type "${activityType}", using script action as fallback`);
292
+ return exports.ACTION_TYPE_IDS.default;
293
+ }
294
+ /**
295
+ * Get trigger when condition based on trigger type
296
+ */
297
+ function getTriggerWhen(triggerType) {
298
+ switch (triggerType.toLowerCase()) {
299
+ case 'record_created':
300
+ case 'created':
301
+ return 'after';
302
+ case 'record_updated':
303
+ case 'updated':
304
+ return 'after';
305
+ case 'record_deleted':
306
+ case 'deleted':
307
+ return 'after';
308
+ case 'before_insert':
309
+ return 'before';
310
+ case 'before_update':
311
+ return 'before';
312
+ case 'before_delete':
313
+ return 'before';
314
+ case 'scheduled':
315
+ return 'scheduled';
316
+ case 'manual':
317
+ default:
318
+ return 'manual';
319
+ }
320
+ }
321
+ /**
322
+ * Build action-specific configuration
323
+ */
324
+ function buildActionConfiguration(activity) {
325
+ const config = {
326
+ action_type: activity.type,
327
+ name: activity.name
328
+ };
329
+ // Add type-specific configuration
330
+ switch (activity.type.toLowerCase()) {
331
+ case 'notification':
332
+ case 'send_email':
333
+ config.recipient = activity.inputs?.recipient || '';
334
+ config.subject = activity.inputs?.subject || '';
335
+ config.message = activity.inputs?.message || activity.inputs?.body || '';
336
+ break;
337
+ case 'approval':
338
+ case 'ask_for_approval':
339
+ config.approver = activity.inputs?.approver || '';
340
+ config.approval_message = activity.inputs?.message || '';
341
+ config.due_date = activity.inputs?.due_date || '';
342
+ break;
343
+ case 'script':
344
+ config.script = activity.inputs?.script || '';
345
+ break;
346
+ case 'condition':
347
+ config.condition = activity.condition || activity.inputs?.condition || '';
348
+ break;
349
+ case 'create_record':
350
+ config.table = activity.inputs?.table || '';
351
+ config.fields = activity.inputs?.fields || {};
352
+ break;
353
+ case 'update_record':
354
+ config.table = activity.inputs?.table || '';
355
+ config.sys_id = activity.inputs?.sys_id || '';
356
+ config.fields = activity.inputs?.fields || {};
357
+ break;
358
+ default:
359
+ // Include all inputs as configuration
360
+ config.inputs = activity.inputs || {};
361
+ }
362
+ return config;
363
+ }
364
+ /**
365
+ * Sanitize flow name for ServiceNow internal_name field
366
+ */
367
+ function sanitizeInternalName(name) {
368
+ return name
369
+ .toLowerCase()
370
+ .replace(/[^a-z0-9_\s]/g, '') // Remove special characters except underscores and spaces
371
+ .replace(/\s+/g, '_') // Replace spaces with underscores
372
+ .replace(/_+/g, '_') // Replace multiple underscores with single
373
+ .replace(/^_|_$/g, '') // Remove leading/trailing underscores
374
+ .substring(0, 80); // Limit length to 80 characters
375
+ }
376
+ /**
377
+ * Convert flow definition to ServiceNow Update XML format
378
+ * Enhanced with modern flow structure support and better validation
379
+ */
380
+ function generateFlowXML(components, options = {}) {
381
+ const { includeMetadata = true, validateBeforeExport = true, compactFormat = false } = options;
382
+ // Validate components before generating XML
383
+ if (validateBeforeExport) {
384
+ const validation = validateFlowComponents(components);
385
+ if (!validation.isValid) {
386
+ throw new Error(`Flow validation failed: ${validation.errors.join(', ')}`);
387
+ }
388
+ }
389
+ const xml = [];
390
+ const indent = compactFormat ? '' : ' ';
391
+ const newline = compactFormat ? '' : '\n';
392
+ xml.push('<?xml version="1.0" encoding="UTF-8"?>');
393
+ // Add metadata if requested
394
+ if (includeMetadata) {
395
+ xml.push(`<!-- Generated by Snow-Flow at ${new Date().toISOString()} -->`);
396
+ xml.push(`<!-- Flow: ${components.flowRecord.name || 'Unknown'} -->`);
397
+ xml.push(`<!-- Actions: ${components.actionInstances.length} -->`);
398
+ xml.push(`<!-- Variables: ${components.variables.length} -->`);
399
+ }
400
+ xml.push('<unload unload_date="' + new Date().toISOString() + '">');
401
+ // Flow record with enhanced fields
402
+ xml.push(`${indent}<sys_hub_flow action="INSERT_OR_UPDATE">`);
403
+ Object.entries(components.flowRecord).forEach(([key, value]) => {
404
+ // Ensure critical fields are properly set
405
+ let processedValue = value;
406
+ if (key === 'active' && typeof value !== 'boolean') {
407
+ processedValue = value === 'true' || value === true;
408
+ }
409
+ if (key === 'validated' && typeof value !== 'boolean') {
410
+ processedValue = value === 'true' || value === true;
411
+ }
412
+ xml.push(`${indent}${indent}<${key}>${escapeXML(String(processedValue))}</${key}>`);
413
+ });
414
+ xml.push(`${indent}</sys_hub_flow>`);
415
+ // Enhanced trigger instance with validation
416
+ if (components.triggerInstance && Object.keys(components.triggerInstance).length > 0) {
417
+ xml.push(`${indent}<sys_hub_trigger_instance action="INSERT_OR_UPDATE">`);
418
+ Object.entries(components.triggerInstance).forEach(([key, value]) => {
419
+ xml.push(`${indent}${indent}<${key}>${escapeXML(String(value))}</${key}>`);
420
+ });
421
+ xml.push(`${indent}</sys_hub_trigger_instance>`);
422
+ }
423
+ // Action instances with proper ordering
424
+ components.actionInstances
425
+ .sort((a, b) => (a.order || 0) - (b.order || 0)) // Ensure proper order
426
+ .forEach(action => {
427
+ xml.push(`${indent}<sys_hub_action_instance action="INSERT_OR_UPDATE">`);
428
+ Object.entries(action).forEach(([key, value]) => {
429
+ xml.push(`${indent}${indent}<${key}>${escapeXML(String(value))}</${key}>`);
430
+ });
431
+ xml.push(`${indent}</sys_hub_action_instance>`);
432
+ });
433
+ // Logic chain with connection validation
434
+ components.logicChain
435
+ .sort((a, b) => (a.order || 0) - (b.order || 0)) // Ensure proper flow
436
+ .forEach(logic => {
437
+ xml.push(`${indent}<sys_hub_flow_logic action="INSERT_OR_UPDATE">`);
438
+ Object.entries(logic).forEach(([key, value]) => {
439
+ xml.push(`${indent}${indent}<${key}>${escapeXML(String(value))}</${key}>`);
440
+ });
441
+ xml.push(`${indent}</sys_hub_flow_logic>`);
442
+ });
443
+ // Variables with type validation
444
+ components.variables.forEach(variable => {
445
+ xml.push(`${indent}<sys_hub_flow_variable action="INSERT_OR_UPDATE">`);
446
+ Object.entries(variable).forEach(([key, value]) => {
447
+ xml.push(`${indent}${indent}<${key}>${escapeXML(String(value))}</${key}>`);
448
+ });
449
+ xml.push(`${indent}</sys_hub_flow_variable>`);
450
+ });
451
+ // Include connections if available (for modern flows)
452
+ if (components.connections && components.connections.length > 0) {
453
+ components.connections.forEach(connection => {
454
+ xml.push(`${indent}<sys_hub_flow_connection action="INSERT_OR_UPDATE">`);
455
+ Object.entries(connection).forEach(([key, value]) => {
456
+ xml.push(`${indent}${indent}<${key}>${escapeXML(String(value))}</${key}>`);
457
+ });
458
+ xml.push(`${indent}</sys_hub_flow_connection>`);
459
+ });
460
+ }
461
+ xml.push('</unload>');
462
+ return xml.join(newline + (compactFormat ? '' : newline));
463
+ }
464
+ /**
465
+ * Escape XML special characters
466
+ */
467
+ function escapeXML(text) {
468
+ return text
469
+ .replace(/&/g, '&amp;')
470
+ .replace(/</g, '&lt;')
471
+ .replace(/>/g, '&gt;')
472
+ .replace(/"/g, '&quot;')
473
+ .replace(/'/g, '&apos;');
474
+ }
475
+ /**
476
+ * Validate flow components before deployment
477
+ */
478
+ function validateFlowComponents(components) {
479
+ const errors = [];
480
+ const warnings = [];
481
+ // Validate flow record
482
+ if (!components.flowRecord.name) {
483
+ errors.push('Flow record missing required name field');
484
+ }
485
+ if (!components.flowRecord.sys_id) {
486
+ errors.push('Flow record missing sys_id');
487
+ }
488
+ // Validate trigger
489
+ if (!components.triggerInstance.sys_id) {
490
+ errors.push('Trigger instance missing sys_id');
491
+ }
492
+ if (!components.triggerInstance.flow) {
493
+ errors.push('Trigger instance not linked to flow');
494
+ }
495
+ // Validate actions
496
+ components.actionInstances.forEach((action, index) => {
497
+ if (!action.sys_id) {
498
+ errors.push(`Action ${index} missing sys_id`);
499
+ }
500
+ if (!action.flow) {
501
+ errors.push(`Action ${index} not linked to flow`);
502
+ }
503
+ if (!action.action_type) {
504
+ errors.push(`Action ${index} missing action_type`);
505
+ }
506
+ });
507
+ // Validate logic chain
508
+ if (components.logicChain.length === 0 && components.actionInstances.length > 0) {
509
+ warnings.push('No logic chain defined for flow with actions');
510
+ }
511
+ // Check for orphaned components
512
+ const flowId = components.flowRecord.sys_id;
513
+ const orphanedActions = components.actionInstances.filter(a => a.flow !== flowId);
514
+ if (orphanedActions.length > 0) {
515
+ errors.push(`${orphanedActions.length} actions not properly linked to flow`);
516
+ }
517
+ return {
518
+ isValid: errors.length === 0,
519
+ errors,
520
+ warnings
521
+ };
522
+ }
523
+ /**
524
+ * Convert legacy flow format to FlowDefinition
525
+ * Handles various input formats from existing flow creation systems
526
+ */
527
+ function convertToFlowDefinition(flow) {
528
+ // Extract activities from various possible sources
529
+ const activities = flow.activities || flow.actions || flow.steps || [];
530
+ // Normalize trigger format
531
+ const trigger = {
532
+ type: flow.trigger_type || flow.trigger?.type || 'manual',
533
+ table: flow.trigger?.table || flow.table || 'incident',
534
+ condition: flow.trigger?.condition || flow.condition || flow.trigger_condition || ''
535
+ };
536
+ // Normalize activities format
537
+ const normalizedActivities = activities.map((activity, index) => ({
538
+ id: activity.id || `activity_${index}`,
539
+ name: activity.name || activity.label || `Activity ${index + 1}`,
540
+ type: activity.type || activity.action_type || 'script',
541
+ inputs: activity.inputs || activity.config || {},
542
+ outputs: activity.outputs || {},
543
+ condition: activity.condition || '',
544
+ artifact_reference: activity.artifact_reference || activity.artifact,
545
+ subflow_reference: activity.subflow_reference || activity.subflow
546
+ }));
547
+ // Extract variables from various sources
548
+ let variables = flow.variables || [];
549
+ // Add inputs as variables
550
+ if (flow.inputs && Array.isArray(flow.inputs)) {
551
+ const inputVars = flow.inputs.map((input, index) => ({
552
+ id: input.id || input.name || `input_${index}`,
553
+ name: input.name || input.id || `input_${index}`,
554
+ type: input.type || 'string',
555
+ input: true,
556
+ output: false,
557
+ default_value: input.default_value || input.defaultValue || '',
558
+ description: input.description || ''
559
+ }));
560
+ variables = variables.concat(inputVars);
561
+ }
562
+ // Add outputs as variables
563
+ if (flow.outputs && Array.isArray(flow.outputs)) {
564
+ const outputVars = flow.outputs.map((output, index) => ({
565
+ id: output.id || output.name || `output_${index}`,
566
+ name: output.name || output.id || `output_${index}`,
567
+ type: output.type || 'string',
568
+ input: false,
569
+ output: true,
570
+ default_value: output.default_value || output.defaultValue || '',
571
+ description: output.description || ''
572
+ }));
573
+ variables = variables.concat(outputVars);
574
+ }
575
+ return {
576
+ name: flow.name || 'Untitled Flow',
577
+ description: flow.description || flow.name || 'Generated flow',
578
+ table: trigger.table,
579
+ trigger,
580
+ activities: normalizedActivities,
581
+ variables,
582
+ connections: flow.connections || [],
583
+ error_handling: flow.error_handling || []
584
+ };
585
+ }
586
+ /**
587
+ * Create flow components for testing/validation purposes
588
+ * Generates minimal valid flow structure for testing
589
+ */
590
+ function createTestFlowComponents(name = 'Test Flow') {
591
+ const testFlow = {
592
+ name,
593
+ description: `Test flow: ${name}`,
594
+ table: 'incident',
595
+ trigger: {
596
+ type: 'manual',
597
+ table: 'incident',
598
+ condition: ''
599
+ },
600
+ activities: [
601
+ {
602
+ id: 'log_action',
603
+ name: 'Log Message',
604
+ type: 'script',
605
+ inputs: {
606
+ script: `gs.info('Test flow ${name} executed successfully');`
607
+ },
608
+ outputs: {
609
+ result: 'string'
610
+ }
611
+ }
612
+ ],
613
+ variables: [
614
+ {
615
+ id: 'test_var',
616
+ name: 'Test Variable',
617
+ type: 'string',
618
+ input: true,
619
+ output: false,
620
+ default_value: 'test_value'
621
+ }
622
+ ],
623
+ connections: [],
624
+ error_handling: []
625
+ };
626
+ return generateFlowComponents(testFlow);
627
+ }
628
+ /**
629
+ * Utility to extract sys_ids from existing ServiceNow records for update operations
630
+ */
631
+ function extractSysIds(existingFlow) {
632
+ const sysIds = {};
633
+ if (existingFlow.sys_id) {
634
+ sysIds.flow = existingFlow.sys_id;
635
+ }
636
+ if (existingFlow.trigger_instance?.sys_id) {
637
+ sysIds.trigger = existingFlow.trigger_instance.sys_id;
638
+ }
639
+ if (existingFlow.action_instances && Array.isArray(existingFlow.action_instances)) {
640
+ existingFlow.action_instances.forEach((action, index) => {
641
+ if (action.sys_id) {
642
+ sysIds[`action_${index}`] = action.sys_id;
643
+ }
644
+ });
645
+ }
646
+ return sysIds;
647
+ }
648
+ /**
649
+ * Generate flow update payload for modifying existing flows
650
+ */
651
+ function generateFlowUpdate(flowDefinition, existingSysIds) {
652
+ const components = generateFlowComponents(flowDefinition, existingSysIds.flow);
653
+ // Replace generated sys_ids with existing ones where available
654
+ if (existingSysIds.trigger) {
655
+ components.triggerInstance.sys_id = existingSysIds.trigger;
656
+ }
657
+ components.actionInstances.forEach((action, index) => {
658
+ const existingId = existingSysIds[`action_${index}`];
659
+ if (existingId) {
660
+ action.sys_id = existingId;
661
+ }
662
+ });
663
+ return components;
664
+ }
665
+ exports.default = {
666
+ generateFlowComponents,
667
+ createActionInstances,
668
+ buildLogicChain,
669
+ generateSysId,
670
+ validateFlowComponents,
671
+ generateFlowXML,
672
+ convertToFlowDefinition,
673
+ createTestFlowComponents,
674
+ extractSysIds,
675
+ generateFlowUpdate,
676
+ ACTION_TYPE_IDS: exports.ACTION_TYPE_IDS
677
+ };