wasm4pm 26.6.25

High-performance process mining algorithms in WebAssembly for JavaScript/TypeScript
Documentation
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
/// BPMN 2.0 XML to POWL conversion.
///
/// Parses a BPMN 2.0 XML document and converts it to a POWL model string.
/// Handles both pm4wasm-generated BPMN (with `pm4py:connector`/`pm4py:silent`
/// markers) and generic BPMN from external tools (Camunda, bpmn.io, Signavio).
///
/// Mapping:
///
/// | BPMN element                                | POWL node              |
/// |---------------------------------------------|------------------------|
/// | `<task name="A"/>`                          | Transition("A")        |
/// | `<serviceTask pm4py:silent="true"/>`        | Transition(None) [tau] |
/// | `<exclusiveGateway>` (split/join pair)       | OperatorPowl(Xor)      |
/// | `<exclusiveGateway>` with back-arc           | OperatorPowl(Loop)     |
/// | `<parallelGateway>` (split/join pair)        | StrictPartialOrder     |
/// | Sequential chain of tasks                    | StrictPartialOrder(seq)|
#[cfg(feature = "powl")]
use crate::powl_arena::{Operator, PowlArena};
use roxmltree::Document;
use std::collections::{BTreeMap, HashSet};

// ─── BPMN element types ─────────────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq)]
enum BpmnNodeType {
    Task,
    SilentTask,
    ExclusiveGateway,
    ParallelGateway,
    InclusiveGateway,
    StartEvent,
    EndEvent,
    Connector, // pm4py:connector serviceTask (virtual node, skip)
    Other,
}

#[derive(Debug, Clone)]
struct BpmnNode {
    #[allow(dead_code)]
    id: String,
    name: String,
    node_type: BpmnNodeType,
}

// ─── XML parsing helpers ────────────────────────────────────────────────────

/// Classify a BPMN element by its local tag name and attributes.
fn classify_element<'a, 'input>(
    local_name: &str,
    node: roxmltree::Node<'a, 'input>,
) -> BpmnNodeType {
    match local_name {
        "startEvent" => BpmnNodeType::StartEvent,
        "endEvent" => BpmnNodeType::EndEvent,
        "task" => BpmnNodeType::Task,
        "userTask" | "serviceTask" | "sendTask" | "receiveTask" | "callActivity" | "scriptTask"
        | "businessRuleTask" => {
            let is_connector = attr_val(node, "pm4py:connector").as_deref() == Some("true");
            let is_silent = attr_val(node, "pm4py:silent").as_deref() == Some("true");
            if is_connector {
                BpmnNodeType::Connector
            } else if is_silent {
                BpmnNodeType::SilentTask
            } else {
                BpmnNodeType::Task
            }
        }
        "exclusiveGateway" => BpmnNodeType::ExclusiveGateway,
        "parallelGateway" => BpmnNodeType::ParallelGateway,
        "inclusiveGateway" => BpmnNodeType::InclusiveGateway,
        _ => BpmnNodeType::Other,
    }
}

/// Get an attribute value from an roxmltree Node, supporting namespace-prefixed
/// attributes (e.g., `pm4py:connector`). roxmltree stores prefixed attributes
/// as-is in the attribute name string.
fn attr_val<'a, 'input>(node: roxmltree::Node<'a, 'input>, key: &str) -> Option<String> {
    node.attribute(key).map(|s| s.to_string())
}

/// Type alias for the BPMN graph extraction result.
type BpmnGraphResult = Result<(BTreeMap<String, BpmnNode>, Vec<(String, String)>), String>;

