rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
use crate::extensions::flow_state::{CasOutcome, FlowStore, flow_result};
use crate::imposter::ResponseMode;
use anyhow::{Result, anyhow};
use rhai::Dynamic;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;

// Engine modules (only used by proxy.rs for compilation)
mod bounded;
mod compiled_cache;
/// What scripts read as the time and as randomness (issue #1756).
pub(crate) mod env;
mod rhai_engine;
pub use bounded::{
    DEFAULT_SCRIPT_TIMEOUT_MS, ScriptTimeoutError, resolve_script_timeout_ms,
    should_inject_bounded, should_inject_bounded_with_ctx, should_inject_bounded_with_ctx_traced,
    should_inject_wasm, should_inject_wasm_traced,
};

// `engine: "wasm"` (issue #1751).
#[cfg(feature = "wasm")]
mod wasm;
/// The parts of a wasm call, apart, for `benches/script_engine_bench.rs` (issue #1760). Not an API.
#[cfg(feature = "wasm")]
#[doc(hidden)]
pub use wasm::bench as wasm_bench;

/// A `_rift.script` with `engine: "wasm"`, as one call needs it (issue #1751).
#[derive(Debug, Clone, Copy)]
pub struct WasmScript<'a> {
    /// The component's bytes, base64.
    pub code: &'a str,
    /// `_rift.script.export`: `"rift"` or `"http"` (issue #1758); `None` is `"rift"` when the
    /// component exports `rift:mock/handler`, else `"http"`.
    pub export: Option<&'a str>,
    /// `_rift.script.knobs`; `None` is `{}`.
    pub knobs: Option<&'a serde_json::Value>,
    /// `_rift.scriptEngine.wasm`.
    pub limits: crate::imposter::WasmLimits,
    /// What the component's `wasi:clocks` read (issue #1754); `None` is the system clock.
    pub clock: Option<&'a ScriptClock>,
    /// `_rift.script.instance` (issue #1793): `"request"` (`None`) for a fresh instance per call,
    /// `"imposter"` for one kept in `instances`.
    pub instance: Option<&'a str>,
    /// Where an `instance: "imposter"` component is kept: the imposter's. `None` runs it as
    /// `"request"` (a caller with no imposter).
    pub instances: Option<&'a WasmInstances>,
}

/// An imposter's kept `instance: "imposter"` wasm instances (issue #1793). Empty, and inert, in a
/// build without the `wasm` feature.
#[derive(Default)]
pub struct WasmInstances {
    #[cfg(feature = "wasm")]
    pub(crate) map: wasm::instances::InstanceMap,
}

impl std::fmt::Debug for WasmInstances {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WasmInstances").finish_non_exhaustive()
    }
}

impl WasmInstances {
    /// Whether no instance is kept.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        #[cfg(feature = "wasm")]
        {
            self.map.is_empty()
        }
        #[cfg(not(feature = "wasm"))]
        {
            true
        }
    }

    /// Drop every instance: `restart_runtime_state`.
    pub fn clear(&self) {
        #[cfg(feature = "wasm")]
        self.map.clear();
    }

    /// What `GET /imposters/:port/wasm/instances` reports.
    #[must_use]
    pub fn list(&self) -> Vec<WasmInstanceInfo> {
        #[cfg(feature = "wasm")]
        {
            self.map.list()
        }
        #[cfg(not(feature = "wasm"))]
        {
            Vec::new()
        }
    }

    /// Call `rift:mock/introspect.snapshot` on a live instance (issue #1794): `id` as
    /// [`Self::list`] gives it, or the only live one. `stubs` tells "no instance yet" from "no
    /// stub keeps one"; `flow_store` is the imposter's, which the guest reads but cannot write.
    #[cfg_attr(not(feature = "wasm"), allow(unused_variables, clippy::unused_async))]
    pub async fn snapshot<'s>(
        &self,
        id: Option<&str>,
        stubs: impl Iterator<Item = &'s crate::imposter::Stub>,
        flow_store: std::sync::Arc<dyn crate::extensions::flow_state::FlowStore>,
    ) -> Result<WasmSnapshot, WasmSnapshotError> {
        #[cfg(feature = "wasm")]
        {
            if self.map.is_empty() {
                // `RequestMode` only for an imposter whose wasm stubs are all `instance:
                // "request"`; with no wasm stub, or one that keeps an instance, there is simply
                // none live yet.
                let (mut wasm, mut keeps_one) = (false, false);
                for script in stubs
                    .flat_map(|stub| stub.responses.iter())
                    .filter_map(|response| match response {
                        crate::imposter::StubResponse::RiftScript { rift, .. } => {
                            rift.script.as_ref()
                        }
                        _ => None,
                    })
                {
                    wasm |= script.engine.as_deref() == Some("wasm");
                    keeps_one |= wasm::instances::key_of(script).is_some();
                }
                return Err(if wasm && !keeps_one {
                    WasmSnapshotError::RequestMode
                } else {
                    WasmSnapshotError::NotInstantiated
                });
            }
            wasm::instances::snapshot(&self.map, id, flow_store).await
        }
        #[cfg(not(feature = "wasm"))]
        {
            Err(WasmSnapshotError::Unavailable)
        }
    }

    /// Keep only the instances some stub in `stubs` still references (issue #1793): an edit that
    /// keeps a component referenced, by any stub, keeps its instance.
    #[cfg_attr(not(feature = "wasm"), allow(unused_variables))]
    pub(crate) fn retain_referenced<'s>(
        &self,
        stubs: impl Iterator<Item = &'s crate::imposter::Stub>,
    ) {
        #[cfg(feature = "wasm")]
        {
            if self.map.is_empty() {
                return;
            }
            let referenced: std::collections::HashSet<_> = stubs
                .flat_map(|stub| stub.responses.iter())
                .filter_map(|response| match response {
                    crate::imposter::StubResponse::RiftScript { rift, .. } => rift.script.as_ref(),
                    _ => None,
                })
                .filter_map(wasm::instances::key_of)
                .collect();
            self.map.retain(&referenced);
        }
    }
}

/// What `rift:mock/introspect.snapshot` returned (issue #1794).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WasmSnapshot {
    /// The guest's JSON text, byte for byte.
    pub body: String,
    /// The fuel the call spent.
    pub fuel_used: Option<u64>,
}

/// Why `GET /imposters/:port/wasm/snapshot` has no snapshot to give (issue #1794).
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum WasmSnapshotError {
    /// No `instance` was named and more than one is live: their ids.
    #[error("more than one wasm instance is live; name one with ?instance=<id> ({})", .0.join(", "))]
    Ambiguous(Vec<String>),
    /// The named instance, or any, is not live: none was made yet, or the last one was dropped.
    /// The route never instantiates, since that would run `init`.
    #[error("not instantiated")]
    NotInstantiated,
    /// The imposter's wasm stubs are all `instance: "request"`: their state is the flow store's.
    #[error("no live instance (instance: \"request\")")]
    RequestMode,
    /// The component does not export `rift:mock/introspect`.
    #[error("component does not export rift:mock/introspect")]
    NoExport,
    /// The guest returned `err`, or its export has the wrong type.
    #[error("{0}")]
    Guest(String),
    /// The guest returned text that is not JSON.
    #[error("snapshot is not JSON")]
    NotJson,
    /// The call trapped or missed its deadline; the instance was dropped.
    #[error("{0}")]
    Trap(String),
    /// Waiting for the instance passed `timeoutMs`.
    #[error("timed out waiting for the wasm instance")]
    Busy,
    /// A build without the `wasm` feature.
    #[error("engine \"wasm\" is not available in this build")]
    Unavailable,
}

/// One kept instance, as `GET /imposters/:port/wasm/instances` lists it (issue #1793).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WasmInstanceInfo {
    /// The SHA-256 of its key: the component, `export` and `knobs`.
    pub id: String,
    /// The component's SHA-256.
    pub sha256: String,
    /// `export` as the stubs write it.
    pub export: Option<String>,
    /// The first 12 hex digits of the SHA-256 of its canonical `knobs`.
    pub knobs_hash: String,
    /// When it was instantiated, in milliseconds since the Unix epoch.
    pub instantiated_at: u64,
    /// Calls it has answered since.
    pub calls: u64,
    /// The bytes of linear memory it holds.
    pub memory_bytes: usize,
}

