wasm4pm 26.7.1

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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
/**
 * wasm4pm — High-Performance Process Intelligence Control WebAssembly Client Library
 *
 * High-level TypeScript API for process mining in the browser.
 * Provides intuitive access to discovery, analysis, and conformance checking.
 */
import {
  asEventLogHandleId,
  asOCELHandleId,
  asDFGHandleId,
  asPetriNetHandleId,
  asDeclareHandleId,
  asTemporalProfileHandleId,
  asNGramPredictorHandleId,
  asStreamingDFGHandleId,
  asStreamingConformanceHandleId,
} from './types.js';
/**
 * Parse a WASM error response
 * WASM functions return JSON-stringified errors: {"code":"...", "message":"..."}
 */
export function parseWasm4pmError(error) {
  if (typeof error === 'string') {
    try {
      const parsed = JSON.parse(error);
      if (parsed.code && parsed.message) {
        return { code: parsed.code, message: parsed.message };
      }
    } catch {
      // Not valid JSON, treat as generic error
    }
    return { code: 'UNKNOWN_ERROR', message: error };
  }
  if (error instanceof Error) {
    return { code: 'ERROR', message: error.message };
  }
  return { code: 'UNKNOWN_ERROR', message: String(error) };
}
/**
 * Main client for wasm4pm operations
 * Handles initialization, data management, and algorithm execution
 */
export class ProcessMiningClient {
  constructor() {
    this.initialized = false;
    this.wasmModule = null;
    this.objects = new Map();
  }
  /**
   * Initialize the WASM module
   */
  async init() {
    if (this.initialized) {
      return;
    }
    try {
      // This will be the compiled WASM module
      // The actual initialization depends on how wasm-pack builds the module
      if (typeof globalThis !== 'undefined' && globalThis.wasm4pm) {
        this.wasmModule = globalThis.wasm4pm;
      }
      this.initialized = true;
    } catch (error) {
      throw new Error(`Failed to initialize wasm4pm: ${error}`);
    }
  }
  /**
   * Load an EventLog from JSON string
   */
  loadEventLogFromJSON(jsonContent) {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    const handle = asEventLogHandleId(this.wasmModule.load_eventlog_from_json(jsonContent));
    return new EventLogHandle(handle, this.wasmModule);
  }
  /**
   * Load an EventLog from XES string
   */
  loadEventLogFromXES(xesContent) {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    const handle = asEventLogHandleId(this.wasmModule.load_eventlog_from_xes(xesContent));
    return new EventLogHandle(handle, this.wasmModule);
  }
  /**
   * Load an OCEL from JSON string
   */
  loadOCELFromJSON(jsonContent) {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    const handle = asOCELHandleId(this.wasmModule.load_ocel_from_json(jsonContent));
    return new OCELHandle(handle, this.wasmModule);
  }
  /**
   * Load an OCEL from XML string
   */
  loadOCELFromXML(xmlContent) {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    const handle = asOCELHandleId(this.wasmModule.load_ocel_from_xml(xmlContent));
    return new OCELHandle(handle, this.wasmModule);
  }
  /**
   * Discover a Temporal Profile from an EventLog
   */
  discoverTemporalProfile(log, options = {}) {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    const activityKey = options.activityKey || 'concept:name';
    const timestampKey = options.timestampKey || 'time:timestamp';
    const handle = asTemporalProfileHandleId(
      this.wasmModule.discover_temporal_profile(log.getId(), activityKey, timestampKey)
    );
    return new TemporalProfileHandle(handle, this.wasmModule);
  }
  /**
   * Build an N-Gram Predictor from an EventLog
   */
  buildNGramPredictor(log, options = {}) {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    const activityKey = options.activityKey || 'concept:name';
    const n = options.n || 3;
    const handle = asNGramPredictorHandleId(
      this.wasmModule.build_ngram_predictor(log.getId(), activityKey, n)
    );
    return new NGramPredictorHandle(handle, this.wasmModule);
  }
  /**
   * Build a Remaining Time Model from a completed EventLog.
   * Fits a Weibull survival model and per-bucket statistics.
   * @param log - handle to a loaded EventLog
   * @param activityKey - attribute holding the activity name (default: 'concept:name')
   * @param timestampKey - attribute holding the timestamp (default: 'time:timestamp')
   */
  buildRemainingTimeModel(log, options = {}) {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    const activityKey = options.activityKey || 'concept:name';
    const timestampKey = options.timestampKey || 'time:timestamp';
    const handle = this.wasmModule.build_remaining_time_model(
      log.getId(),
      activityKey,
      timestampKey
    );
    return new RemainingTimeModelHandle(handle, this.wasmModule);
  }
  /**
   * Begin a Streaming DFG builder
   */
  beginStreamingDFG() {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    const handle = asStreamingDFGHandleId(this.wasmModule.streaming_dfg_begin());
    return new StreamingDFGHandle(handle, this.wasmModule);
  }
  /**
   * Begin a Streaming Conformance checker against a reference DFG
   */
  beginStreamingConformance(dfg) {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    const handle = asStreamingConformanceHandleId(
      this.wasmModule.streaming_conformance_begin(dfg.getId())
    );
    return new StreamingConformanceHandle(handle, this.wasmModule);
  }
  /**
   * Get the capability registry metadata
   */
  getCapabilityRegistry() {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    return this.wasmModule.get_capability_registry();
  }
  /**
   * Run OC performance analysis on an OCEL
   */
  analyzeOCPerformance(ocel) {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    return this.wasmModule.oc_performance_analysis(ocel.getId());
  }
  /**
   * Get the version of wasm4pm
   */
  getVersion() {
    if (!this.initialized) throw new Error('Client not initialized. Call init() first.');
    return this.wasmModule.get_version();
  }
}
/**
 * Handle to an EventLog stored in WASM memory
 */