/// Extract all BPMN elements and sequence flows from the XML.
fn extract_bpmn_graph(xml: &str) -> BpmnGraphResult {
    let mut nodes: BTreeMap<String, BpmnNode> = BTreeMap::new();
    let mut flows: Vec<(String, String)> = Vec::new();

    let doc = Document::parse(xml).map_err(|e| e.to_string())?;

    let bpmn_elements = [
        "task",
        "userTask",
        "serviceTask",
        "sendTask",
        "receiveTask",
        "callActivity",
        "scriptTask",
        "businessRuleTask",
        "startEvent",
        "endEvent",
        "exclusiveGateway",
        "parallelGateway",
        "inclusiveGateway",
    ];

    for node in doc.root().descendants() {
        if !node.is_element() {
            continue;
        }

        let tag = node.tag_name().name();

        if bpmn_elements.contains(&tag) {
            let id = node
                .attribute("id")
                .unwrap_or(&format!("unknown_{}", nodes.len()))
                .to_string();
            let name = node.attribute("name").unwrap_or("").to_string();
            let node_type = classify_element(tag, node);

            nodes.insert(
                id.clone(),
                BpmnNode {
                    id,
                    name,
                    node_type,
                },
            );
        } else if tag == "sequenceFlow" {
            if let (Some(src), Some(tgt)) =
                (node.attribute("sourceRef"), node.attribute("targetRef"))
            {
                flows.push((src.to_string(), tgt.to_string()));
            }
        }
    }

    Ok((nodes, flows))
}

// ─── Graph analysis ────────────────────────────────────────────────────────

/// Build a "shortcut" outgoing map that skips connector nodes.
/// This transparently resolves chains like: startEvent -> connector -> task
/// into direct edges: startEvent -> task.
fn build_shortcut_outgoing(
    flows: &[(String, String)],
    connector_ids: &HashSet<String>,
) -> BTreeMap<String, Vec<String>> {
    // Build raw adjacency
    let mut raw: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (src, tgt) in flows {
        raw.entry(src.clone()).or_default().push(tgt.clone());
    }

    // For each node, resolve through connector chains
    let mut resolved: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (src, targets) in &raw {
        let mut final_targets: Vec<String> = Vec::new();
        for tgt in targets {
            let end = resolve_through_connectors(tgt, &raw, connector_ids);
            if !final_targets.contains(&end) {
                final_targets.push(end);
            }
        }
        resolved.insert(src.clone(), final_targets);
    }
    resolved
}

/// Follow a chain of connector nodes to find the real target.
fn resolve_through_connectors(
    start: &str,
    raw: &BTreeMap<String, Vec<String>>,
    connector_ids: &HashSet<String>,
) -> String {
    let mut current = start.to_string();
    let mut visited = HashSet::new();
    while connector_ids.contains(&current) {
        if !visited.insert(current.clone()) {
            break; // Cycle guard
        }
        if let Some(nexts) = raw.get(&current) {
            if let Some(next) = nexts.first() {
                current = next.clone();
            } else {
                break;
            }
        } else {
            break;
        }
    }
    current
}

// ─── POWL construction ─────────────────────────────────────────────────────

#[cfg(feature = "powl")]
/// Convert a BPMN graph to POWL, starting from the start event and tracing
/// through the model.
fn bpmn_graph_to_powl(
    arena: &mut PowlArena,
    nodes: &BTreeMap<String, BpmnNode>,
    outgoing: &BTreeMap<String, Vec<String>>,
) -> Result<u32, String> {
    // Find start nodes
    let start_nodes = find_start_nodes(nodes, outgoing);
    if start_nodes.is_empty() {
        return Err("No start event found in BPMN model".to_string());
    }

    // Build POWL from each start node, then combine
    let mut powl_roots: Vec<u32> = Vec::new();
    for start_id in &start_nodes {
        let visited = &mut HashSet::new();
        let root = build_subtree(arena, start_id, nodes, outgoing, visited)?;
        powl_roots.push(root);
    }

    if powl_roots.len() == 1 {
        Ok(powl_roots[0])
    } else {
        // Multiple start nodes: wrap in XOR (choice of which process to start)
        Ok(arena.add_operator(Operator::Xor, powl_roots))
    }
}