/// What an `engine: "wasm"` call answered (issue #1758).
#[derive(Debug, Clone)]
pub enum WasmAnswer {
    /// `export: "rift"`: a decision, as Rhai and JavaScript return one.
    Decision(FaultDecision),
    /// `export: "http"`: the component's whole response.
    Response(WasmResponse),
}

/// An `export: "http"` component's response: bytes, and every header value it set.
#[derive(Debug, Clone)]
pub struct WasmResponse {
    pub status: u16,
    pub headers: hyper::HeaderMap,
    pub body: bytes::Bytes,
}

impl WasmAnswer {
    /// As a [`FaultDecision`], for a caller that serves only decisions (the generic
    /// `should_inject_bounded*` entry points). A response's body must be UTF-8, and a repeated
    /// header's values are joined with `", "`, as HTTP combines them.
    pub fn into_fault_decision(self, rule_id: &str) -> anyhow::Result<FaultDecision> {
        match self {
            Self::Decision(decision) => Ok(decision),
            Self::Response(response) => {
                let body = String::from_utf8(response.body.to_vec()).map_err(|_| {
                    anyhow::anyhow!(
                        "the component's response body is not UTF-8, which this caller cannot serve"
                    )
                })?;
                Ok(FaultDecision::Error {
                    status: response.status,
                    body,
                    rule_id: rule_id.to_owned(),
                    headers: joined_headers(&response.headers),
                })
            }
        }
    }
}

/// `headers` with each name once, its values joined with `", "`. A value that is not UTF-8 is
/// read lossily.
pub fn joined_headers(headers: &hyper::HeaderMap) -> std::collections::HashMap<String, String> {
    let mut joined: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    for (name, value) in headers {
        let value = String::from_utf8_lossy(value.as_bytes());
        joined
            .entry(name.as_str().to_owned())
            .and_modify(|v| {
                v.push_str(", ");
                v.push_str(&value);
            })
            .or_insert_with(|| value.into_owned());
    }
    joined
}

/// The time a script reads (issue #1754).
#[derive(Debug, Clone)]
pub enum ScriptClock {
    /// The imposter's clock, read at every use: a step taken while a script runs is seen.
    Imposter(std::sync::Arc<crate::imposter::clock::ImposterClock>),
    /// A fixed instant, in milliseconds since the Unix epoch: a request's `X-Rift-Now`.
    Fixed(i64),
}

impl ScriptClock {
    /// The current instant in milliseconds since the Unix epoch, or `None` for wall time.
    #[must_use]
    pub fn frozen_ms(&self) -> Option<i64> {
        match self {
            Self::Imposter(clock) => match clock.mode() {
                crate::imposter::clock::ClockMode::Wall => None,
                crate::imposter::clock::ClockMode::Frozen { now_ms } => Some(now_ms),
            },
            Self::Fixed(ms) => Some(*ms),
        }
    }
}

pub use rhai_engine::RhaiEngine;
pub(crate) use rhai_engine::values_map_to_rhai;

/// A Rhai engine with file modules turned off (issue #1611): an `import` statement resolves
/// nothing, on every door. Rhai's default resolver loads any `.rhai` file on the host; `import`
/// was never documented, and confining it would need a per-imposter resolver through the shared
/// script pool. Every Rhai engine Rift builds comes from here.
pub(crate) fn rift_rhai_engine() -> rhai::Engine {
    let mut engine = rhai::Engine::new();
    engine.set_module_resolver(rhai::module_resolvers::DummyModuleResolver::new());
    engine
}

// Script pool for optimized execution

#[cfg(feature = "javascript")]
mod js_engine;
#[cfg(feature = "javascript")]
mod js_runtime;
/// Exposed so other modules (e.g. `behaviors::wait`) that run a standalone JS snippet outside the
/// MB inject/predicate/decorate hooks still get the same interpreter-level guards (issue #355
/// Items 3/6) rather than an unbounded `Context::default()`.
#[cfg(feature = "javascript")]
pub(crate) use js_engine::bounded_js_context;
#[cfg(feature = "javascript")]
pub use js_engine::{
    InjectionFailure, JsEngine, MountebankRequest, PredicateInjectionError, compile_js_to_bytecode,
    execute_mountebank_decorate, execute_mountebank_decorate_bounded,
    execute_mountebank_decorate_within, execute_mountebank_inject,
    execute_mountebank_inject_bounded, execute_predicate_generator_inject,
    execute_predicate_inject,
};
#[cfg(feature = "javascript")]
#[allow(unused_imports)]
pub use js_engine::{MountebankInjectResponse, execute_js_bytecode};

/// One imposter's script-state map behind its own lock (issue #477).
pub(crate) type ScriptStateCell =
    std::sync::Arc<parking_lot::Mutex<serde_json::Map<String, serde_json::Value>>>;

/// The imposter a script run belongs to (issue #1726): the port its logger and host globals name,
/// and the script `state` its inject, decorate and predicate inject read and write.
///
/// The state belongs to one imposter instance, as Mountebank's `imposterState` belongs to one
/// imposter object. A run that outlives its imposter's delete writes into that imposter's cell,
/// never into the one an imposter re-created on the same port starts with. The runs of one
/// imposter all execute on one MB pool worker while any is in flight, sharing one live JS `state`
/// object built from the cell and saved back to it as each run ends (issue #1678): they interleave
/// at `await`s as in Mountebank, a synchronous section never interleaves with another, and no
/// update is lost (issue #477). The cell's lock is held only to seed and save the live object.
#[derive(Clone)]
pub struct ScriptScope {
    pub port: u16,
    #[cfg_attr(not(feature = "javascript"), allow(dead_code))]
    pub(crate) state: ScriptStateCell,
    /// The state cell's probe (`formal/scripting`), `None` in production. It rides the scope since
    /// the MB script pool is process-global: a run belongs to no manager the pool could ask.
    #[cfg_attr(not(feature = "javascript"), allow(dead_code))]
    pub(crate) probe: crate::imposter::probe::ProbeHandle,
}

impl std::fmt::Debug for ScriptScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScriptScope")
            .field("port", &self.port)
            .field("state", &self.state)
            .finish_non_exhaustive()
    }
}

impl ScriptScope {
    pub(crate) fn new(port: u16, state: ScriptStateCell) -> Self {
        Self {
            port,
            state,
            probe: None,
        }
    }

    /// This scope with a state cell probe (`formal/scripting/README.md`). For tests: nothing
    /// installs one in production.
    #[must_use]
    pub fn with_probe(mut self, probe: std::sync::Arc<dyn crate::imposter::Probe>) -> Self {
        self.probe = Some(probe);
        self
    }

    /// A scope with its own empty state, for a run no imposter owns, such as a test.
    #[must_use]
    pub fn detached(port: u16) -> Self {
        Self::new(port, ScriptStateCell::default())
    }

    /// The scope of a standalone match ([`stub_matches`](crate::imposter::stub_matches) and
    /// [`predicate_matches`](crate::imposter::predicate_matches), which intercept rules use): one
    /// state per port, kept for the life of the process, as every script state was before #1726.
    pub(crate) fn standalone(port: u16) -> Self {
        static STANDALONE: std::sync::LazyLock<
            parking_lot::Mutex<std::collections::HashMap<u16, ScriptStateCell>>,
        > = std::sync::LazyLock::new(Default::default);
        let state = std::sync::Arc::clone(STANDALONE.lock().entry(port).or_default());
        Self::new(port, state)
    }
}

// Validator trait and unified error types
mod validator;
#[allow(unused_imports)]
pub use validator::ScriptValidationError;
pub use validator::ScriptValidator;

