wwf
2025-05-20 938c3e5a587ce950a94964ea509b9e7f8834dfae
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
type IterationInfo = { iterationId: string; iterationIndex: number }
type LoopInfo = { loopId: string; loopIndex: number }
type NodePlain = { nodeType: 'plain'; nodeId: string; } & (Partial<IterationInfo> & Partial<LoopInfo>)
type NodeComplex = { nodeType: string; nodeId: string; params: (NodePlain | (NodeComplex & (Partial<IterationInfo> & Partial<LoopInfo>)) | Node[] | number)[] } & (Partial<IterationInfo> & Partial<LoopInfo>)
type Node = NodePlain | NodeComplex
 
/**
 * Parses a DSL string into an array of node objects.
 * @param dsl - The input DSL string.
 * @returns An array of parsed nodes.
 */
function parseDSL(dsl: string): NodeData[] {
  return convertToNodeData(parseTopLevelFlow(dsl).map(nodeStr => parseNode(nodeStr)))
}
 
/**
 * Splits a top-level flow string by "->", respecting nested structures.
 * @param dsl - The DSL string to split.
 * @returns An array of top-level segments.
 */
function parseTopLevelFlow(dsl: string): string[] {
  const segments: string[] = []
  let buffer = ''
  let nested = 0
 
  for (let i = 0; i < dsl.length; i++) {
    const char = dsl[i]
    if (char === '(') nested++
    if (char === ')') nested--
    if (char === '-' && dsl[i + 1] === '>' && nested === 0) {
      segments.push(buffer.trim())
      buffer = ''
      i++ // Skip the ">" character
    }
    else {
      buffer += char
    }
  }
  if (buffer.trim())
    segments.push(buffer.trim())
 
  return segments
}
 
/**
 * Parses a single node string.
 * If the node is complex (e.g., has parentheses), it extracts the node type, node ID, and parameters.
 * @param nodeStr - The node string to parse.
 * @param parentIterationId - The ID of the parent iteration node (if applicable).
 * @param parentLoopId - The ID of the parent loop node (if applicable).
 * @returns A parsed node object.
 */
function parseNode(nodeStr: string, parentIterationId?: string, parentLoopId?: string): Node {
  // Check if the node is a complex node
  if (nodeStr.startsWith('(') && nodeStr.endsWith(')')) {
    const innerContent = nodeStr.slice(1, -1).trim() // Remove outer parentheses
    let nested = 0
    let buffer = ''
    const parts: string[] = []
 
    // Split the inner content by commas, respecting nested parentheses
    for (let i = 0; i < innerContent.length; i++) {
      const char = innerContent[i]
      if (char === '(') nested++
      if (char === ')') nested--
 
      if (char === ',' && nested === 0) {
        parts.push(buffer.trim())
        buffer = ''
      }
      else {
        buffer += char
      }
    }
    parts.push(buffer.trim())
 
    // Extract nodeType, nodeId, and params
    const [nodeType, nodeId, ...paramsRaw] = parts
    const params = parseParams(paramsRaw, nodeType === 'iteration' ? nodeId.trim() : parentIterationId, nodeType === 'loop' ? nodeId.trim() : parentLoopId)
    const complexNode = {
      nodeType: nodeType.trim(),
      nodeId: nodeId.trim(),
      params,
    }
    if (parentIterationId) {
      (complexNode as any).iterationId = parentIterationId;
      (complexNode as any).iterationIndex = 0 // Fixed as 0
    }
    if (parentLoopId) {
      (complexNode as any).loopId = parentLoopId;
      (complexNode as any).loopIndex = 0 // Fixed as 0
    }
    return complexNode
  }
 
  // If it's not a complex node, treat it as a plain node
  const plainNode: NodePlain = { nodeType: 'plain', nodeId: nodeStr.trim() }
  if (parentIterationId) {
    plainNode.iterationId = parentIterationId
    plainNode.iterationIndex = 0 // Fixed as 0
  }
  if (parentLoopId) {
    plainNode.loopId = parentLoopId
    plainNode.loopIndex = 0 // Fixed as 0
  }
  return plainNode
}
 
/**
 * Parses parameters of a complex node.
 * Supports nested flows and complex sub-nodes.
 * Adds iteration-specific metadata recursively.
 * @param paramParts - The parameters string split by commas.
 * @param parentIterationId - The ID of the parent iteration node (if applicable).
 * @param parentLoopId - The ID of the parent loop node (if applicable).
 * @returns An array of parsed parameters (plain nodes, nested nodes, or flows).
 */
function parseParams(paramParts: string[], parentIteration?: string, parentLoopId?: string): (Node | Node[] | number)[] {
  return paramParts.map((part) => {
    if (part.includes('->')) {
      // Parse as a flow and return an array of nodes
      return parseTopLevelFlow(part).map(node => parseNode(node, parentIteration || undefined, parentLoopId || undefined))
    }
    else if (part.startsWith('(')) {
      // Parse as a nested complex node
      return parseNode(part, parentIteration || undefined, parentLoopId || undefined)
    }
    else if (!Number.isNaN(Number(part.trim()))) {
      // Parse as a numeric parameter
      return Number(part.trim())
    }
    else {
      // Parse as a plain node
      return parseNode(part, parentIteration || undefined, parentLoopId || undefined)
    }
  })
}
 