/// Find start event nodes (startEvent elements, or nodes with no incoming edges).
fn find_start_nodes(
    nodes: &BTreeMap<String, BpmnNode>,
    outgoing: &BTreeMap<String, Vec<String>>,
) -> Vec<String> {
    // Prefer explicit start events
    let start_events: Vec<String> = nodes
        .iter()
        .filter(|(_, n)| n.node_type == BpmnNodeType::StartEvent)
        .map(|(id, _)| id.clone())
        .collect();

    if !start_events.is_empty() {
        start_events
    } else {
        // Find nodes with no incoming edges
        let has_incoming: HashSet<String> = nodes
            .keys()
            .filter(|id| outgoing.values().any(|targets| targets.contains(id)))
            .cloned()
            .collect();

        nodes
            .iter()
            .filter(|(id, n)| {
                !has_incoming.contains(*id)
                    && n.node_type != BpmnNodeType::EndEvent
                    && n.node_type != BpmnNodeType::Connector
                    && n.node_type != BpmnNodeType::Other
            })
            .map(|(id, _)| id.clone())
            .collect()
    }
}

#[cfg(feature = "powl")]
/// Recursively build a POWL subtree from a BPMN node.
fn build_subtree(
    arena: &mut PowlArena,
    node_id: &str,
    nodes: &BTreeMap<String, BpmnNode>,
    outgoing: &BTreeMap<String, Vec<String>>,
    visited: &mut HashSet<String>,
) -> Result<u32, String> {
    // Cycle guard
    if !visited.insert(node_id.to_string()) {
        // Back-edge detected: return a tau (silent transition) as silent loop routing
        return Ok(arena.add_silent_transition());
    }

    let node = nodes
        .get(node_id)
        .ok_or_else(|| format!("Node '{}' not found in BPMN elements", node_id))?;

    let children_ids = outgoing.get(node_id).cloned().unwrap_or_default();

    // Filter children: skip end events and connectors
    let real_children: Vec<String> = children_ids
        .iter()
        .filter(|id| {
            nodes.get(*id).is_none_or(|n| {
                n.node_type != BpmnNodeType::EndEvent && n.node_type != BpmnNodeType::Connector
            })
        })
        .cloned()
        .collect();

    let result = match &node.node_type {
        BpmnNodeType::StartEvent => {
            if real_children.len() == 1 {
                build_subtree(arena, &real_children[0], nodes, outgoing, visited)
            } else if real_children.is_empty() {
                Ok(arena.add_silent_transition())
            } else {
                // Multiple paths from start: XOR
                let child_nodes: Vec<u32> = real_children
                    .iter()
                    .map(|c| build_subtree(arena, c, nodes, outgoing, visited))
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(arena.add_operator(Operator::Xor, child_nodes))
            }
        }

        BpmnNodeType::EndEvent => Ok(arena.add_silent_transition()),

        BpmnNodeType::Task => {
            let label = if node.name.is_empty() {
                None
            } else {
                Some(node.name.clone())
            };

            if real_children.is_empty() {
                Ok(arena.add_transition(label))
            } else {
                let task_node = arena.add_transition(label);
                let child_nodes: Vec<u32> = real_children
                    .iter()
                    .map(|c| build_subtree(arena, c, nodes, outgoing, visited))
                    .collect::<Result<Vec<_>, _>>()?;

                if child_nodes.len() == 1 {
                    Ok(arena.add_sequence(vec![task_node, child_nodes[0]]))
                } else {
                    let mut all = vec![task_node];
                    all.extend(child_nodes);
                    Ok(arena.add_sequence(all))
                }
            }
        }

        BpmnNodeType::SilentTask => {
            if real_children.is_empty() {
                Ok(arena.add_silent_transition())
            } else {
                let tau_node = arena.add_silent_transition();
                let child_nodes: Vec<u32> = real_children
                    .iter()
                    .map(|c| build_subtree(arena, c, nodes, outgoing, visited))
                    .collect::<Result<Vec<_>, _>>()?;

                if child_nodes.len() == 1 {
                    Ok(arena.add_sequence(vec![tau_node, child_nodes[0]]))
                } else {
                    let mut all = vec![tau_node];
                    all.extend(child_nodes);
                    Ok(arena.add_sequence(all))
                }
            }
        }

        BpmnNodeType::ExclusiveGateway => {
            if real_children.is_empty() {
                Ok(arena.add_silent_transition())
            } else if real_children.len() == 1 {
                build_subtree(arena, &real_children[0], nodes, outgoing, visited)
            } else {
                // Multiple paths: check for loop (back-edge)
                let forward_children: Vec<String> = real_children
                    .iter()
                    .filter(|c| !visited.contains(*c))
                    .cloned()
                    .collect();
                let back_edge_children: Vec<String> = real_children
                    .iter()
                    .filter(|c| visited.contains(*c))
                    .cloned()
                    .collect();

                if !back_edge_children.is_empty() && !forward_children.is_empty() {
                    // Loop pattern: do-branch and redo-branch
                    let do_child =
                        build_subtree(arena, &forward_children[0], nodes, outgoing, visited)?;
                    let redo_child = if forward_children.len() > 1 {
                        build_subtree(arena, &forward_children[1], nodes, outgoing, visited)?
                    } else {
                        let mut new_visited = HashSet::new();
                        build_subtree(
                            arena,
                            &back_edge_children[0],
                            nodes,
                            outgoing,
                            &mut new_visited,
                        )?
                    };
                    Ok(arena.add_operator(Operator::Loop, vec![do_child, redo_child]))
                } else {
                    // XOR choice
                    let child_nodes: Vec<u32> = real_children
                        .iter()
                        .map(|c| build_subtree(arena, c, nodes, outgoing, visited))
                        .collect::<Result<Vec<_>, _>>()?;
                    Ok(arena.add_operator(Operator::Xor, child_nodes))
                }
            }
        }

        BpmnNodeType::ParallelGateway => {
            if real_children.is_empty() {
                Ok(arena.add_silent_transition())
            } else if real_children.len() == 1 {
                build_subtree(arena, &real_children[0], nodes, outgoing, visited)
            } else {
                // Parallel: SPO with no ordering constraints (all concurrent)
                let child_nodes: Vec<u32> = real_children
                    .iter()
                    .map(|c| build_subtree(arena, c, nodes, outgoing, visited))
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(arena.add_strict_partial_order(child_nodes))
            }
        }

        BpmnNodeType::InclusiveGateway => {
            // Treat inclusive gateway as XOR (simplification)
            if real_children.is_empty() {
                Ok(arena.add_silent_transition())
            } else if real_children.len() == 1 {
                build_subtree(arena, &real_children[0], nodes, outgoing, visited)
            } else {
                let child_nodes: Vec<u32> = real_children
                    .iter()
                    .map(|c| build_subtree(arena, c, nodes, outgoing, visited))
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(arena.add_operator(Operator::Xor, child_nodes))
            }
        }

        BpmnNodeType::Connector | BpmnNodeType::Other => {
            if real_children.len() == 1 {
                build_subtree(arena, &real_children[0], nodes, outgoing, visited)
            } else if real_children.is_empty() {
                Ok(arena.add_silent_transition())
            } else {
                let child_nodes: Vec<u32> = real_children
                    .iter()
                    .map(|c| build_subtree(arena, c, nodes, outgoing, visited))
                    .collect::<Result<Vec<_>, _>>()?;
                Ok(arena.add_sequence(child_nodes))
            }
        }
    };

    visited.remove(node_id);
    result
}