// Validator modules - used by config validation and stub_validator
mod rhai_validator;
#[allow(unused_imports)]
pub use rhai_validator::RhaiValidationError;
pub use rhai_validator::RhaiValidator;

#[cfg(feature = "javascript")]
mod js_validator;
#[cfg(feature = "javascript")]
#[allow(unused_imports)]
pub use js_validator::JsValidationError;
#[cfg(feature = "javascript")]
pub use js_validator::JsValidator;

// Stub script validation for Admin API
mod stub_validator;
pub use stub_validator::{validate_stub, validate_stubs};

// Static entrypoint/arity checking, for `rift script check` (issue #360)
mod entrypoint_check;
pub use entrypoint_check::{EntrypointCheckError, EntrypointMatch, check_entrypoint};

// Script decision/log tracing, for `rift script run` and the debug-mode per-request trace
// (issue #360)
mod trace;
#[cfg(test)]
pub(crate) use trace::keep_scoped_captures_visible;
pub use trace::{ScriptTraceEntry, cap_trace_logs, capture_script_logs, render_decision};

/// Failure of a `predicateGenerators.inject` pass during proxy recording (issue #498).
///
/// Distinguishes "predicates could NOT be generated" (infrastructure, script, or malformed
/// output) from a generator legitimately returning an empty list. Without this distinction the
/// proxy-recording path collapsed every failure to an empty predicate list and silently recorded
/// a match-all stub; carrying the failure as an error lets the caller skip auto-stub creation.
/// Defined unconditionally so the proxy signature resolves without the `javascript` feature.
#[derive(Debug, thiserror::Error)]
pub enum PredicateGeneratorError {
    /// The MB script pool could not run the generator (infrastructure failure).
    #[error("script pool failure: {0}")]
    Pool(String),
    /// The generator script errored while executing.
    #[error("script execution error: {0}")]
    Script(String),
    /// The generator script threw (issue #1580). `message` is what Mountebank reports as the
    /// error's `data`: the thrown value's `message`, `None` when it has none (`throw 'text'`).
    /// `detail` is the engine's full rendering, with position and stack, for the log.
    #[error("script execution error: {detail}")]
    Threw {
        message: Option<String>,
        detail: String,
    },
    /// The generator ran but did not return a usable predicate array.
    #[error("generator produced invalid output: {0}")]
    Output(String),
    /// A generated predicate does not decode, or the engine would refuse it at a config door
    /// (issue #1353). Recording it would drop it, or write a stub the engine cannot re-import.
    #[error("generated predicate is invalid: {0}")]
    Invalid(String),
    /// A generator's `xpath` selector failed to evaluate on an XML body (issue #1668). Mountebank's
    /// `xpathSelect` throws while recording, so the proxied request fails with `500 malformed
    /// xpath predicate selector`, not with the `x-rift-generator-error` header.
    #[error(transparent)]
    Selector(#[from] crate::behaviors::XPathSelectorError),
}

impl PredicateGeneratorError {
    /// Short, stable, header-safe token for the `x-rift-generator-error` response header (the full
    /// detail goes to the server log, not to the client). It marks the `500` a failed recording
    /// answers (issue #1708), except `invalid-predicate`, which marks the upstream response served
    /// instead.
    #[must_use]
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Pool(_) => "pool-failure",
            Self::Script(_) | Self::Threw { .. } => "script-error",
            Self::Output(_) => "invalid-output",
            Self::Invalid(_) => "invalid-predicate",
            // For logs only: the request fails with a 500 instead of carrying the header.
            Self::Selector(_) => "selector-error",
        }
    }
}

/// Script execution result for fault injection decisions
#[derive(Debug, Clone)]

pub enum FaultDecision {
    None,
    Latency {
        duration_ms: u64,
        rule_id: String,
    },
    Error {
        status: u16,
        body: String,
        rule_id: String,
        headers: std::collections::HashMap<String, String>,
    },
    /// Connection reset, requested via the v2 `reset()` result constructor (issue #357 Item 3) —
    /// the scripting analogue of the Mountebank-compatible `_rift.fault.tcp` / top-level `fault`
    /// carrier (see `imposter::fault_io::TcpFaultKind`). Callers apply it the same way: attach
    /// `TcpFaultKind::Reset` to a carrier response's extensions so the serve loop's `FaultIo`
    /// aborts the connection instead of framing a clean HTTP response.
    Reset {
        rule_id: String,
    },
}

/// Everything about the calling stub thread into `ctx.stub` (issue #357 Item 1). Fields are
/// `None` where unavailable, mirroring P1's `stub_id` contract (issue #355).
#[derive(Debug, Clone, Default)]
pub struct ScriptStubContext {
    pub scenario_name: Option<String>,
    pub scenario_state: Option<String>,
    pub stub_id: Option<String>,
}

/// Everything the shared `ctx` builder (issue #357 Item 1) needs, engine-agnostic. Each engine
/// (`rhai_engine`, `js_engine`) turns this into its own native `ctx` value; the
/// field names/semantics are identical across engines by contract — keep them that way.
#[derive(Debug, Clone)]
pub struct ScriptCtxInput<'a> {
    pub request: &'a ScriptRequest,
    pub flow_id: String,
    pub stub: ScriptStubContext,
    /// Imposter port, used only to tag `ctx.logger` output; 0 when not running under an imposter
    /// (e.g. the proxy path, or a bare `ScriptEngine::should_inject_fault` call in tests).
    pub port: u16,
}

impl<'a> ScriptCtxInput<'a> {
    pub fn new(request: &'a ScriptRequest, flow_id: impl Into<String>) -> Self {
        Self {
            request,
            flow_id: flow_id.into(),
            stub: ScriptStubContext::default(),
            port: 0,
        }
    }

    #[must_use]
    pub fn with_stub(mut self, stub: ScriptStubContext) -> Self {
        self.stub = stub;
        self
    }

    #[must_use]
    pub fn with_port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }
}

/// Extra, optional context a caller can thread into `ctx` beyond the bare `(request, flow_store)`
/// pair (issue #357 Item 1). Callers with no imposter context (the proxy path, direct engine unit
/// tests) use `Default`, which falls back to `request.headers["x-flow-id"]` (or `""`) for
/// `ctx.flowId` and leaves `ctx.stub` fields `None` — the real HTTP path
/// (`imposter::handler`) supplies the resolved flow id and stub metadata for full fidelity.
#[derive(Debug, Clone, Default)]
pub struct ScriptCtxExtras {
    pub flow_id: Option<String>,
    pub stub: ScriptStubContext,
    pub port: u16,
    /// The query string as the client sent it, without `?` (issue #1758): an `export: "http"`
    /// component sees it unchanged. `None` encodes the parsed pairs again.
    pub raw_query: Option<String>,
    /// Whether the request arrived over TLS: the scheme an `export: "http"` component sees.
    pub https: bool,
}

impl ScriptCtxExtras {
    pub fn build_ctx_input<'a>(&self, request: &'a ScriptRequest) -> ScriptCtxInput<'a> {
        let flow_id = self.flow_id.clone().unwrap_or_else(|| {
            request
                .headers
                .iter()
                .find(|(k, _)| k.eq_ignore_ascii_case("x-flow-id"))
                // A repeated `x-flow-id` names its flow by the first value, as predicates read it.
                .and_then(|(_, v)| v.first().cloned())
                .unwrap_or_default()
        });
        ScriptCtxInput::new(request, flow_id)
            .with_stub(self.stub.clone())
            .with_port(self.port)
    }
}

/// A `respond`/bare-expression return value that isn't a string or a JSON-shaped value (issue
/// #357 Item 3 — body values). `http(status, body)` decides which of these to serialize based on
/// the script value's own type: a string passes through verbatim; a map/array is JSON-serialized.
#[derive(Debug, Clone)]
pub enum ScriptResultBody {
    Json(Value),
    Str(String),
}

