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
//! Global stored-object state (handles, object pool, arena management).
//!
//! This module implements the handle-based state system that allows the WebAssembly
//! module to persist complex Rust objects across JavaScript calls without
//! expensive serialization or manual lifetime management in JavaScript.

use crate::error::{codes, wasm_err};
#[cfg(feature = "streaming_basic")]
use crate::incremental_dfg::IncrementalDFG;
#[cfg(feature = "streaming_basic")]
use crate::incremental_dfg::StreamingDFG;
use crate::models::{
    DeclareModel, EventLog, NGramPredictor, PetriNet, StreamingConformanceChecker, TemporalProfile,
    DFG, OCEL,
};
#[cfg(feature = "streaming_basic")]
use crate::streaming::{StreamingDfgBuilder, StreamingHeuristicBuilder, StreamingSkeletonBuilder};
#[cfg(feature = "streaming_full")]
use crate::streaming_pipeline::StreamingPipeline;
use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use wasm_bindgen::prelude::*;

/// Typed object storage for the WASM handle-based state system.
///
/// All objects created by the library (event logs, process models, streaming
/// builders, etc.) are stored internally and referenced by string handles.
/// This enum provides type-safe access to stored objects and enables
/// efficient serialization across the WASM boundary without requiring
/// JavaScript to manage Rust object lifetimes.
#[allow(clippy::large_enum_variant)]
#[derive(Clone)]
pub enum StoredObject {
    /// A case-centric event log.
    EventLog(EventLog),
    /// An object-centric event log.
    OCEL(OCEL),
    /// A Petri Net process model.
    PetriNet(PetriNet),
    /// A Directly-Follows Graph.
    DFG(DFG),
    /// A DECLARE model.
    DeclareModel(DeclareModel),
    /// A generic JSON string result.
    #[allow(dead_code)]
    JsonString(String),
    /// A builder for streaming DFG discovery.
    #[cfg(feature = "streaming_basic")]
    StreamingDfgBuilder(StreamingDfgBuilder),
    /// A builder for streaming skeleton discovery.
    #[cfg(feature = "streaming_basic")]
    StreamingSkeletonBuilder(StreamingSkeletonBuilder),
    /// A builder for streaming heuristic discovery.
    #[cfg(feature = "streaming_basic")]
    StreamingHeuristicBuilder(StreamingHeuristicBuilder),
    /// A stateful streaming conformance checker.
    StreamingConformanceChecker(StreamingConformanceChecker),
    /// A temporal profile of activity durations.
    TemporalProfile(TemporalProfile),
    /// A next-activity predictor.
    NGramPredictor(NGramPredictor),
    /// An incremental DFG representation.
    #[cfg(feature = "streaming_basic")]
    IncrementalDFG(IncrementalDFG),
    /// A streaming DFG representation.
    #[cfg(feature = "streaming_basic")]
    StreamingDFG(StreamingDFG),
    /// A full streaming pipeline.
    #[cfg(feature = "streaming_full")]
    StreamingPipeline(StreamingPipeline),
    /// A POWL model stored as (arena, root_index).
    #[cfg(feature = "powl")]
    PowlModel {
        arena: crate::powl_arena::PowlArena,
        root: u32,
    },
}

/// Global application state for managing objects in WASM handle system.
pub struct AppState {
    /// Inner storage mapping handles to objects.
    objects: Arc<Mutex<HashMap<String, StoredObject>>>,
    /// Counter for generating unique handles.
    counter: Arc<Mutex<u64>>,
    /// Lifecycle authority context.
    lsa: Arc<Mutex<crate::lsa::LifecycleAuthority>>,
}

impl AppState {
    /// Create a new empty application state.
    #[must_use]
    pub fn new() -> Self {
        AppState {
            objects: Arc::new(Mutex::new(HashMap::new())),
            counter: Arc::new(Mutex::new(0)),
            lsa: Arc::new(Mutex::new(crate::lsa::LifecycleAuthority::default())),
        }
    }