// ─── Public API ─────────────────────────────────────────────────────────────

/// Parse a BPMN 2.0 XML string and convert it to a POWL model string.
///
/// Handles both pm4wasm-generated BPMN and generic BPMN from external tools.
/// Connector nodes (pm4py:connector) and silent tasks (pm4py:silent) are
/// transparently resolved.
///
/// Mirrors `pm4py.read_bpmn()`.
///
/// # Errors
/// Returns a descriptive error string on parse failure or invalid BPMN structure.
#[cfg(feature = "powl")]
pub fn bpmn_to_powl_string(bpmn_xml: &str) -> Result<String, String> {
    if bpmn_xml.trim().is_empty() {
        return Err("Empty BPMN XML".to_string());
    }

    let (nodes, flows) = extract_bpmn_graph(bpmn_xml)?;

    if nodes.is_empty() {
        return Err("No BPMN elements found in XML".to_string());
    }

    // Identify connector nodes
    let connector_ids: HashSet<String> = nodes
        .iter()
        .filter(|(_, n)| n.node_type == BpmnNodeType::Connector)
        .map(|(id, _)| id.clone())
        .collect();

    // Build shortcut outgoing map (resolves through connectors)
    let outgoing = build_shortcut_outgoing(&flows, &connector_ids);

    let mut arena = PowlArena::new();
    let root = bpmn_graph_to_powl(&mut arena, &nodes, &outgoing)?;

    Ok(arena.to_repr(root))
}