type NodeData = {
  id: string;
  node_id: string;
  title: string;
  node_type?: string;
  execution_metadata: Record<string, any>;
  status: string;
}
 
/**
 * Converts a plain node to node data.
 */
function convertPlainNode(node: Node): NodeData[] {
  return [
    {
      id: node.nodeId,
      node_id: node.nodeId,
      title: node.nodeId,
      execution_metadata: {},
      status: 'succeeded',
    },
  ]
}
 
/**
 * Converts a retry node to node data.
 */
function convertRetryNode(node: Node): NodeData[] {
  const { nodeId, iterationId, iterationIndex, loopId, loopIndex, params } = node as NodeComplex
  const retryCount = params ? Number.parseInt(params[0] as unknown as string, 10) : 0
  const result: NodeData[] = [
    {
      id: nodeId,
      node_id: nodeId,
      title: nodeId,
      execution_metadata: {},
      status: 'succeeded',
    },
  ]
 
  for (let i = 0; i < retryCount; i++) {
    result.push({
      id: nodeId,
      node_id: nodeId,
      title: nodeId,
      execution_metadata: iterationId ? {
        iteration_id: iterationId,
        iteration_index: iterationIndex || 0,
      } : loopId ? {
        loop_id: loopId,
        loop_index: loopIndex || 0,
      } : {},
      status: 'retry',
    })
  }
 
  return result
}
 
/**
 * Converts an iteration node to node data.
 */
function convertIterationNode(node: Node): NodeData[] {
  const { nodeId, params } = node as NodeComplex
  const result: NodeData[] = [
    {
      id: nodeId,
      node_id: nodeId,
      title: nodeId,
      node_type: 'iteration',
      status: 'succeeded',
      execution_metadata: {},
    },
  ]
 
  params?.forEach((param: any) => {
    if (Array.isArray(param)) {
      param.forEach((childNode: Node) => {
        const childData = convertToNodeData([childNode])
        childData.forEach((data) => {
          data.execution_metadata = {
            ...data.execution_metadata,
            iteration_id: nodeId,
            iteration_index: 0,
          }
        })
        result.push(...childData)
      })
    }
  })
 
  return result
}
 
/**
 * Converts an loop node to node data.
 */
function convertLoopNode(node: Node): NodeData[] {
  const { nodeId, params } = node as NodeComplex
  const result: NodeData[] = [
    {
      id: nodeId,
      node_id: nodeId,
      title: nodeId,
      node_type: 'loop',
      status: 'succeeded',
      execution_metadata: {},
    },
  ]
 
  params?.forEach((param: any) => {
    if (Array.isArray(param)) {
      param.forEach((childNode: Node) => {
        const childData = convertToNodeData([childNode])
        childData.forEach((data) => {
          data.execution_metadata = {
            ...data.execution_metadata,
            loop_id: nodeId,
            loop_index: 0,
          }
        })
        result.push(...childData)
      })
    }
  })
 
  return result
}
 
/**
 * Converts a parallel node to node data.
 */
function convertParallelNode(node: Node, parentParallelId?: string, parentStartNodeId?: string): NodeData[] {
  const { nodeId, params } = node as NodeComplex
  const result: NodeData[] = [
    {
      id: nodeId,
      node_id: nodeId,
      title: nodeId,
      execution_metadata: {
        parallel_id: nodeId,
      },
      status: 'succeeded',
    },
  ]
 
  params?.forEach((param) => {
    if (Array.isArray(param)) {
      const startNodeId = param[0]?.nodeId
      param.forEach((childNode: Node) => {
        const childData = convertToNodeData([childNode])
        childData.forEach((data) => {
          data.execution_metadata = {
            ...data.execution_metadata,
            parallel_id: nodeId,
            parallel_start_node_id: startNodeId,
            ...(parentParallelId && {
              parent_parallel_id: parentParallelId,
              parent_parallel_start_node_id: parentStartNodeId,
            }),
          }
        })
        result.push(...childData)
      })
    }
    else if (param && typeof param === 'object') {
      const startNodeId = param.nodeId
      const childData = convertToNodeData([param])
      childData.forEach((data) => {
        data.execution_metadata = {
          ...data.execution_metadata,
          parallel_id: nodeId,
          parallel_start_node_id: startNodeId,
          ...(parentParallelId && {
            parent_parallel_id: parentParallelId,
            parent_parallel_start_node_id: parentStartNodeId,
          }),
        }
      })
      result.push(...childData)
    }
  })
 
  return result
}
 
/**
 * Main function to convert nodes to node data.
 */
function convertToNodeData(nodes: Node[], parentParallelId?: string, parentStartNodeId?: string): NodeData[] {
  const result: NodeData[] = []
 
  nodes.forEach((node) => {
    switch (node.nodeType) {
      case 'plain':
        result.push(...convertPlainNode(node))
        break
      case 'retry':
        result.push(...convertRetryNode(node))
        break
      case 'iteration':
        result.push(...convertIterationNode(node))
        break
      case 'loop':
        result.push(...convertLoopNode(node))
        break
      case 'parallel':
        result.push(...convertParallelNode(node, parentParallelId, parentStartNodeId))
        break
      default:
        throw new Error(`Unknown nodeType: ${node.nodeType}`)
    }
  })
 
  return result
}
 
export default parseDSL