/// The v2 result constructors (issue #357 Item 3), engine-agnostic: `http()`/`delay()`/`reset()`/
/// `pass()` all build one of these, which `into_fault_decision` then turns into the
/// [`FaultDecision`] the caller applies. Each engine wraps this in its own native "builder" value
/// so `.header(k, v)` can chain.
#[derive(Debug, Clone)]
pub enum ScriptResult {
    /// `pass()` or a script returning nothing: respond normally, no injection.
    Pass,
    /// `delay(ms)`.
    Delay(u64),
    /// `reset()`: connection reset (the old `fault: "tcp"` shape).
    Reset,
    /// `http(status, body?)`, with zero or more `.header(k, v)` calls applied.
    Http {
        status: u16,
        body: Option<ScriptResultBody>,
        headers: Vec<(String, String)>,
    },
}

impl ScriptResult {
    pub fn http(status: u16, body: Option<ScriptResultBody>) -> Self {
        ScriptResult::Http {
            status,
            body,
            headers: Vec::new(),
        }
    }

    /// Apply a `.header(k, v)` builder call. A no-op on `Delay`/`Reset`/`Pass` — only `http()`
    /// results carry headers.
    pub fn add_header(&mut self, key: String, value: String) {
        if let ScriptResult::Http { headers, .. } = self {
            headers.push((key, value));
        }
    }

    /// Convert a result constructor (issue #357 Item 3) into the [`FaultDecision`] the caller
    /// applies. A JSON `body` gets `Content-Type: application/json` UNLESS the script already set
    /// a `content-type` header itself (case-insensitive match; an explicit header always wins).
    pub fn into_fault_decision(self, rule_id: &str) -> FaultDecision {
        match self {
            ScriptResult::Pass => FaultDecision::None,
            ScriptResult::Delay(duration_ms) => FaultDecision::Latency {
                duration_ms,
                rule_id: rule_id.to_string(),
            },
            ScriptResult::Reset => FaultDecision::Reset {
                rule_id: rule_id.to_string(),
            },
            ScriptResult::Http {
                status,
                body,
                headers,
            } => {
                let mut header_map: HashMap<String, String> = HashMap::new();
                let mut has_content_type = false;
                for (k, v) in headers {
                    if k.eq_ignore_ascii_case("content-type") {
                        has_content_type = true;
                    }
                    header_map.insert(k, v);
                }
                let body_str = match body {
                    None => String::new(),
                    Some(ScriptResultBody::Str(s)) => s,
                    Some(ScriptResultBody::Json(v)) => {
                        if !has_content_type {
                            header_map
                                .insert("Content-Type".to_string(), "application/json".to_string());
                        }
                        serde_json::to_string(&v).unwrap_or_default()
                    }
                };
                FaultDecision::Error {
                    status,
                    body: body_str,
                    rule_id: rule_id.to_string(),
                    headers: header_map,
                }
            }
        }
    }
}

/// Name of the v2 named entrypoint (issue #357 Items 2/4): a `respond` hook calls a function
/// named `respond`, if one is declared, else evaluates the script as a bare expression.
///
/// `respond` is the only entrypoint either engine dispatches. #357 landed the vocabulary for
/// `matches`/`transform`/`delay` too, but nothing ever wired them, so #1001 removed those names
/// rather than keep advertising hooks the runtime ignores. Predicate scripting is Mountebank
/// `inject`; response rewriting is the `decorate`/`shellTransform` behaviors.
pub mod entrypoints {
    pub const RESPOND: &str = "respond";
}

/// A script engine as `_rift.script.engine`, `defaultEngine`, a `file:` extension or
/// `rift script --engine` names it, parsed once here so every site shares one allowlist and one
/// set of messages (issue #1750). The wire type stays a string: an unknown engine still decodes and
/// fails at admission or when served, so stored configs keep replaying.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScriptEngineKind {
    Rhai,
    JavaScript,
    Wasm,
}

/// Why an engine name names no engine.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum EngineNameError {
    /// `lua`, an engine Rift had and removed.
    #[error(
        "the Lua scripting engine was removed (issue #450); use engine \"rhai\" or \"javascript\""
    )]
    Removed,
    /// Any other name.
    #[error("Unknown script engine type: {0}")]
    Unknown(String),
}

impl ScriptEngineKind {
    /// The engine `name` names: `rhai`, `javascript` (or its alias `js`) or `wasm`.
    pub fn parse(name: &str) -> Result<Self, EngineNameError> {
        match name {
            "rhai" => Ok(Self::Rhai),
            "javascript" | "js" => Ok(Self::JavaScript),
            "wasm" => Ok(Self::Wasm),
            "lua" => Err(EngineNameError::Removed),
            other => Err(EngineNameError::Unknown(other.to_owned())),
        }
    }

    /// The canonical name, `javascript` for the `js` alias.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Rhai => "rhai",
            Self::JavaScript => "javascript",
            Self::Wasm => "wasm",
        }
    }

    /// Whether `name` names the wasm engine.
    #[must_use]
    pub fn is_wasm(name: &str) -> bool {
        matches!(Self::parse(name), Ok(Self::Wasm))
    }

    /// The engine a script file's extension names: `None` for an extension that names none, and
    /// `Removed` for `.lua`.
    pub fn from_extension(ext: &str) -> Option<Result<Self, EngineNameError>> {
        match ext {
            "rhai" => Some(Ok(Self::Rhai)),
            "js" => Some(Ok(Self::JavaScript)),
            "wasm" => Some(Ok(Self::Wasm)),
            "lua" => Some(Err(EngineNameError::Removed)),
            _ => None,
        }
    }
}

/// Admit a component (base64) as `_rift.script` admission does, returning what it imports (issue
/// #1757's upload).
#[cfg(feature = "wasm")]
pub(crate) fn wasm_admit_imports(code: &str) -> Result<Vec<String>, String> {
    wasm::admit_imports(code).map_err(|e| e.to_string())
}

/// Admit a component (base64) under `export` (`"rift"`, `"http"` or `None`), as `_rift.script`
/// admission does (issues #1751, #1758), and return the export that answers: `"rift"` or `"http"`.
/// Without the `wasm` feature, every component is refused.
pub fn admit_wasm_component(code: &str, export: Option<&str>) -> Result<&'static str, String> {
    #[cfg(feature = "wasm")]
    {
        wasm::admit_export(code, export).map_err(|e| e.to_string())
    }
    #[cfg(not(feature = "wasm"))]
    {
        let _ = (code, export);
        Err(WASM_UNAVAILABLE.to_owned())
    }
}

/// The message `wasm` gets in a build without the `wasm` feature (issue #1751).
#[cfg_attr(feature = "wasm", allow(dead_code))]
pub(crate) const WASM_UNAVAILABLE: &str = "engine \"wasm\" is not available in this build";

/// Unified script engine that supports Rhai and JavaScript
#[derive(Clone)]

pub enum ScriptEngine {
    Rhai(RhaiEngine),
    #[cfg(feature = "javascript")]
    JavaScript(JsEngine),
}

impl ScriptEngine {
    /// Create a new script engine based on the engine type
    pub fn new(engine_type: &str, script: &str, rule_id: &str) -> Result<Self> {
        match ScriptEngineKind::parse(engine_type)? {
            ScriptEngineKind::Rhai => Ok(ScriptEngine::Rhai(RhaiEngine::new(script, rule_id)?)),
            #[cfg(feature = "javascript")]
            ScriptEngineKind::JavaScript => {
                Ok(ScriptEngine::JavaScript(JsEngine::new(script, rule_id)?))
            }
            #[cfg(not(feature = "javascript"))]
            ScriptEngineKind::JavaScript => Err(anyhow!(
                "JavaScript engine is not enabled. Enable the 'javascript' feature flag"
            )),
            #[cfg(not(feature = "wasm"))]
            ScriptEngineKind::Wasm => Err(anyhow!(WASM_UNAVAILABLE)),
            // A component runs on the request task, not through this synchronous engine.
            #[cfg(feature = "wasm")]
            ScriptEngineKind::Wasm => Err(anyhow!(
                "engine \"wasm\" runs only as a `_rift.script` response"
            )),
        }
    }