// ─── WASM export ────────────────────────────────────────────────────────────

#[cfg(all(target_arch = "wasm32", feature = "powl"))]
use wasm_bindgen::prelude::*;

#[cfg(all(target_arch = "wasm32", feature = "powl"))]
#[wasm_bindgen]
/// WASM entry point: parse BPMN 2.0 XML and return a POWL model string.
///
/// # Errors
/// Returns a JavaScript `Error` with a descriptive message on failure.
pub fn read_bpmn(bpmn_xml: &str) -> Result<String, JsValue> {
    match bpmn_to_powl_string(bpmn_xml) {
        Ok(powl) => Ok(powl),
        Err(e) => Err(crate::error::js_val(&e)),
    }
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(all(test, feature = "powl"))]
mod tests {
    use super::*;
    #[cfg(feature = "powl")]
    use crate::powl_arena::PowlArena;
    #[cfg(feature = "powl")]
    use crate::powl_parser::parse_powl_model_string;

    /// Helper: parse a POWL string and return (arena, root).
    fn parse(s: &str) -> (PowlArena, u32) {
        let mut arena = PowlArena::new();
        let root = parse_powl_model_string(s, &mut arena).expect("parse failed");
        (arena, root)
    }

    #[test]
    fn test_simple_sequence_bpmn_to_powl() {
        let bpmn = r#"<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <process id="p1">
    <startEvent id="start"/>
    <task id="t1" name="A"/>
    <task id="t2" name="B"/>
    <endEvent id="end"/>
    <sequenceFlow sourceRef="start" targetRef="t1"/>
    <sequenceFlow sourceRef="t1" targetRef="t2"/>
    <sequenceFlow sourceRef="t2" targetRef="end"/>
  </process>
</definitions>"#;
        let result = bpmn_to_powl_string(bpmn).unwrap();
        assert!(
            result.contains("A"),
            "Expected 'A' in POWL output, got: {}",
            result
        );
        assert!(
            result.contains("B"),
            "Expected 'B' in POWL output, got: {}",
            result
        );
    }

    #[test]
    fn test_xor_gateway_bpmn_to_powl() {
        let bpmn = r#"<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <process id="p1">
    <startEvent id="start"/>
    <exclusiveGateway id="gw1"/>
    <task id="t1" name="A"/>
    <task id="t2" name="B"/>
    <endEvent id="end"/>
    <sequenceFlow sourceRef="start" targetRef="gw1"/>
    <sequenceFlow sourceRef="gw1" targetRef="t1"/>
    <sequenceFlow sourceRef="gw1" targetRef="t2"/>
    <sequenceFlow sourceRef="t1" targetRef="end"/>
    <sequenceFlow sourceRef="t2" targetRef="end"/>
  </process>
</definitions>"#;
        let result = bpmn_to_powl_string(bpmn).unwrap();
        assert!(
            result.contains("X"),
            "Expected XOR operator in POWL output, got: {}",
            result
        );
        assert!(
            result.contains("A"),
            "Expected 'A' in POWL output, got: {}",
            result
        );
        assert!(
            result.contains("B"),
            "Expected 'B' in POWL output, got: {}",
            result
        );
    }