    /// Store an object and return a unique handle (string ID).
    ///
    /// # Errors
    /// Returns a `JsValue` error if the internal mutex cannot be locked.
    #[must_use]
    pub fn store_object(&self, obj: StoredObject) -> Result<String, JsValue> {
        let mut counter = self.counter.lock().map_err(|e| {
            wasm_err(
                codes::INTERNAL_ERROR,
                format!("Failed to lock counter: {e}"),
            )
        })?;
        let id = format!("obj_{counter}");
        *counter += 1;

        let mut objects = self.objects.lock().map_err(|e| {
            wasm_err(
                codes::INTERNAL_ERROR,
                format!("Failed to lock objects: {e}"),
            )
        })?;
        objects.insert(id.clone(), obj);
        Ok(id)
    }

    /// Retrieve an object by handle.
    ///
    /// This method clones the object. For better performance with large objects,
    /// prefer [`with_object`](Self::with_object).
    ///
    /// # Errors
    /// Returns a `JsValue` error if the internal mutex cannot be locked.
    #[must_use]
    pub fn get_object(&self, id: &str) -> Result<Option<StoredObject>, JsValue> {
        let objects = self.objects.lock().map_err(|e| {
            wasm_err(
                codes::INTERNAL_ERROR,
                format!("Failed to lock objects: {e}"),
            )
        })?;
        Ok(objects.get(id).cloned())
    }

    /// Execute a closure with a borrowed reference to the named object — zero clone.
    ///
    /// Use this instead of `get_object()` for all algorithm calls to avoid
    /// expensive cloning of large event logs or models.
    ///
    /// # Errors
    /// Returns a `JsValue` error if the internal mutex cannot be locked or
    /// if the closure returns an error.
    #[must_use]
    pub fn with_object<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(Option<&StoredObject>) -> Result<R, JsValue>,
    {
        let objects = self.objects.lock().map_err(|e| {
            wasm_err(
                codes::INTERNAL_ERROR,
                format!("Failed to lock objects: {e}"),
            )
        })?;
        f(objects.get(id))
    }

    /// Execute a closure with a mutable reference to the named object — zero clone.
    ///
    /// Use this for in-place mutation (e.g., streaming builder ingestion).
    ///
    /// # Errors
    /// Returns a `JsValue` error if the internal mutex cannot be locked or
    /// if the closure returns an error.
    #[must_use]
    pub fn with_object_mut<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(Option<&mut StoredObject>) -> Result<R, JsValue>,
    {
        let mut objects = self.objects.lock().map_err(|e| {
            wasm_err(
                codes::INTERNAL_ERROR,
                format!("Failed to lock objects: {e}"),
            )
        })?;
        f(objects.get_mut(id))
    }