    /// Execute the `respond(ctx)` entrypoint (or bare-expression script) and determine if a fault
    /// should be injected. `ctx` gets best-effort defaults ([`ScriptCtxExtras::default`]) —
    /// callers with real flow-id/stub context should use [`Self::should_inject_fault_with_ctx`]
    /// instead.
    pub fn should_inject_fault(
        &self,
        request: &ScriptRequest,
        flow_store: Arc<dyn FlowStore>,
    ) -> Result<FaultDecision> {
        self.should_inject_fault_with_ctx(request, flow_store, &ScriptCtxExtras::default())
    }

    /// As [`Self::should_inject_fault`], but with real `ctx.flowId`/`ctx.stub` context (issue
    /// #357 Item 1) — used by the imposter `_rift.script` hook, which knows the resolved flow id
    /// and matched stub.
    pub fn should_inject_fault_with_ctx(
        &self,
        request: &ScriptRequest,
        flow_store: Arc<dyn FlowStore>,
        extra: &ScriptCtxExtras,
    ) -> Result<FaultDecision> {
        match self {
            ScriptEngine::Rhai(engine) => {
                engine.should_inject_fault_with_ctx(request, flow_store, extra)
            }
            #[cfg(feature = "javascript")]
            ScriptEngine::JavaScript(engine) => {
                engine.should_inject_with_ctx(request, flow_store, extra)
            }
        }
    }
}

/// Request context passed to scripts
#[derive(Debug, Clone)]

pub struct ScriptRequest {
    pub method: String,
    pub path: String,
    /// In the order the client sent them (issue #1606), every value: a script sees a repeated
    /// header as an array, a single one as a string (issue #1629).
    pub headers: crate::util::MultiValueMap,
    pub body: Value,
    /// Query parameters parsed from the URL, in request order (issue #1596), every value of a
    /// repeated key (issue #1629).
    pub query: crate::util::MultiValueMap,
    /// Path parameters extracted from route patterns (e.g., /users/:id)
    pub path_params: HashMap<String, String>,
    /// The raw request body text, exactly as received (issue #357 Item 1: `ctx.request.body` is
    /// always the raw string, unifying the old split where the Mountebank path kept a raw string
    /// and the `_rift.script` path kept parsed JSON). `None` when the caller only has/derives a
    /// parsed `body`; ctx-building then falls back to re-serializing `body` (loses exact
    /// whitespace but not shape) so callers migrated ad hoc from `body` alone still work.
    pub raw_body: Option<String>,
    /// Whether `raw_body` is UTF-8 text or a base64-encoded binary body (issue #636). Mirrors
    /// `ResponseMode`/`_mode` on the response side so scripts can tell which they got instead of
    /// silently treating base64 as text.
    pub mode: ResponseMode,
}

/// Wrapper for FlowStore that can be used in scripts (Rhai and JavaScript)
/// Uses direct synchronous calls since FlowStore is no longer async
///
/// Every op is unconditionally fail-loud (issues #322/#358): a backend failure always raises a
/// script error, so a store outage is never conflated with "absent"/"false"/"0".
#[derive(Clone)]
pub struct ScriptFlowStore {
    store: Arc<dyn FlowStore>,
}

impl ScriptFlowStore {
    /// The `ctx.state` handle.
    pub fn new(store: Arc<dyn FlowStore>) -> Self {
        Self { store }
    }

    /// Get a value from flow state. Raises on a backend failure.
    pub fn get(
        &mut self,
        flow_id: String,
        key: String,
    ) -> std::result::Result<Dynamic, Box<rhai::EvalAltResult>> {
        match flow_result("get", self.store.get(&flow_id, &key)) {
            Ok(Some(val)) => Ok(rhai_engine::json_to_dynamic(val)),
            Ok(None) => Ok(Dynamic::UNIT),
            Err(msg) => Err(msg.into()),
        }
    }

    /// Set a value in flow state. Raises on a backend failure.
    pub fn set(
        &mut self,
        flow_id: String,
        key: String,
        value: Dynamic,
    ) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
        let json_val = rhai_engine::dynamic_to_json(value);
        match flow_result(
            "set",
            self.store.set(&flow_id, &key, json_val).map(|()| true),
        ) {
            Ok(v) => Ok(v),
            Err(msg) => Err(msg.into()),
        }
    }

    /// Check if a key exists. Raises on a backend failure.
    pub fn exists(
        &mut self,
        flow_id: String,
        key: String,
    ) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
        match flow_result("exists", self.store.exists(&flow_id, &key)) {
            Ok(v) => Ok(v),
            Err(msg) => Err(msg.into()),
        }
    }

    /// Delete a key. Raises on a backend failure.
    pub fn delete(
        &mut self,
        flow_id: String,
        key: String,
    ) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
        match flow_result("delete", self.store.delete(&flow_id, &key).map(|()| true)) {
            Ok(v) => Ok(v),
            Err(msg) => Err(msg.into()),
        }
    }

    /// Increment a counter. Raises on a backend failure.
    pub fn increment(
        &mut self,
        flow_id: String,
        key: String,
    ) -> std::result::Result<i64, Box<rhai::EvalAltResult>> {
        match flow_result("increment", self.store.increment(&flow_id, &key)) {
            Ok(v) => Ok(v),
            Err(msg) => Err(msg.into()),
        }
    }

    /// Set TTL for a flow. Raises on a backend failure.
    pub fn set_ttl(
        &mut self,
        flow_id: String,
        ttl_seconds: i64,
    ) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
        match flow_result(
            "setTtl",
            self.store.set_ttl(&flow_id, ttl_seconds).map(|()| true),
        ) {
            Ok(v) => Ok(v),
            Err(msg) => Err(msg.into()),
        }
    }

    /// Take (read and clear) the last flow-store op error for this thread, or unit if the
    /// last op succeeded (issue #322).
    pub fn last_error(&mut self) -> Dynamic {
        match crate::extensions::flow_state::take_last_flow_error() {
            Some(msg) => Dynamic::from(msg),
            None => Dynamic::UNIT,
        }
    }

    // ============================================================
    // Atomic ops + ergonomic getters. Like the ops above, these ALWAYS raise a script error on a
    // backend failure — a store outage must never be conflated with "key absent"/"conflict".
    // ============================================================

    /// Get a value, or `default` if the key is absent. A store failure always raises.
    pub fn get_or(
        &mut self,
        flow_id: String,
        key: String,
        default: Dynamic,
    ) -> std::result::Result<Dynamic, Box<rhai::EvalAltResult>> {
        match flow_result("getOr", self.store.get(&flow_id, &key)) {
            Ok(Some(val)) => Ok(rhai_engine::json_to_dynamic(val)),
            Ok(None) => Ok(default),
            Err(msg) => Err(msg.into()),
        }
    }

    /// Atomically increment by `by`, starting at 0 when absent. Always fail-loud.
    pub fn increment_by(
        &mut self,
        flow_id: String,
        key: String,
        by: i64,
    ) -> std::result::Result<i64, Box<rhai::EvalAltResult>> {
        flow_result("incrementBy", self.store.increment_by(&flow_id, &key, by)).map_err(Into::into)
    }

    /// Atomic compare-and-set (issues #358, #311): `key` is set to `new` iff its current value
    /// equals `expected` (unit means "not present"). Returns the raw [`CasOutcome`]; the caller
    /// (the Rhai-specific `RhaiStateHandle`) converts it to the engine's object-map return shape.
    /// Always fail-loud.
    pub fn cas(
        &mut self,
        flow_id: String,
        key: String,
        expected: Dynamic,
        new: Dynamic,
    ) -> std::result::Result<CasOutcome, Box<rhai::EvalAltResult>> {
        let expected_json = if expected.is_unit() {
            None
        } else {
            Some(rhai_engine::dynamic_to_json(expected))
        };
        let new_json = rhai_engine::dynamic_to_json(new);
        flow_result(
            "cas",
            self.store
                .compare_and_set(&flow_id, &key, expected_json.as_ref(), new_json),
        )
        .map_err(Into::into)
    }

    /// Set a per-flow TTL override. Always fail-loud.
    pub fn ttl(
        &mut self,
        flow_id: String,
        ttl_seconds: i64,
    ) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
        flow_result(
            "ttl",
            self.store.set_ttl(&flow_id, ttl_seconds).map(|()| true),
        )
        .map_err(Into::into)
    }

    /// Set a per-key TTL override (issue #530). Returns `true` if the key existed, `false` if
    /// absent; `ttl_seconds <= 0` deletes the key. Always fail-loud.
    pub fn key_ttl(
        &mut self,
        flow_id: String,
        key: String,
        ttl_seconds: i64,
    ) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
        flow_result(
            "keyTtl",
            self.store.set_key_ttl(&flow_id, &key, ttl_seconds),
        )
        .map_err(Into::into)
    }

    /// Remove every key in a flow (issue #530). Returns `true`. Always fail-loud.
    pub fn clear(
        &mut self,
        flow_id: String,
    ) -> std::result::Result<bool, Box<rhai::EvalAltResult>> {
        flow_result("clear", self.store.clear_flow(&flow_id).map(|()| true)).map_err(Into::into)
    }
}