export class EventLogHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  /**
   * Get the handle ID
   */
  getId() {
    return this.handle;
  }
  /**
   * Get basic statistics about the log
   */
  getStats() {
    try {
      return this.wasmModule.analyze_event_statistics(this.handle);
    } catch (error) {
      throw new Error(`Failed to get event log statistics: ${error}`);
    }
  }
  /**
   * Get number of traces (cases)
   */
  getTraceCount() {
    return this.wasmModule.get_trace_count(this.handle);
  }
  /**
   * Get total number of events
   */
  getEventCount() {
    return this.wasmModule.get_event_count(this.handle);
  }
  /**
   * Get unique activities
   */
  getActivities(activityKey = 'concept:name') {
    return this.wasmModule.get_activities(this.handle, activityKey);
  }
  /**
   * Get trace length statistics
   */
  getTraceLengthStats(activityKey = 'concept:name') {
    return this.wasmModule.get_trace_length_statistics(this.handle);
  }
  /**
   * Get activity frequencies
   */
  getActivityFrequencies(activityKey = 'concept:name') {
    return this.wasmModule.get_activity_frequencies(this.handle, activityKey);
  }
  /**
   * Get all attribute names used in the log
   */
  getAttributeNames() {
    return this.wasmModule.get_attribute_names(this.handle);
  }
  /**
   * Filter the log to keep only traces containing the specified activity
   */
  filterByActivity(activity, activityKey = 'concept:name') {
    const result = this.wasmModule.filter_log_by_activity(this.handle, activityKey, activity);
    return new EventLogHandle(asEventLogHandleId(result.handle), this.wasmModule);
  }
  /**
   * Filter the log to keep only traces within the specified length range
   */
  filterByTraceLength(minLength, maxLength) {
    const result = this.wasmModule.filter_log_by_trace_length(this.handle, minLength, maxLength);
    return new EventLogHandle(asEventLogHandleId(result.handle), this.wasmModule);
  }
  /**
   * Discover a Directly-Follows Graph (DFG)
   */
  discoverDFG(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const minFrequency = options.minFrequency || 1;
    const result = this.wasmModule.discover_dfg_filtered(this.handle, activityKey, minFrequency);
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * Discover DECLARE constraints
   */
  discoverDECLARE(activityKey = 'concept:name') {
    const result = this.wasmModule.discover_declare(this.handle, activityKey);
    return new DeclareModelHandle(asDeclareHandleId(result.handle), this.wasmModule);
  }
  /**
   * Discover a Petri Net using Alpha++
   */
  discoverAlphaPlusPlus(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const minSupport = options.minSupport || 0.1;
    const result = this.wasmModule.discover_alpha_plus_plus(this.handle, activityKey, minSupport);
    return new PetriNetHandle(asPetriNetHandleId(result.handle), this.wasmModule);
  }
  /**
   * Discover optimal Petri Net using ILP constraint-based optimization
   */
  discoverILPPetriNet(activityKey = 'concept:name') {
    const result = this.wasmModule.discover_ilp_petri_net(this.handle, activityKey);
    return new PetriNetHandle(asPetriNetHandleId(result.handle), this.wasmModule);
  }
  /**
   * Discover DFG using weighted fitness-simplicity optimization
   */
  discoverOptimizedDFG(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const fitnessWeight = options.fitnessWeight || 0.7;
    const simplicityWeight = options.simplicityWeight || 0.3;
    const result = this.wasmModule.discover_optimized_dfg(
      this.handle,
      activityKey,
      fitnessWeight,
      simplicityWeight
    );
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * Discover process model using Genetic Algorithm evolution
   */
  discoverGeneticAlgorithm(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const populationSize = options.populationSize || 50;
    const generations = options.generations || 20;
    const result = this.wasmModule.discover_genetic_algorithm(
      this.handle,
      activityKey,
      populationSize,
      generations
    );
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * Discover process model using Particle Swarm Optimization
   */
  discoverPSOAlgorithm(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const swarmSize = options.swarmSize || 30;
    const iterations = options.iterations || 50;
    const result = this.wasmModule.discover_pso_algorithm(
      this.handle,
      activityKey,
      swarmSize,
      iterations
    );
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * A* Search-based discovery - informed heuristic search for optimal models
   */
  discoverAStar(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const maxIterations = options.maxIterations || 1000;
    const result = this.wasmModule.discover_astar(this.handle, activityKey, maxIterations);
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * Hill Climbing - greedy local optimization to maximal fitness
   */
  discoverHillClimbing(activityKey = 'concept:name') {
    const result = this.wasmModule.discover_hill_climbing(this.handle, activityKey);
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * Analyze trace variants - extract unique process paths and frequencies
   */
  getTraceVariants(activityKey = 'concept:name') {
    return this.wasmModule.analyze_trace_variants(this.handle, activityKey);
  }
  /**
   * Sequential Pattern Mining - find frequent activity sequences
   */
  mineSequentialPatterns(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const minSupport = options.minSupport || 0.01;
    const patternLength = options.patternLength || 3;
    return this.wasmModule.mine_sequential_patterns(
      this.handle,
      activityKey,
      minSupport,
      patternLength
    );
  }
  /**
   * Detect concept drift - identify where process behavior changes
   */
  detectConceptDrift(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const windowSize = options.windowSize || 50;
    return this.wasmModule.detect_concept_drift(this.handle, activityKey, windowSize);
  }
  /**
   * Cluster traces - group similar traces for variant analysis
   */
  clusterTraces(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const numClusters = options.numClusters || 5;
    return this.wasmModule.cluster_traces(this.handle, activityKey, numClusters);
  }
  /**
   * Analyze start/end activities - find entry and exit points in process
   */
  getStartEndActivities(activityKey = 'concept:name') {
    return this.wasmModule.analyze_start_end_activities(this.handle, activityKey);
  }
  /**
   * Activity co-occurrence - find activities that happen together in traces
   */
  getActivityCooccurrence(activityKey = 'concept:name') {
    return this.wasmModule.analyze_activity_cooccurrence(this.handle, activityKey);
  }
  /**
   * Inductive Miner - recursive structure discovery with direct follows graph
   */
  discoverInductiveMiner(activityKey = 'concept:name') {
    const result = this.wasmModule.discover_inductive_miner(this.handle, activityKey);
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * Ant Colony Optimization - pheromone-based distributed search
   */
  discoverAntColony(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const numAnts = options.numAnts || 20;
    const iterations = options.iterations || 10;
    const result = this.wasmModule.discover_ant_colony(
      this.handle,
      activityKey,
      numAnts,
      iterations
    );
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * Simulated Annealing - thermal search with cooling schedule
   */
  discoverSimulatedAnnealing(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const temperature = options.temperature || 100.0;
    const coolingRate = options.coolingRate || 0.95;
    const result = this.wasmModule.discover_simulated_annealing(
      this.handle,
      activityKey,
      temperature,
      coolingRate
    );
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * Extract Process Skeleton - minimal model keeping only frequent edges
   */
  extractProcessSkeleton(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const minFrequency = options.minFrequency || 2;
    const result = this.wasmModule.extract_process_skeleton(this.handle, activityKey, minFrequency);
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * Analyze Activity Dependencies - identify predecessors and successors
   */
  getActivityDependencies(activityKey = 'concept:name') {
    return this.wasmModule.analyze_activity_dependencies(this.handle, activityKey);
  }
  /**
   * Analyze Case Attributes - correlate case-level attributes with process
   */
  getCaseAttributeAnalysis(activityKey = 'concept:name') {
    return this.wasmModule.analyze_case_attributes(this.handle, activityKey);
  }
  /**
   * Variant Complexity - measure Shannon entropy and variant diversity
   */
  getVariantComplexity(activityKey = 'concept:name') {
    return this.wasmModule.analyze_variant_complexity(this.handle, activityKey);
  }
  /**
   * Activity Transition Matrix - compute Markov chain transition probabilities
   */
  getTransitionMatrix(activityKey = 'concept:name') {
    return this.wasmModule.compute_activity_transition_matrix(this.handle, activityKey);
  }
  /**
   * Temporal Speedup Analysis - identify process acceleration/deceleration patterns
   */
  analyzeProcessSpeedup(options = {}) {
    const timestampKey = options.timestampKey || 'time:timestamp';
    const windowSize = options.windowSize || 50;
    return this.wasmModule.analyze_process_speedup(this.handle, timestampKey, windowSize);
  }
  /**
   * Trace Similarity Matrix - compute pairwise trace distance/similarity
   */
  getTraceSimilarityMatrix(activityKey = 'concept:name') {
    return this.wasmModule.compute_trace_similarity_matrix(this.handle, activityKey);
  }
  /**
   * Temporal Bottlenecks - identify time-based performance bottlenecks
   */
  getTemporalBottlenecks(options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const timestampKey = options.timestampKey || 'time:timestamp';
    return this.wasmModule.analyze_temporal_bottlenecks(this.handle, activityKey, timestampKey);
  }
  /**
   * Activity Ordering - extract mandatory predecessor ordering from traces
   */
  getActivityOrdering(activityKey = 'concept:name') {
    return this.wasmModule.extract_activity_ordering(this.handle, activityKey);
  }
  /**
   * Generate dotted chart data for visualization
   */
  getDottedChart(activityKey = 'concept:name') {
    return this.wasmModule.analyze_dotted_chart(this.handle);
  }
  /**
   * Calculate case durations
   */
  calculateCaseDurations(timestampKey = 'time:timestamp') {
    return this.wasmModule.calculate_trace_durations(this.handle, timestampKey);
  }
  /**
   * Check if log has timestamp attributes
   */
  hasTimestamps(timestampKey = 'time:timestamp') {
    return this.wasmModule.validate_has_timestamps(this.handle, timestampKey);
  }
  /**
   * Check if log has activity attributes
   */
  hasActivities(activityKey = 'concept:name') {
    return this.wasmModule.validate_has_activities(this.handle, activityKey);
  }
  /**
   * Export the log to JSON
   */
  toJSON() {
    return this.wasmModule.export_eventlog_to_json(this.handle);
  }
  /**
   * Export the log to XES format
   */
  toXES() {
    return this.wasmModule.export_eventlog_to_xes(this.handle);
  }
  /**
   * Extract case-level features for predictive modeling
   */
  extractCaseFeatures(
    activityKey = 'concept:name',
    timestampKey = 'time:timestamp',
    config = { features: [], target: 'outcome' }
  ) {
    try {
      const result = this.wasmModule.extract_case_features(
        this.handle,
        activityKey,
        timestampKey,
        JSON.stringify(config)
      );
      return Promise.resolve(JSON.parse(result));
    } catch (error) {
      return Promise.reject(new Error(`Failed to extract case features: ${error}`));
    }
  }
  /**
   * Extract prefix-level features for remaining time/outcome prediction
   */
  extractPrefixFeatures(
    activityKey = 'concept:name',
    timestampKey = 'time:timestamp',
    prefixLength = 5
  ) {
    try {
      const result = this.wasmModule.extract_prefix_features(
        this.handle,
        activityKey,
        timestampKey,
        prefixLength
      );
      return Promise.resolve(JSON.parse(result));
    } catch (error) {
      return Promise.reject(new Error(`Failed to extract prefix features: ${error}`));
    }
  }
  /**
   * Export extracted features as CSV
   */
  exportFeaturesAsCSV(
    activityKey = 'concept:name',
    timestampKey = 'time:timestamp',
    config = { features: [], target: 'outcome' }
  ) {
    try {
      const featuresJson = this.wasmModule.export_features_json(
        this.handle,
        activityKey,
        timestampKey,
        JSON.stringify(config)
      );
      const result = this.wasmModule.export_features_csv(featuresJson);
      return Promise.resolve(result);
    } catch (error) {
      return Promise.reject(new Error(`Failed to export features as CSV: ${error}`));
    }
  }
  /**
   * Check data quality of the event log
   */
  checkDataQuality(activityKey = 'concept:name', timestampKey = 'time:timestamp') {
    try {
      const result = this.wasmModule.check_data_quality(this.handle, activityKey, timestampKey);
      return Promise.resolve(JSON.parse(result));
    } catch (error) {
      return Promise.reject(new Error(`Failed to check data quality: ${error}`));
    }
  }
  /**
   * Infer event log schema automatically
   */
  inferSchema() {
    try {
      const result = this.wasmModule.infer_eventlog_schema(this.handle);
      return Promise.resolve(JSON.parse(result));
    } catch (error) {
      return Promise.reject(new Error(`Failed to infer schema: ${error}`));
    }
  }
  /**
   * Analyze resource utilization
   */
  analyzeResourceUtilization(resourceKey = 'org:resource', timestampKey = 'time:timestamp') {
    try {
      const result = this.wasmModule.analyze_resource_utilization(
        this.handle,
        resourceKey,
        timestampKey
      );
      return Promise.resolve(JSON.parse(result));
    } catch (error) {
      return Promise.reject(new Error(`Failed to analyze resource utilization: ${error}`));
    }
  }
  /**
   * Analyze resource-activity interactions
   */
  analyzeResourceActivityMatrix(resourceKey = 'org:resource', activityKey = 'concept:name') {
    try {
      const result = this.wasmModule.analyze_resource_activity_matrix(
        this.handle,
        resourceKey,
        activityKey
      );
      return Promise.resolve(JSON.parse(result));
    } catch (error) {
      return Promise.reject(new Error(`Failed to analyze resource-activity matrix: ${error}`));
    }
  }
  /**
   * Identify resource bottlenecks
   */
  identifyResourceBottlenecks(
    resourceKey = 'org:resource',
    timestampKey = 'time:timestamp',
    activityKey = 'concept:name'
  ) {
    try {
      const result = this.wasmModule.identify_resource_bottlenecks(
        this.handle,
        resourceKey,
        timestampKey,
        activityKey
      );
      return Promise.resolve(JSON.parse(result));
    } catch (error) {
      return Promise.reject(new Error(`Failed to identify resource bottlenecks: ${error}`));
    }
  }
  /**
   * Cleanup: delete the log from WASM memory
   */
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
/**
 * Handle to an OCEL stored in WASM memory
 */
export class OCELHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  /**
   * Get the handle ID
   */
  getId() {
    return this.handle;
  }
  /**
   * Get basic statistics about the OCEL
   */
  getStats() {
    return this.wasmModule.analyze_ocel_statistics(this.handle);
  }
  /**
   * Get the total number of events in the OCEL
   */
  getEventCount() {
    return this.wasmModule.get_ocel_event_count(this.handle);
  }
  /**
   * Get the total number of objects in the OCEL
   */
  getObjectCount() {
    return this.wasmModule.get_ocel_object_count(this.handle);
  }
  /**
   * Discover Object-Centric DFG
   */
  discoverOCDFG(options = {}) {
    const minFrequency = options.minFrequency || 1;
    const result = this.wasmModule.discover_ocel_dfg(this.handle);
    return new DFGHandle(asDFGHandleId(result.handle), this.wasmModule);
  }
  /**
   * Export to JSON
   */
  toJSON() {
    return this.wasmModule.export_ocel_to_json(this.handle);
  }
  /**
   * List all object types in the OCEL
   */
  listObjectTypes() {
    try {
      const result = this.wasmModule.list_ocel_object_types(this.handle);
      return Promise.resolve(JSON.parse(result));
    } catch (error) {
      return Promise.reject(new Error(`Failed to list object types: ${error}`));
    }
  }
  /**
   * Get statistics for each object type
   */
  getTypeStatistics() {
    try {
      const result = this.wasmModule.get_ocel_type_statistics(this.handle);
      return Promise.resolve(JSON.parse(result));
    } catch (error) {
      return Promise.reject(new Error(`Failed to get type statistics: ${error}`));
    }
  }
  /**
   * Flatten OCEL to EventLog for a specific object type
   */
  flattenToEventLog(objectType) {
    try {
      const result = this.wasmModule.flatten_ocel_to_eventlog(this.handle, objectType);
      return new EventLogHandle(asEventLogHandleId(result), this.wasmModule);
    } catch (error) {
      throw new Error(`Failed to flatten OCEL to EventLog: ${error}`);
    }
  }
  /**
   * Discover DFG for each object type
   */
  discoverDFGPerType() {
    try {
      const result = this.wasmModule.discover_ocel_dfg_per_type(this.handle);
      return Promise.resolve(JSON.parse(result));
    } catch (error) {
      return Promise.reject(new Error(`Failed to discover DFG per type: ${error}`));
    }
  }
  /**
   * Cleanup: delete from WASM memory
   */
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
/**
 * Handle to a Directly-Follows Graph
 */
export class DFGHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  /**
   * Get the handle ID
   */
  getId() {
    return this.handle;
  }
  /**
   * Get the DFG as JSON
   */
  toJSON() {
    const json = this.wasmModule.export_dfg_to_json(this.handle);
    return JSON.parse(json);
  }
  /**
   * Cleanup
   */
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
/**
 * Handle to a Petri Net
 */
export class PetriNetHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  /**
   * Get the handle ID
   */
  getId() {
    return this.handle;
  }
  /**
   * Get the Petri Net as JSON
   */
  toJSON() {
    const json = this.wasmModule.export_petri_net_to_json(this.handle);
    return JSON.parse(json);
  }
  /**
   * Check conformance of an EventLog against this Petri Net
   */
  checkConformance(log, activityKey = 'concept:name') {
    return this.wasmModule.check_token_based_replay(log.getId(), this.handle, activityKey);
  }
  /**
   * Cleanup
   */
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
/**
 * Handle to a DECLARE model
 */
export class DeclareModelHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  /**
   * Get the handle ID
   */
  getId() {
    return this.handle;
  }
  /**
   * Get the model as JSON
   */
  toJSON() {
    // Phase 2A: export function not yet in WASM .d.ts; cast to preserve forward compat
    const exportFn = this.wasmModule.export_declare_model_to_json;
    if (!exportFn)
      throw new Error('export_declare_model_to_json not available in current WASM build');
    const json = exportFn(this.handle);
    return JSON.parse(json);
  }
  /**
   * Cleanup
   */
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
/**
 * Handle to an Object-Centric Petri Net
 */
export class OCPetriNetHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  /**
   * Get the handle ID
   */
  getId() {
    return this.handle;
  }
  /**
   * Get the OC Petri Net as JSON
   */
  toJSON() {
    // Phase 2A: export function not yet in WASM .d.ts; cast to preserve forward compat
    const exportFn = this.wasmModule.export_oc_petri_net_to_json;
    if (!exportFn)
      throw new Error('export_oc_petri_net_to_json not available in current WASM build');
    const json = exportFn(this.handle);
    return JSON.parse(json);
  }
  /**
   * Export as PNML format (Petri Net Markup Language)
   */
  toPNML() {
    // Phase 2A: export function not yet in WASM .d.ts; cast to preserve forward compat
    const exportFn = this.wasmModule.export_oc_petri_net_to_pnml;
    if (!exportFn)
      throw new Error('export_oc_petri_net_to_pnml not available in current WASM build');
    return exportFn(this.handle);
  }
  /**
   * Cleanup
   */
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
/**
 * Handle to a Temporal Profile stored in WASM memory
 */
export class TemporalProfileHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  getId() {
    return this.handle;
  }
  /**
   * Check conformance of an EventLog against this temporal profile
   * @param log - EventLog to check
   * @param zeta - z-score threshold for deviation detection (default 2.0)
   */
  checkConformance(log, options = {}) {
    const activityKey = options.activityKey || 'concept:name';
    const timestampKey = options.timestampKey || 'time:timestamp';
    const zeta = options.zeta || 2.0;
    return this.wasmModule.check_temporal_conformance(
      log.getId(),
      this.handle,
      activityKey,
      timestampKey,
      zeta
    );
  }
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
/**
 * Handle to an N-Gram Predictor stored in WASM memory
 */
export class NGramPredictorHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  getId() {
    return this.handle;
  }
  /**
   * Predict the next activity given a prefix of activities (simple, returns raw value)
   * @param prefix - array of activity names forming the prefix
   */
  predictNextActivity(prefix) {
    return this.wasmModule.predict_next_activity(this.handle, JSON.stringify(prefix));
  }
  /**
   * Predict top-k next activities with probabilities, confidence, and entropy.
   * Returns `{ activities: string[], probabilities: number[], confidence: number, entropy: number }`
   * @param prefix - array of activity names forming the current prefix
   * @param k - number of top candidates to return
   */
  predictNextK(prefix, k) {
    return JSON.parse(this.wasmModule.predict_next_k(this.handle, JSON.stringify(prefix), k));
  }
  /**
   * Beam-search future paths from the current prefix.
   * Returns an array of `{ sequence: string[], probability: number, length: number }`
   * sorted by descending probability.
   * @param prefix - array of activity names forming the current prefix
   * @param beamWidth - number of beams (candidate paths) to keep at each step
   * @param maxSteps - maximum number of future activities to project
   */
  predictBeamPaths(prefix, beamWidth, maxSteps) {
    return JSON.parse(
      this.wasmModule.predict_beam_paths(this.handle, JSON.stringify(prefix), beamWidth, maxSteps)
    );
  }
  /**
   * Score the likelihood of a complete trace (returns plain log-probability float).
   * @param activities - array of activity names in the trace
   */
  scoreTraceLikelihood(activities) {
    return this.wasmModule.score_trace_likelihood(this.handle, JSON.stringify(activities));
  }
  /**
   * Score trace likelihood with structured output.
   * Returns `{ log_likelihood: number, normalized: number }`
   * @param activities - array of activity names in the trace
   */
  computeTraceLikelihood(activities) {
    return this.wasmModule.compute_trace_likelihood(this.handle, JSON.stringify(activities));
  }
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
// ---------------------------------------------------------------------------
// RemainingTimeModelHandle
// ---------------------------------------------------------------------------
/**
 * Handle to a Remaining Time Model stored in WASM memory.
 * Answers "When will this case complete?"
 *
 * Build with `ProcessMiningClient.buildRemainingTimeModel()`.
 */
export class RemainingTimeModelHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  getId() {
    return this.handle;
  }
  /**
   * Estimate remaining time for a running case given its activity prefix.
   * Returns `{ remaining_ms: number, confidence: number, method: string }`
   * @param prefix - array of activity names observed so far
   */
  predictCaseDuration(prefix) {
    return this.wasmModule.predict_case_duration(this.handle, JSON.stringify(prefix));
  }
  /**
   * Instantaneous hazard rate at a given elapsed time.
   * Returns `{ hazard_rate, survival_probability, cumulative_hazard, median_remaining_ms, shape, scale }`
   * @param elapsedMs - milliseconds elapsed since case start
   */
  predictHazardRate(elapsedMs) {
    return this.wasmModule.predict_hazard_rate(this.handle, elapsedMs);
  }
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
/**
 * Handle to a Streaming DFG builder stored in WASM memory
 */
export class StreamingDFGHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  getId() {
    return this.handle;
  }
  /**
   * Add a single event to the streaming DFG
   */
  addEvent(caseId, activity) {
    return this.wasmModule.streaming_dfg_add_event(this.handle, caseId, activity);
  }
  /**
   * Add a batch of events as JSON array
   * @param eventsJson - JSON string of [{case_id, activity}, ...]
   */
  addBatch(eventsJson) {
    return this.wasmModule.streaming_dfg_add_batch(this.handle, eventsJson);
  }
  /**
   * Close a trace (mark case as complete)
   */
  closeTrace(caseId) {
    return this.wasmModule.streaming_dfg_close_trace(this.handle, caseId);
  }
  /**
   * Flush all open traces (close them without explicit close)
   */
  flushOpen() {
    return this.wasmModule.streaming_dfg_flush_open(this.handle);
  }
  /**
   * Take a snapshot of the current DFG state
   */
  snapshot() {
    return this.wasmModule.streaming_dfg_snapshot(this.handle);
  }
  /**
   * Finalize the streaming DFG and produce the final result
   */
  finalize() {
    return this.wasmModule.streaming_dfg_finalize(this.handle);
  }
  /**
   * Get current statistics
   */
  stats() {
    return this.wasmModule.streaming_dfg_stats(this.handle);
  }
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
/**
 * Handle to a Streaming Conformance checker stored in WASM memory
 */
export class StreamingConformanceHandle {
  constructor(handle, wasmModule) {
    this.handle = handle;
    this.wasmModule = wasmModule;
  }
  getId() {
    return this.handle;
  }
  /**
   * Add a single event for conformance checking
   */
  addEvent(caseId, activity) {
    return this.wasmModule.streaming_conformance_add_event(this.handle, caseId, activity);
  }
  /**
   * Close a trace (mark case as complete)
   */
  closeTrace(caseId) {
    return this.wasmModule.streaming_conformance_close_trace(this.handle, caseId);
  }
  /**
   * Get current conformance statistics
   */
  stats() {
    return this.wasmModule.streaming_conformance_stats(this.handle);
  }
  /**
   * Finalize and produce final conformance results
   */
  finalize() {
    return this.wasmModule.streaming_conformance_finalize(this.handle);
  }
  delete() {
    this.wasmModule.delete_object(this.handle);
  }
}
/**
 * Convenience function to load a file from the browser
 */
export async function loadFileAsText(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target?.result);
    reader.onerror = () => reject(new Error('Failed to read file'));
    reader.readAsText(file);
  });
}
// ============================================================================
// TEXT ENCODING FUNCTIONS
// ============================================================================
/**
 * Get a reference to the WASM module (for text encoding functions)
 */
let wasmModuleGlobal = null;
/**
 * Initialize the global WASM module reference
 */
export function initializeWasm4pmModule(wasmModule) {
  wasmModuleGlobal = wasmModule;
}
/**
 * Encode DFG as plain text representation
 */
export async function encodeTextAsText(dfgHandle) {
  if (!wasmModuleGlobal) {
    throw new Error('WASM module not initialized. Call initializeWasm4pmModule() first.');
  }
  try {
    return wasmModuleGlobal.encode_dfg_as_text(dfgHandle.getId());
  } catch (error) {
    throw new Error(`Failed to encode DFG as text: ${error}`);
  }
}
/**
 * Encode variants as text representation
 */
export async function encodeVariantsAsText(logHandle, activityKey = 'concept:name', topN = 10) {
  if (!wasmModuleGlobal) {
    throw new Error('WASM module not initialized. Call initializeWasm4pmModule() first.');
  }
  try {
    return wasmModuleGlobal.encode_variants_as_text(logHandle.getId(), activityKey, topN);
  } catch (error) {
    throw new Error(`Failed to encode variants as text: ${error}`);
  }
}
/**
 * Encode event log as text summary
 */
export async function encodeLogAsText(logHandle) {
  if (!wasmModuleGlobal) {
    throw new Error('WASM module not initialized. Call initializeWasm4pmModule() first.');
  }
  try {
    return wasmModuleGlobal.encode_statistics_as_text(logHandle.getId());
  } catch (error) {
    throw new Error(`Failed to encode log as text: ${error}`);
  }
}
/**
 * Encode Petri Net as text representation
 */
export async function encodePetriNetAsText(petriNetHandle) {
  if (!wasmModuleGlobal) {
    throw new Error('WASM module not initialized. Call initializeWasm4pmModule() first.');
  }
  try {
    return wasmModuleGlobal.encode_petri_net_as_text(petriNetHandle.getId());
  } catch (error) {
    throw new Error(`Failed to encode Petri Net as text: ${error}`);
  }
}
/**
 * Encode OCEL as text representation
 */
export async function encodeOCELAsText(ocelHandle) {
  if (!wasmModuleGlobal) {
    throw new Error('WASM module not initialized. Call initializeWasm4pmModule() first.');
  }
  try {
    return wasmModuleGlobal.encode_ocel_as_text(ocelHandle.getId());
  } catch (error) {
    throw new Error(`Failed to encode OCEL as text: ${error}`);
  }
}
/**
 * Encode object-centric Petri Net as text representation
 */
export async function encodeOCPetriNetAsText(ocpnHandle) {
  if (!wasmModuleGlobal) {
    throw new Error('WASM module not initialized. Call initializeWasm4pmModule() first.');
  }
  try {
    return wasmModuleGlobal.encode_oc_petri_net_as_text(ocpnHandle.getId());
  } catch (error) {
    throw new Error(`Failed to encode OC Petri Net as text: ${error}`);
  }
}
/**
 * Encode process model comparison as text
 */
export async function encodeModelComparisonAsText(model1Handle, model2Handle) {
  if (!wasmModuleGlobal) {
    throw new Error('WASM module not initialized. Call initializeWasm4pmModule() first.');
  }
  try {
    const id1 = model1Handle instanceof DFGHandle ? model1Handle.getId() : model1Handle.getId();
    const id2 = model2Handle instanceof DFGHandle ? model2Handle.getId() : model2Handle.getId();
    return wasmModuleGlobal.encode_model_comparison_as_text(id1, id2);
  } catch (error) {
    throw new Error(`Failed to encode model comparison as text: ${error}`);
  }
}
// =============================================================================
// Van der Aalst Prediction API — standalone functions
// =============================================================================
// These wrap the six perspective modules introduced in Phase 4.
// They all require the global WASM module (call initializeWasm4pmModule() first).
// ---------------------------------------------------------------------------
// Outcome prediction (answers "Does this case complete normally?")
// ---------------------------------------------------------------------------
/**
 * Score how anomalous a trace is relative to a DFG model.
 * Returns `{ score: number [0–1], is_anomalous: boolean, threshold: number }`
 * @param dfgHandle - handle to a discovered DFG
 * @param trace - array of activity names
 */
export function scoreAnomaly(dfgHandle, trace) {
  if (!wasmModuleGlobal) throw new Error('WASM module not initialized');
  return wasmModuleGlobal.score_anomaly(dfgHandle.getId(), JSON.stringify(trace));
}
/**
 * Estimate the probability that a running case completes normally given its prefix.
 * Returns `{ coverage: number [0–1], matching_traces: number, normal_completions: number }`
 * @param logHandle - handle to a completed EventLog used as reference
 * @param prefix - activity prefix of the running case
 * @param activityKey - attribute key for the activity name
 */
export function computeBoundaryCoverage(logHandle, prefix, activityKey = 'concept:name') {
  if (!wasmModuleGlobal) throw new Error('WASM module not initialized');
  return wasmModuleGlobal.compute_boundary_coverage(
    logHandle.getId(),
    JSON.stringify(prefix),
    activityKey
  );
}
// ---------------------------------------------------------------------------
// Drift detection (answers "Has the process changed?")
// ---------------------------------------------------------------------------
/**
 * Detect where process behaviour shifts in an event log using a sliding window.
 * Returns `{ drifts_detected: number, drifts: [{position, distance, type}], window_size, method }`
 * @param logHandle - handle to an EventLog
 * @param activityKey - attribute key for the activity name
 * @param windowSize - number of traces per window (default 10)
 */
export function detectDrift(logHandle, activityKey = 'concept:name', windowSize = 10) {
  if (!wasmModuleGlobal) throw new Error('WASM module not initialized');
  return JSON.parse(wasmModuleGlobal.detect_drift(logHandle.getId(), activityKey, windowSize));
}
/**
 * Compute Exponential Moving Average over a numeric series.
 * Returns `{ smoothed: number[], trend: "rising"|"falling"|"stable", last_value: number }`
 * @param values - time-series of numeric values (e.g. throughput times)
 * @param alpha - smoothing factor in (0,1]; 0.3 is a good default
 */
export function computeEwma(values, alpha = 0.3) {
  if (!wasmModuleGlobal) throw new Error('WASM module not initialized');
  return JSON.parse(wasmModuleGlobal.compute_ewma(JSON.stringify(values), alpha));
}
// ---------------------------------------------------------------------------
// Feature extraction (answers "What describes this case?")
// ---------------------------------------------------------------------------
/**
 * Extract numeric features from a case prefix for ML or bandit models.
 * Returns `{ length, last_activity, unique_activities, rework_count, activity_frequency_entropy }`
 * @param prefix - array of activity names observed so far
 */
export function extractPrefixFeatures(prefix) {
  if (!wasmModuleGlobal) throw new Error('WASM module not initialized');
  return wasmModuleGlobal.extract_prefix_features_wasm(JSON.stringify(prefix));
}
/**
 * Count consecutive repeated activities (loops/rework) in a trace.
 * Returns `{ rework_count, rework_ratio, repeated_pairs: string[] }`
 * @param trace - array of activity names
 */
export function computeReworkScore(trace) {
  if (!wasmModuleGlobal) throw new Error('WASM module not initialized');
  return wasmModuleGlobal.compute_rework_score(JSON.stringify(trace));
}
/**
 * Build a transition probability graph (probabilistic DFG) from an event log.
 * Returns `{ edges: [{from, to, probability, count}], activities: string[] }`
 * @param logHandle - handle to an EventLog
 * @param activityKey - attribute key for the activity name
 */
export function buildTransitionProbabilities(logHandle, activityKey = 'concept:name') {
  if (!wasmModuleGlobal) throw new Error('WASM module not initialized');
  return wasmModuleGlobal.build_transition_probabilities(logHandle.getId(), activityKey);
}
// ---------------------------------------------------------------------------
// Resource & intervention (answers "What should we do?")
// ---------------------------------------------------------------------------
/**
 * Estimate average wait time using the M/M/1 queueing model.
 * Returns `{ wait_time: number, utilization: number, is_stable: boolean }`
 * @param arrivalRate - events arriving per unit time
 * @param serviceRate - events processed per unit time
 */
export function estimateQueueDelay(arrivalRate, serviceRate) {
  if (!wasmModuleGlobal) throw new Error('WASM module not initialized');
  return wasmModuleGlobal.estimate_queue_delay(arrivalRate, serviceRate);
}
/**
 * Rank intervention options using a greedy UCB-like heuristic.
 * Returns an array of `{ name, score, rank }` sorted by descending score.
 * @param interventions - array of `{ name: string, utility: number }` objects
 * @param exploitationWeight - 0–1; higher = favour top utility (default 0.7)
 */
export function rankInterventions(interventions, exploitationWeight = 0.7) {
  if (!wasmModuleGlobal) throw new Error('WASM module not initialized');
  return wasmModuleGlobal.rank_interventions(JSON.stringify(interventions), exploitationWeight);
}
/**
 * Select the next intervention using the UCB1 multi-armed bandit algorithm.
 * Returns `{ selected: string, arm_index, ucb_score, mean_reward, exploration_bonus }`
 * @param banditState - `{ arms: [{name, total_reward, pull_count}], total_pulls }`
 * @param explorationFactor - controls exploration vs exploitation (default √2 ≈ 1.414)
 */
export function selectIntervention(banditState, explorationFactor = Math.SQRT2) {
  if (!wasmModuleGlobal) throw new Error('WASM module not initialized');
  return wasmModuleGlobal.select_intervention(JSON.stringify(banditState), explorationFactor);
}
//# sourceMappingURL=client.js.map