    #[test]
    fn test_parallel_gateway_bpmn_to_powl() {
        let bpmn = r#"<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <process id="p1">
    <startEvent id="start"/>
    <parallelGateway id="gw_split"/>
    <task id="t1" name="A"/>
    <task id="t2" name="B"/>
    <parallelGateway id="gw_join"/>
    <endEvent id="end"/>
    <sequenceFlow sourceRef="start" targetRef="gw_split"/>
    <sequenceFlow sourceRef="gw_split" targetRef="t1"/>
    <sequenceFlow sourceRef="gw_split" targetRef="t2"/>
    <sequenceFlow sourceRef="t1" targetRef="gw_join"/>
    <sequenceFlow sourceRef="t2" targetRef="gw_join"/>
    <sequenceFlow sourceRef="gw_join" targetRef="end"/>
  </process>
</definitions>"#;
        let result = bpmn_to_powl_string(bpmn).unwrap();
        assert!(
            result.contains("A"),
            "Expected 'A' in POWL output, got: {}",
            result
        );
        assert!(
            result.contains("B"),
            "Expected 'B' in POWL output, got: {}",
            result
        );
    }

    #[test]
    fn test_empty_bpmn_errors() {
        let result = bpmn_to_powl_string("");
        assert!(result.is_err(), "Expected error for empty BPMN");
    }

    #[test]
    fn test_invalid_xml_does_not_panic() {
        // Should not panic; may succeed with no elements found or fail on parse
        let _ = bpmn_to_powl_string("not xml at all");
    }

    #[test]
    fn test_single_task_bpmn() {
        let bpmn = r#"<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <process id="p1">
    <startEvent id="start"/>
    <task id="t1" name="A"/>
    <endEvent id="end"/>
    <sequenceFlow sourceRef="start" targetRef="t1"/>
    <sequenceFlow sourceRef="t1" targetRef="end"/>
  </process>
</definitions>"#;
        let result = bpmn_to_powl_string(bpmn).unwrap();
        assert!(
            result.contains("A"),
            "Expected 'A' in POWL output, got: {}",
            result
        );
    }

    #[test]
    fn test_pm4wasm_connector_resolution() {
        // BPMN generated by pm4wasm's to_bpmn uses connector serviceTasks
        let bpmn = r#"<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:pm4py="http://pm4py.org/bpmn-ext">
  <process id="process_1" isExecutable="false">
    <startEvent id="startEvent_1"/>
    <endEvent id="endEvent_1"/>
    <serviceTask id="p_1" name="" pm4py:connector="true"/>
    <serviceTask id="p_2" name="" pm4py:connector="true"/>
    <task id="task_1" name="A"/>
    <sequenceFlow id="flow_1" sourceRef="startEvent_1" targetRef="p_1"/>
    <sequenceFlow id="flow_2" sourceRef="p_1" targetRef="task_1"/>
    <sequenceFlow id="flow_3" sourceRef="task_1" targetRef="p_2"/>
    <sequenceFlow id="flow_4" sourceRef="p_2" targetRef="endEvent_1"/>
  </process>
</definitions>"#;
        let result = bpmn_to_powl_string(bpmn).unwrap();
        assert!(
            result.contains("A"),
            "Expected 'A' after connector resolution, got: {}",
            result
        );
    }

    #[test]
    fn test_user_task_recognized() {
        let bpmn = r#"<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <process id="p1">
    <startEvent id="start"/>
    <userTask id="ut1" name="Review"/>
    <endEvent id="end"/>
    <sequenceFlow sourceRef="start" targetRef="ut1"/>
    <sequenceFlow sourceRef="ut1" targetRef="end"/>
  </process>
</definitions>"#;
        let result = bpmn_to_powl_string(bpmn).unwrap();
        assert!(
            result.contains("Review"),
            "Expected 'Review' from userTask, got: {}",
            result
        );
    }

    #[test]
    fn test_no_start_event_finds_root() {
        // BPMN without explicit startEvent: should find node with no incoming flow
        let bpmn = r#"<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <process id="p1">
    <task id="t1" name="A"/>
    <task id="t2" name="B"/>
    <sequenceFlow sourceRef="t1" targetRef="t2"/>
  </process>
</definitions>"#;
        let result = bpmn_to_powl_string(bpmn).unwrap();
        assert!(
            result.contains("A"),
            "Expected 'A' in POWL output, got: {}",
            result
        );
    }
}