#[cfg(test)]
mod tests {
    // #1750: one parse for every engine name.
    #[test]
    fn engine_names_parse_once() {
        use super::{EngineNameError, ScriptEngineKind};
        assert_eq!(ScriptEngineKind::parse("rhai"), Ok(ScriptEngineKind::Rhai));
        assert_eq!(
            ScriptEngineKind::parse("javascript"),
            Ok(ScriptEngineKind::JavaScript)
        );
        assert_eq!(
            ScriptEngineKind::parse("js"),
            Ok(ScriptEngineKind::JavaScript)
        );
        assert_eq!(ScriptEngineKind::parse("wasm"), Ok(ScriptEngineKind::Wasm));
        assert_eq!(
            ScriptEngineKind::parse("lua"),
            Err(EngineNameError::Removed)
        );
        assert_eq!(
            ScriptEngineKind::parse("cobol"),
            Err(EngineNameError::Unknown("cobol".to_owned()))
        );
        assert_eq!(ScriptEngineKind::JavaScript.as_str(), "javascript");
        assert_eq!(ScriptEngineKind::Rhai.as_str(), "rhai");
        assert_eq!(ScriptEngineKind::Wasm.as_str(), "wasm");
        assert_eq!(
            EngineNameError::Removed.to_string(),
            "the Lua scripting engine was removed (issue #450); use engine \"rhai\" or \"javascript\""
        );
        assert_eq!(
            EngineNameError::Unknown("cobol".to_owned()).to_string(),
            "Unknown script engine type: cobol"
        );
    }

    #[test]
    fn engine_names_from_extensions() {
        use super::{EngineNameError, ScriptEngineKind};
        assert_eq!(
            ScriptEngineKind::from_extension("rhai"),
            Some(Ok(ScriptEngineKind::Rhai))
        );
        assert_eq!(
            ScriptEngineKind::from_extension("js"),
            Some(Ok(ScriptEngineKind::JavaScript))
        );
        assert_eq!(
            ScriptEngineKind::from_extension("wasm"),
            Some(Ok(ScriptEngineKind::Wasm))
        );
        assert_eq!(
            ScriptEngineKind::from_extension("lua"),
            Some(Err(EngineNameError::Removed))
        );
        assert_eq!(ScriptEngineKind::from_extension("txt"), None);
    }

    // Without the `wasm` feature, `wasm` parses and is refused with its own message, not as an
    // unknown engine.
    #[cfg(not(feature = "wasm"))]
    #[test]
    fn wasm_is_refused_as_unavailable() {
        let err = super::ScriptEngine::new("wasm", "x", "r")
            .err()
            .expect("refused");
        assert_eq!(
            err.to_string(),
            "engine \"wasm\" is not available in this build"
        );
    }

    use super::*;
    use crate::extensions::flow_state::NoOpFlowStore;
    use serde_json::json;
    use std::collections::HashMap;

    /// A flow store whose every op fails — for exercising the error branches of the wrappers.
    struct FailingStore;
    impl FlowStore for FailingStore {
        fn get(&self, _: &str, _: &str) -> Result<Option<Value>> {
            Err(anyhow!("boom"))
        }
        fn set(&self, _: &str, _: &str, _: Value) -> Result<()> {
            Err(anyhow!("boom"))
        }
        fn exists(&self, _: &str, _: &str) -> Result<bool> {
            Err(anyhow!("boom"))
        }
        fn delete(&self, _: &str, _: &str) -> Result<()> {
            Err(anyhow!("boom"))
        }
        fn increment(&self, _: &str, _: &str) -> Result<i64> {
            Err(anyhow!("boom"))
        }
        fn set_ttl(&self, _: &str, _: i64) -> Result<()> {
            Err(anyhow!("boom"))
        }
        fn set_key_ttl(&self, _: &str, _: &str, _: i64) -> Result<bool> {
            Err(anyhow!("boom"))
        }
        fn clear_flow(&self, _: &str) -> Result<()> {
            Err(anyhow!("boom"))
        }
    }

    // Every ScriptFlowStore op, on a backend failure, raises a script error AND records the
    // error for `last_error()` (issue #322). Covers all six ops — a wrong result in any one
    // would be caught here.
    #[test]
    fn rhai_flow_store_ops_fail_loud_and_record_error() {
        use crate::extensions::flow_state::take_last_flow_error;
        let mut s = ScriptFlowStore::new(Arc::new(FailingStore));

        let _ = take_last_flow_error();
        assert!(
            s.get("f".into(), "k".into()).is_err(),
            "get must raise on a backend failure"
        );
        assert!(
            take_last_flow_error().is_some_and(|e| e.contains("get")),
            "get records last_error"
        );

        assert!(
            s.set("f".into(), "k".into(), Dynamic::from(1)).is_err(),
            "set must raise on a backend failure"
        );
        assert!(take_last_flow_error().is_some_and(|e| e.contains("set")));

        assert!(
            s.exists("f".into(), "k".into()).is_err(),
            "exists must raise on a backend failure"
        );
        assert!(take_last_flow_error().is_some_and(|e| e.contains("exists")));

        assert!(
            s.delete("f".into(), "k".into()).is_err(),
            "delete must raise on a backend failure"
        );
        assert!(take_last_flow_error().is_some_and(|e| e.contains("delete")));

        assert!(
            s.increment("f".into(), "k".into()).is_err(),
            "increment must raise on a backend failure"
        );
        assert!(take_last_flow_error().is_some_and(|e| e.contains("increment")));

        assert!(
            s.set_ttl("f".into(), 60).is_err(),
            "set_ttl must raise on a backend failure"
        );
        assert!(take_last_flow_error().is_some_and(|e| e.contains("setTtl")));

        // Issue #530: the per-key ttl and clear ops are fail-loud too.
        assert!(
            s.key_ttl("f".into(), "k".into(), 60).is_err(),
            "key_ttl must raise on a backend failure"
        );
        assert!(take_last_flow_error().is_some_and(|e| e.contains("keyTtl")));

        assert!(
            s.clear("f".into()).is_err(),
            "clear must raise on a backend failure"
        );
        assert!(take_last_flow_error().is_some_and(|e| e.contains("clear")));
    }

    // AC2 (issue #322): the Rhai flow_store.last_error() accessor surfaces the last recorded
    // backend error (then leaves the slot taken so a following op reflects its own status).
    #[test]
    fn rhai_flow_store_last_error_surfaces() {
        use crate::extensions::flow_state::{log_flow_err, take_last_flow_error};
        let _ = take_last_flow_error();
        let mut s = ScriptFlowStore::new(Arc::new(NoOpFlowStore));
        // Simulate a failed op recording an error through the shared seam.
        let _ = log_flow_err(
            "increment",
            0i64,
            Err::<i64, _>(anyhow::anyhow!("backend down")),
        );
        let err = s.last_error();
        assert!(
            err.into_string()
                .map(|x| x.contains("backend down"))
                .unwrap_or(false),
            "last_error() must surface the recorded backend error"
        );
        // last_error() took the value: a subsequent call with no new failure returns unit.
        assert!(s.last_error().is_unit());
    }