    /// Execute a closure with the named `EventLog`, returning a typed error if not found.
    #[must_use]
    pub fn with_event_log<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&EventLog) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::EventLog(log)) => f(log),
            Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not an EventLog")),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("EventLog '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with the named `PetriNet`, returning a typed error if not found.
    #[must_use]
    pub fn with_petri_net<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&PetriNet) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::PetriNet(net)) => f(net),
            Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not a PetriNet")),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("PetriNet '{id}' not found"),
            )),
        })
    }
    /// Execute a closure with a mutable reference to the named `PetriNet`.
    #[must_use]
    pub fn with_petri_net_mut<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&mut PetriNet) -> Result<R, JsValue>,
    {
        self.with_object_mut(id, |obj| match obj {
            Some(StoredObject::PetriNet(net)) => f(net),
            Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not a PetriNet")),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("PetriNet '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with the named `OCEL`, returning a typed error if not found.
    #[cfg(feature = "ocel")]
    pub fn with_ocel<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&OCEL) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::OCEL(ocel)) => f(ocel),
            Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not an OCEL")),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("OCEL '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with the named `DFG`, returning a typed error if not found.
    #[must_use]
    pub fn with_dfg<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&DFG) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::DFG(dfg)) => f(dfg),
            Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not a DFG")),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("DFG '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with the named `JsonString`, returning a typed error if not found.
    #[must_use]
    pub fn with_json_string<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&str) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::JsonString(s)) => f(s),
            Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not a JsonString")),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("JsonString '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with a mutable reference to the named `EventLog`.
    #[must_use]
    pub fn with_event_log_mut<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&mut EventLog) -> Result<R, JsValue>,
    {
        self.with_object_mut(id, |obj| match obj {
            Some(StoredObject::EventLog(log)) => f(log),
            Some(_) => Err(wasm_err(codes::INVALID_INPUT, "Object is not an EventLog")),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("EventLog '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with the named `StreamingDfgBuilder`, returning a typed error if not found.
    #[cfg(feature = "streaming_basic")]
    pub fn with_streaming_dfg<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&StreamingDfgBuilder) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::StreamingDfgBuilder(b)) => f(b),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a StreamingDfgBuilder",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("StreamingDfgBuilder '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with a mutable reference to the named `StreamingDfgBuilder`.
    #[cfg(feature = "streaming_basic")]
    pub fn with_streaming_dfg_mut<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&mut StreamingDfgBuilder) -> Result<R, JsValue>,
    {
        self.with_object_mut(id, |obj| match obj {
            Some(StoredObject::StreamingDfgBuilder(b)) => f(b),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a StreamingDfgBuilder",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("StreamingDfgBuilder '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with the named `TemporalProfile`, returning a typed error if not found.
    #[must_use]
    pub fn with_temporal_profile<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&TemporalProfile) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::TemporalProfile(p)) => f(p),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a TemporalProfile",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("TemporalProfile '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with the named `DeclareModel`, returning a typed error if not found.
    #[must_use]
    pub fn with_declare_model<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&DeclareModel) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::DeclareModel(m)) => f(m),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a DeclareModel",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("DeclareModel '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with a mutable reference to the named `StreamingConformanceChecker`.
    #[must_use]
    pub fn with_streaming_conformance_mut<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&mut StreamingConformanceChecker) -> Result<R, JsValue>,
    {
        self.with_object_mut(id, |obj| match obj {
            Some(StoredObject::StreamingConformanceChecker(c)) => f(c),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a StreamingConformanceChecker",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("StreamingConformanceChecker '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with a mutable reference to the named `StreamingSkeletonBuilder`.
    #[cfg(feature = "streaming_basic")]
    pub fn with_streaming_skeleton_mut<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&mut StreamingSkeletonBuilder) -> Result<R, JsValue>,
    {
        self.with_object_mut(id, |obj| match obj {
            Some(StoredObject::StreamingSkeletonBuilder(b)) => f(b),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a StreamingSkeletonBuilder",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("StreamingSkeletonBuilder '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with the named `StreamingSkeletonBuilder` (immutable).
    #[cfg(feature = "streaming_basic")]
    pub fn with_streaming_skeleton<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&StreamingSkeletonBuilder) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::StreamingSkeletonBuilder(b)) => f(b),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a StreamingSkeletonBuilder",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("StreamingSkeletonBuilder '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with a mutable reference to the named `StreamingHeuristicBuilder`.
    #[cfg(feature = "streaming_basic")]
    pub fn with_streaming_heuristic_mut<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&mut StreamingHeuristicBuilder) -> Result<R, JsValue>,
    {
        self.with_object_mut(id, |obj| match obj {
            Some(StoredObject::StreamingHeuristicBuilder(b)) => f(b),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a StreamingHeuristicBuilder",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("StreamingHeuristicBuilder '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with the named `StreamingHeuristicBuilder` (immutable).
    #[cfg(feature = "streaming_basic")]
    pub fn with_streaming_heuristic<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&StreamingHeuristicBuilder) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::StreamingHeuristicBuilder(b)) => f(b),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a StreamingHeuristicBuilder",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("StreamingHeuristicBuilder '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with a mutable reference to the named `StreamingPipeline`.
    #[cfg(feature = "streaming_full")]
    pub fn with_streaming_pipeline_mut<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&mut StreamingPipeline) -> Result<R, JsValue>,
    {
        self.with_object_mut(id, |obj| match obj {
            Some(StoredObject::StreamingPipeline(p)) => f(p),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a StreamingPipeline",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("StreamingPipeline '{id}' not found"),
            )),
        })
    }

    /// Execute a closure with the named `StreamingPipeline` (immutable).
    #[cfg(feature = "streaming_full")]
    pub fn with_streaming_pipeline<F, R>(&self, id: &str, f: F) -> Result<R, JsValue>
    where
        F: FnOnce(&StreamingPipeline) -> Result<R, JsValue>,
    {
        self.with_object(id, |obj| match obj {
            Some(StoredObject::StreamingPipeline(p)) => f(p),
            Some(_) => Err(wasm_err(
                codes::INVALID_INPUT,
                "Object is not a StreamingPipeline",
            )),
            None => Err(wasm_err(
                codes::INVALID_HANDLE,
                format!("StreamingPipeline '{id}' not found"),
            )),
        })
    }

    /// Delete an object by handle from the registry.
    ///
    /// # Errors
    /// Returns a `JsValue` error if the internal mutex cannot be locked.
    #[must_use]
    pub fn delete_object(&self, id: &str) -> Result<bool, JsValue> {
        let mut objects = self.objects.lock().map_err(|e| {
            wasm_err(
                codes::INTERNAL_ERROR,
                format!("Failed to lock objects: {e}"),
            )
        })?;
        Ok(objects.remove(id).is_some())
    }

    /// Return the current number of stored objects.
    ///
    /// # Errors
    /// Returns a `JsValue` error if the internal mutex cannot be locked.
    #[must_use]
    pub fn object_count(&self) -> Result<usize, JsValue> {
        let objects = self.objects.lock().map_err(|e| {
            wasm_err(
                codes::INTERNAL_ERROR,
                format!("Failed to lock objects: {e}"),
            )
        })?;
        Ok(objects.len())
    }

    /// Clear all stored objects from the registry.
    ///
    /// # Errors
    /// Returns a `JsValue` error if the internal mutex cannot be locked.
    #[must_use]
    pub fn clear_all(&self) -> Result<(), JsValue> {
        let mut objects = self.objects.lock().map_err(|e| {
            wasm_err(
                codes::INTERNAL_ERROR,
                format!("Failed to lock objects: {e}"),
            )
        })?;
        objects.clear();
        Ok(())
    }
}

impl Default for AppState {
    fn default() -> Self {
        Self::new()
    }
}

static APP_STATE: Lazy<AppState> = Lazy::new(AppState::new);

/// Get the global application state.
pub fn get_or_init_state() -> &'static AppState {
    &APP_STATE
}

/// JS-accessible function to delete a stored object by handle.
#[wasm_bindgen]
#[must_use]
pub fn delete_object(id: &str) -> Result<bool, JsValue> {
    get_or_init_state().delete_object(id)
}

/// JS-accessible function to check if a stored object exists by handle.
#[wasm_bindgen]
pub fn object_exists(id: &str) -> bool {
    get_or_init_state()
        .with_object(id, |obj| Ok(obj.is_some()))
        .unwrap_or(false)
}

/// JS-accessible function to get the current number of stored objects.
#[wasm_bindgen]
#[must_use]
pub fn object_count() -> Result<usize, JsValue> {
    get_or_init_state().object_count()
}

/// JS-accessible function to clear all stored objects.
#[wasm_bindgen]
#[must_use]
pub fn clear_all_objects() -> Result<(), JsValue> {
    get_or_init_state().clear_all()
}