    // ============================================
    // Tests for FaultDecision enum
    // ============================================

    #[test]
    fn test_fault_decision_none() {
        let decision = FaultDecision::None;
        match decision {
            FaultDecision::None => {}
            _ => panic!("Expected FaultDecision::None"),
        }
    }

    #[test]
    fn test_fault_decision_latency() {
        let decision = FaultDecision::Latency {
            duration_ms: 500,
            rule_id: "test-rule".to_string(),
        };
        match decision {
            FaultDecision::Latency {
                duration_ms,
                rule_id,
            } => {
                assert_eq!(duration_ms, 500);
                assert_eq!(rule_id, "test-rule");
            }
            _ => panic!("Expected FaultDecision::Latency"),
        }
    }

    #[test]
    fn test_fault_decision_error() {
        let mut headers = std::collections::HashMap::new();
        headers.insert("X-Custom".to_string(), "value".to_string());

        let decision = FaultDecision::Error {
            status: 503,
            body: r#"{"error": "service unavailable"}"#.to_string(),
            rule_id: "error-rule".to_string(),
            headers,
        };
        match decision {
            FaultDecision::Error {
                status,
                body,
                rule_id,
                headers,
            } => {
                assert_eq!(status, 503);
                assert!(body.contains("service unavailable"));
                assert_eq!(rule_id, "error-rule");
                assert_eq!(headers.get("X-Custom"), Some(&"value".to_string()));
            }
            _ => panic!("Expected FaultDecision::Error"),
        }
    }

    #[test]
    fn test_fault_decision_clone() {
        let decision = FaultDecision::Latency {
            duration_ms: 100,
            rule_id: "clone-test".to_string(),
        };
        let cloned = decision.clone();
        match cloned {
            FaultDecision::Latency {
                duration_ms,
                rule_id,
            } => {
                assert_eq!(duration_ms, 100);
                assert_eq!(rule_id, "clone-test");
            }
            _ => panic!("Expected cloned FaultDecision::Latency"),
        }
    }

    #[test]
    fn test_fault_decision_debug() {
        let decision = FaultDecision::None;
        let debug_str = format!("{decision:?}");
        assert!(debug_str.contains("None"));
    }

    // Issue #357 Item 3: `reset()` maps to FaultDecision::Reset.
    #[test]
    fn test_fault_decision_reset() {
        let decision = FaultDecision::Reset {
            rule_id: "reset-rule".to_string(),
        };
        match decision {
            FaultDecision::Reset { rule_id } => assert_eq!(rule_id, "reset-rule"),
            _ => panic!("Expected FaultDecision::Reset"),
        }
    }

    // Issue #357 Item 3: the ScriptResult -> FaultDecision conversions used by every engine.
    #[test]
    fn test_script_result_into_fault_decision() {
        assert!(matches!(
            ScriptResult::Pass.into_fault_decision("r"),
            FaultDecision::None
        ));
        assert!(matches!(
            ScriptResult::Delay(42).into_fault_decision("r"),
            FaultDecision::Latency {
                duration_ms: 42,
                ..
            }
        ));
        assert!(matches!(
            ScriptResult::Reset.into_fault_decision("r"),
            FaultDecision::Reset { .. }
        ));

        let mut json_result =
            ScriptResult::http(503, Some(ScriptResultBody::Json(json!({"e": 1}))));
        json_result.add_header("Retry-After".to_string(), "1".to_string());
        match json_result.into_fault_decision("r") {
            FaultDecision::Error {
                status,
                body,
                headers,
                ..
            } => {
                assert_eq!(status, 503);
                assert_eq!(body, r#"{"e":1}"#);
                assert_eq!(headers.get("Retry-After").map(String::as_str), Some("1"));
                assert_eq!(
                    headers.get("Content-Type").map(String::as_str),
                    Some("application/json")
                );
            }
            other => panic!("expected Error, got {other:?}"),
        }

        // An explicit content-type header always wins over the JSON-body default.
        let mut custom_ct = ScriptResult::http(200, Some(ScriptResultBody::Json(json!({}))));
        custom_ct.add_header("content-type".to_string(), "application/custom".to_string());
        match custom_ct.into_fault_decision("r") {
            FaultDecision::Error { headers, .. } => {
                assert_eq!(
                    headers.get("content-type").map(String::as_str),
                    Some("application/custom")
                );
                assert!(!headers.contains_key("Content-Type"));
            }
            other => panic!("expected Error, got {other:?}"),
        }

        // A string body passes through verbatim with no Content-Type added.
        match ScriptResult::http(200, Some(ScriptResultBody::Str("hi".to_string())))
            .into_fault_decision("r")
        {
            FaultDecision::Error { body, headers, .. } => {
                assert_eq!(body, "hi");
                assert!(!headers.contains_key("Content-Type"));
            }
            other => panic!("expected Error, got {other:?}"),
        }
    }

    // ============================================
    // Tests for ScriptRequest
    // ============================================

    #[test]
    fn test_script_request_creation() {
        let request = ScriptRequest {
            mode: ResponseMode::Text,
            raw_body: None,
            method: "POST".to_string(),
            path: "/api/users".to_string(),
            headers: crate::util::OrderedMap::default(),
            body: serde_json::json!({"name": "test"}),
            query: Default::default(),
            path_params: HashMap::new(),
        };
        assert_eq!(request.method, "POST");
        assert_eq!(request.path, "/api/users");
    }

    #[test]
    fn test_script_request_with_headers() {
        let mut headers = crate::util::OrderedMap::default();
        headers.insert(
            "Content-Type".to_string(),
            vec!["application/json".to_string()],
        );
        headers.insert(
            "Authorization".to_string(),
            vec!["Bearer token".to_string()],
        );

        let request = ScriptRequest {
            mode: ResponseMode::Text,
            raw_body: None,
            method: "GET".to_string(),
            path: "/api/data".to_string(),
            headers,
            body: serde_json::json!(null),
            query: Default::default(),
            path_params: HashMap::new(),
        };
        assert_eq!(request.headers.len(), 2);
        assert_eq!(
            request.headers.get("Content-Type"),
            Some(&vec!["application/json".to_string()])
        );
    }

    #[test]
    fn test_script_request_with_query_params() {
        let mut query = crate::util::OrderedMap::default();
        query.insert("page".to_string(), vec!["1".to_string()]);
        query.insert("limit".to_string(), vec!["10".to_string()]);

        let request = ScriptRequest {
            mode: ResponseMode::Text,
            raw_body: None,
            method: "GET".to_string(),
            path: "/api/items".to_string(),
            headers: crate::util::OrderedMap::default(),
            body: serde_json::json!(null),
            query,
            path_params: HashMap::new(),
        };
        assert_eq!(request.query.get("page"), Some(&vec!["1".to_string()]));
        assert_eq!(request.query.get("limit"), Some(&vec!["10".to_string()]));
    }

    #[test]
    fn test_script_request_with_path_params() {
        let mut path_params = HashMap::new();
        path_params.insert("id".to_string(), "123".to_string());
        path_params.insert("action".to_string(), "edit".to_string());

        let request = ScriptRequest {
            mode: ResponseMode::Text,
            raw_body: None,
            method: "PUT".to_string(),
            path: "/api/users/123/edit".to_string(),
            headers: crate::util::OrderedMap::default(),
            body: serde_json::json!({"name": "updated"}),
            query: Default::default(),
            path_params,
        };
        assert_eq!(request.path_params.get("id"), Some(&"123".to_string()));
    }

    #[test]
    fn test_script_request_clone() {
        let request = ScriptRequest {
            mode: ResponseMode::Text,
            raw_body: None,
            method: "DELETE".to_string(),
            path: "/api/items/456".to_string(),
            headers: crate::util::OrderedMap::default(),
            body: serde_json::json!(null),
            query: Default::default(),
            path_params: HashMap::new(),
        };
        let cloned = request.clone();
        assert_eq!(cloned.method, "DELETE");
        assert_eq!(cloned.path, "/api/items/456");
    }

    #[test]
    fn test_script_request_debug() {
        let request = ScriptRequest {
            mode: ResponseMode::Text,
            raw_body: None,
            method: "GET".to_string(),
            path: "/test".to_string(),
            headers: crate::util::OrderedMap::default(),
            body: serde_json::json!(null),
            query: Default::default(),
            path_params: HashMap::new(),
        };
        let debug_str = format!("{request:?}");
        assert!(debug_str.contains("GET"));
        assert!(debug_str.contains("/test"));
    }

    // ============================================
    // Tests for ScriptFlowStore
    // ============================================

    #[test]
    fn test_script_flow_store_creation() {
        let store = Arc::new(NoOpFlowStore);
        let script_store = ScriptFlowStore::new(store);
        assert!(std::mem::size_of_val(&script_store) > 0);
    }

    #[test]
    fn test_script_flow_store_get() {
        let store = Arc::new(NoOpFlowStore);
        let mut script_store = ScriptFlowStore::new(store);
        let result = script_store
            .get("flow-1".to_string(), "key".to_string())
            .expect("NoOp get never fails");
        // NoOpFlowStore returns Unit for get
        assert!(result.is_unit());
    }

    #[test]
    fn test_script_flow_store_set() {
        let store = Arc::new(NoOpFlowStore);
        let mut script_store = ScriptFlowStore::new(store);
        let result = script_store
            .set(
                "flow-1".to_string(),
                "key".to_string(),
                rhai::Dynamic::from(42),
            )
            .expect("NoOp set never fails");
        assert!(result);
    }

    #[test]
    fn test_script_flow_store_exists() {
        let store = Arc::new(NoOpFlowStore);
        let mut script_store = ScriptFlowStore::new(store);
        let result = script_store
            .exists("flow-1".to_string(), "key".to_string())
            .expect("NoOp exists never fails");
        assert!(!result); // NoOpFlowStore always returns false
    }

    #[test]
    fn test_script_flow_store_delete() {
        let store = Arc::new(NoOpFlowStore);
        let mut script_store = ScriptFlowStore::new(store);
        let result = script_store
            .delete("flow-1".to_string(), "key".to_string())
            .expect("NoOp delete never fails");
        assert!(result);
    }

    #[test]
    fn test_script_flow_store_increment() {
        let store = Arc::new(NoOpFlowStore);
        let mut script_store = ScriptFlowStore::new(store);
        // NoOpFlowStore returns 0 on error (which doesn't happen, but increment returns 1)
        let result = script_store
            .increment("flow-1".to_string(), "counter".to_string())
            .expect("NoOp increment never fails");
        assert_eq!(result, 1);
    }

    #[test]
    fn test_script_flow_store_set_ttl() {
        let store = Arc::new(NoOpFlowStore);
        let mut script_store = ScriptFlowStore::new(store);
        let result = script_store
            .set_ttl("flow-1".to_string(), 3600)
            .expect("NoOp set_ttl never fails");
        assert!(result);
    }

    #[test]
    fn test_script_flow_store_clone() {
        let store = Arc::new(NoOpFlowStore);
        let script_store = ScriptFlowStore::new(store);
        let cloned = script_store.clone();
        // Both should reference the same underlying store
        assert!(std::mem::size_of_val(&cloned) > 0);
    }

    // ============================================
    // Tests for ScriptEngine enum
    // ============================================

    #[test]
    fn test_script_engine_new_rhai() {
        let script = r#"
            fn respond(ctx) {
                pass()
            }
        "#;
        let engine = ScriptEngine::new("rhai", script, "test-rule");
        assert!(engine.is_ok());
    }

    #[test]
    fn test_script_engine_new_invalid_type() {
        let script = "return false";
        let engine = ScriptEngine::new("invalid_engine", script, "test-rule");
        assert!(engine.is_err());
        let err_msg = engine.err().unwrap().to_string();
        assert!(err_msg.contains("Unknown script engine type"));
    }

    #[test]
    fn test_script_engine_rhai_execution() {
        let script = r#"
            fn respond(ctx) {
                pass()
            }
        "#;
        let engine = ScriptEngine::new("rhai", script, "test-rule").unwrap();

        let request = ScriptRequest {
            mode: ResponseMode::Text,
            raw_body: None,
            method: "GET".to_string(),
            path: "/test".to_string(),
            headers: crate::util::OrderedMap::default(),
            body: serde_json::json!(null),
            query: Default::default(),
            path_params: HashMap::new(),
        };

        let flow_store: Arc<dyn crate::extensions::flow_state::FlowStore> = Arc::new(NoOpFlowStore);
        let result = engine.should_inject_fault(&request, flow_store);
        assert!(result.is_ok());
    }

    // ============================================
    // Tests for RhaiEngine creation
    // ============================================

    #[test]
    fn test_rhai_engine_creation_valid_script() {
        let script = r#"
            fn respond(ctx) {
                pass()
            }
        "#;
        let engine = RhaiEngine::new(script, "valid-rule");
        assert!(engine.is_ok());
    }

    #[test]
    fn test_rhai_engine_creation_syntax_error() {
        let script = r#"
            fn respond(ctx {  // Missing closing paren
                return false;
            }
        "#;
        let engine = RhaiEngine::new(script, "invalid-rule");
        assert!(engine.is_err());
    }

    #[test]
    fn test_rhai_engine_ast_access() {
        let script = r#"
            fn respond(ctx) {
                pass()
            }
        "#;
        let engine = RhaiEngine::new(script, "test-rule").unwrap();
        let ast = engine.ast();
        assert!(std::mem::size_of_val(ast) > 0);
    }

    // ============================================
    // Feature-gated tests
    // ============================================

    // Issue #450: Lua was removed; "lua" now always fails with an actionable error pointing at
    // the two remaining engines, rather than a feature-flag message.
    #[test]
    fn test_script_engine_new_lua_removed() {
        let engine = ScriptEngine::new("lua", "return false", "test-rule");
        assert!(engine.is_err());
        let err_msg = engine.err().unwrap().to_string();
        assert!(err_msg.contains("removed"), "unexpected message: {err_msg}");
        assert!(err_msg.contains("rhai"));
        assert!(err_msg.contains("javascript"));
    }

    #[cfg(feature = "javascript")]
    mod js_tests {
        use super::*;

        #[test]
        fn test_script_engine_new_javascript() {
            let script = r#"
                function respond(ctx) {
                    return pass();
                }
            "#;
            let engine = ScriptEngine::new("javascript", script, "js-rule");
            assert!(
                engine.is_ok(),
                "JS engine creation failed: {:?}",
                engine.err()
            );
        }

        #[test]
        fn test_script_engine_new_js_alias() {
            let script = r#"
                function respond(ctx) {
                    return pass();
                }
            "#;
            let engine = ScriptEngine::new("js", script, "js-rule");
            assert!(
                engine.is_ok(),
                "JS engine creation failed: {:?}",
                engine.err()
            );
        }

        #[test]
        fn test_compile_js_to_bytecode() {
            let script = r#"
                function respond(ctx) {
                    return pass();
                }
            "#;
            let bytecode = super::super::compile_js_to_bytecode(script);
            assert!(bytecode.is_ok());
        }
    }

    // ============================================
    // Tests for disabled features
    // ============================================

    #[cfg(not(feature = "javascript"))]
    #[test]
    fn test_javascript_engine_disabled() {
        let engine = ScriptEngine::new("javascript", "return false", "test");
        assert!(engine.is_err());
        let err_msg = engine.err().unwrap().to_string();
        assert!(err_msg.contains("not enabled") || err_msg.contains("feature"));
    }
}