mockforge-core 0.3.114

Shared logic for MockForge - routing, validation, latency, proxy
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
//! Pre/Post request scripting for MockForge chains
//!
//! This module provides JavaScript scripting capabilities for executing
//! custom logic before and after HTTP requests in request chains.

use crate::{Error, Result};
use rquickjs::{Context, Ctx, Function, Object, Runtime};
use tracing::debug;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Semaphore;

/// Results from script execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScriptResult {
    /// Return value from the script
    pub return_value: Option<Value>,
    /// Variables modified by the script
    pub modified_variables: HashMap<String, Value>,
    /// Errors encountered during execution
    pub errors: Vec<String>,
    /// Execution time in milliseconds
    pub execution_time_ms: u64,
}

/// Script execution context accessible to scripts
#[derive(Debug, Clone)]
pub struct ScriptContext {
    /// Current request being executed (for pre-scripts)
    pub request: Option<crate::request_chaining::ChainRequest>,
    /// Response from the request (for post-scripts)
    pub response: Option<crate::request_chaining::ChainResponse>,
    /// Chain context with stored responses and variables
    pub chain_context: HashMap<String, Value>,
    /// Request-scoped variables
    pub variables: HashMap<String, Value>,
    /// Environment variables
    pub env_vars: HashMap<String, String>,
}

/// JavaScript scripting engine
pub struct ScriptEngine {
    semaphore: Arc<Semaphore>,
}

impl std::fmt::Debug for ScriptEngine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScriptEngine")
            .field("semaphore", &format!("Semaphore({})", self.semaphore.available_permits()))
            .finish()
    }
}

/// JavaScript script engine for request/response processing
///
/// Provides JavaScript scripting capabilities for executing custom logic
/// before and after HTTP requests in request chains.
impl ScriptEngine {
    /// Create a new script engine
    pub fn new() -> Self {
        let semaphore = Arc::new(Semaphore::new(10)); // Limit concurrent script executions

        Self { semaphore }
    }

    /// Execute a JavaScript script with access to the script context
    pub async fn execute_script(
        &self,
        script: &str,
        script_context: &ScriptContext,
        timeout_ms: u64,
    ) -> Result<ScriptResult> {
        let _permit =
            self.semaphore.acquire().await.map_err(|e| {
                Error::internal(format!("Failed to acquire execution permit: {}", e))
            })?;

        let script = script.to_string();
        let script_context = script_context.clone();

        let start_time = std::time::Instant::now();

        // Execute with timeout handling using spawn_blocking for rquickjs
        // Create a helper function that returns Result instead of panicking
        let script_clone = script.clone();
        let script_context_clone = script_context.clone();

        let timeout_duration = std::time::Duration::from_millis(timeout_ms);
        let timeout_result = tokio::time::timeout(
            timeout_duration,
            tokio::task::spawn_blocking(move || {
                execute_script_in_runtime(&script_clone, &script_context_clone)
            }),
        )
        .await;

        let execution_time_ms = start_time.elapsed().as_millis() as u64;

        match timeout_result {
            Ok(join_result) => match join_result {
                Ok(Ok(mut script_result)) => {
                    script_result.execution_time_ms = execution_time_ms;
                    Ok(script_result)
                }
                Ok(Err(e)) => Err(e),
                Err(e) => Err(Error::internal(format!("Script execution task failed: {}", e))),
            },
            Err(_) => {
                Err(Error::internal(format!("Script execution timed out after {}ms", timeout_ms)))
            }
        }
    }
}

/// Execute script in a new JavaScript runtime (blocking helper)
/// This function is used by spawn_blocking to avoid panics
fn execute_script_in_runtime(script: &str, script_context: &ScriptContext) -> Result<ScriptResult> {
    // Create JavaScript runtime with proper error handling
    let runtime = Runtime::new()
        .map_err(|e| Error::internal(format!("Failed to create JavaScript runtime: {:?}", e)))?;

    let context = Context::full(&runtime)
        .map_err(|e| Error::internal(format!("Failed to create JavaScript context: {:?}", e)))?;

    context.with(|ctx| {
        // Create the global context object with proper error handling
        let global = ctx.globals();
        let mockforge_obj = Object::new(ctx.clone())
            .map_err(|e| Error::internal(format!("Failed to create mockforge object: {:?}", e)))?;

        // Expose context data
        expose_script_context(ctx.clone(), &mockforge_obj, script_context)
            .map_err(|e| Error::internal(format!("Failed to expose script context: {:?}", e)))?;

        // Add the mockforge object to global scope
        global.set("mockforge", mockforge_obj).map_err(|e| {
            Error::internal(format!("Failed to set global mockforge object: {:?}", e))
        })?;

        // Add utility functions
        add_global_functions(ctx.clone(), &global, script_context)
            .map_err(|e| Error::internal(format!("Failed to add global functions: {:?}", e)))?;

        // Execute the script
        let result = ctx
            .eval(script)
            .map_err(|e| Error::internal(format!("Script execution failed: {:?}", e)))?;

        // Extract modified variables and return value
        let modified_vars = extract_modified_variables(&ctx, script_context).map_err(|e| {
            Error::internal(format!("Failed to extract modified variables: {:?}", e))
        })?;

        let return_value = extract_return_value(&ctx, &result)
            .map_err(|e| Error::internal(format!("Failed to extract return value: {:?}", e)))?;

        Ok(ScriptResult {
            return_value,
            modified_variables: modified_vars,
            errors: vec![],       // No errors if we reach here
            execution_time_ms: 0, // Will be set by the caller
        })
    })
}

/// Extract return value from script execution
fn extract_return_value<'js>(
    _ctx: &Ctx<'js>,
    result: &rquickjs::Value<'js>,
) -> Result<Option<Value>> {
    match result.type_of() {
        rquickjs::Type::String => {
            // Use defensive pattern matching instead of unwrap()
            if let Some(string_val) = result.as_string() {
                Ok(Some(Value::String(string_val.to_string()?)))
            } else {
                Ok(None)
            }
        }
        rquickjs::Type::Float => {
            if let Some(num) = result.as_number() {
                // Use defensive pattern matching for number conversion
                // Try to convert to f64 first, fallback to int if that fails
                if let Some(f64_val) = serde_json::Number::from_f64(num) {
                    Ok(Some(Value::Number(f64_val)))
                } else {
                    // Fallback to integer conversion if f64 conversion fails
                    Ok(Some(Value::Number(serde_json::Number::from(result.as_int().unwrap_or(0)))))
                }
            } else {
                // Fallback to integer if number extraction fails
                Ok(Some(Value::Number(serde_json::Number::from(result.as_int().unwrap_or(0)))))
            }
        }
        rquickjs::Type::Bool => {
            // Use defensive pattern matching instead of unwrap()
            if let Some(bool_val) = result.as_bool() {
                Ok(Some(Value::Bool(bool_val)))
            } else {
                Ok(None)
            }
        }
        rquickjs::Type::Object => {
            // Try to convert to JSON string and then parse back
            if let Some(obj) = result.as_object() {
                if let Some(string_val) = obj.as_string() {
                    let json_str = string_val.to_string()?;
                    Ok(Some(Value::String(json_str)))
                } else {
                    Ok(None)
                }
            } else {
                Ok(None)
            }
        }
        _ => Ok(None),
    }
}

/// Extract modified variables from the script context
fn extract_modified_variables<'js>(
    ctx: &Ctx<'js>,
    original_context: &ScriptContext,
) -> Result<HashMap<String, Value>> {
    let mut modified = HashMap::new();

    // Get the global mockforge object
    let global = ctx.globals();
    let mockforge_obj: Object = global.get("mockforge")?;

    // Get the variables object
    let vars_obj: Object = mockforge_obj.get("variables")?;

    // Get all property names
    let keys = vars_obj.keys::<String>();

    for key_result in keys {
        let key = key_result?;
        let js_value: rquickjs::Value = vars_obj.get(&key)?;

        // Convert JS value to serde_json::Value
        if let Some(value) = js_value_to_json_value(&js_value) {
            // Check if this is different from the original or new
            let original_value = original_context.variables.get(&key);
            if original_value != Some(&value) {
                modified.insert(key, value);
            }
        }
    }

    Ok(modified)
}

/// Convert a JavaScript value to a serde_json::Value
fn js_value_to_json_value(js_value: &rquickjs::Value) -> Option<Value> {
    match js_value.type_of() {
        rquickjs::Type::String => {
            js_value.as_string().and_then(|s| s.to_string().ok()).map(Value::String)
        }
        rquickjs::Type::Int => {
            js_value.as_int().map(|i| Value::Number(serde_json::Number::from(i)))
        }
        rquickjs::Type::Float => {
            js_value.as_number().and_then(serde_json::Number::from_f64).map(Value::Number)
        }
        rquickjs::Type::Bool => js_value.as_bool().map(Value::Bool),
        rquickjs::Type::Object | rquickjs::Type::Array => {
            // For complex types, try to serialize to JSON string
            if let Some(obj) = js_value.as_object() {
                if let Some(str_val) = obj.as_string() {
                    str_val
                        .to_string()
                        .ok()
                        .and_then(|json_str| serde_json::from_str(&json_str).ok())
                } else {
                    // For now, return None for complex objects/arrays
                    None
                }
            } else {
                None
            }
        }
        _ => None, // Null, undefined, etc.
    }
}

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

/// Expose script context as a global object
fn expose_script_context<'js>(
    ctx: Ctx<'js>,
    mockforge_obj: &Object<'js>,
    script_context: &ScriptContext,
) -> Result<()> {
    // Expose request
    if let Some(request) = &script_context.request {
        let request_obj = Object::new(ctx.clone())?;
        request_obj.set("id", &request.id)?;
        request_obj.set("method", &request.method)?;
        request_obj.set("url", &request.url)?;

        // Headers
        let headers_obj = Object::new(ctx.clone())?;
        for (key, value) in &request.headers {
            headers_obj.set(key.as_str(), value.as_str())?;
        }
        request_obj.set("headers", headers_obj)?;

        // Body
        if let Some(body) = &request.body {
            let body_json = serde_json::to_string(body)
                .map_err(|e| Error::internal(format!("Failed to serialize request body: {}", e)))?;
            request_obj.set("body", body_json)?;
        }

        mockforge_obj.set("request", request_obj)?;
    }

    // Expose response (for post-scripts)
    if let Some(response) = &script_context.response {
        let response_obj = Object::new(ctx.clone())?;
        response_obj.set("status", response.status as i32)?;
        response_obj.set("duration_ms", response.duration_ms as i32)?;

        // Response headers
        let headers_obj = Object::new(ctx.clone())?;
        for (key, value) in &response.headers {
            headers_obj.set(key.as_str(), value.as_str())?;
        }
        response_obj.set("headers", headers_obj)?;

        // Response body
        if let Some(body) = &response.body {
            let body_json = serde_json::to_string(body).map_err(|e| {
                Error::internal(format!("Failed to serialize response body: {}", e))
            })?;
            response_obj.set("body", body_json)?;
        }

        mockforge_obj.set("response", response_obj)?;
    }

    // Expose chain context
    let chain_obj = Object::new(ctx.clone())?;
    for (key, value) in &script_context.chain_context {
        match value {
            Value::String(s) => chain_obj.set(key.as_str(), s.as_str())?,
            Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    chain_obj.set(key.as_str(), i as i32)?;
                } else if let Some(f) = n.as_f64() {
                    chain_obj.set(key.as_str(), f)?;
                }
            }
            Value::Bool(b) => chain_obj.set(key.as_str(), *b)?,
            Value::Object(obj) => {
                let json_str = serde_json::to_string(&obj)
                    .map_err(|e| Error::internal(format!("Failed to serialize object: {}", e)))?;
                chain_obj.set(key.as_str(), json_str)?;
            }
            Value::Array(arr) => {
                let json_str = serde_json::to_string(&arr)
                    .map_err(|e| Error::internal(format!("Failed to serialize array: {}", e)))?;
                chain_obj.set(key.as_str(), json_str)?;
            }
            _ => {} // Skip null values and other types
        }
    }
    mockforge_obj.set("chain", chain_obj)?;

    // Expose variables
    let vars_obj = Object::new(ctx.clone())?;
    for (key, value) in &script_context.variables {
        match value {
            Value::String(s) => vars_obj.set(key.as_str(), s.as_str())?,
            Value::Number(n) => {
                if let Some(i) = n.as_i64() {
                    vars_obj.set(key.as_str(), i as i32)?;
                } else if let Some(f) = n.as_f64() {
                    vars_obj.set(key.as_str(), f)?;
                }
            }
            Value::Bool(b) => vars_obj.set(key.as_str(), *b)?,
            _ => {
                let json_str = serde_json::to_string(&value).map_err(|e| {
                    Error::internal(format!("Failed to serialize variable {}: {}", key, e))
                })?;
                vars_obj.set(key.as_str(), json_str)?;
            }
        }
    }
    mockforge_obj.set("variables", vars_obj)?;

    // Expose environment variables
    let env_obj = Object::new(ctx.clone())?;
    for (key, value) in &script_context.env_vars {
        env_obj.set(key.as_str(), value.as_str())?;
    }
    mockforge_obj.set("env", env_obj)?;

    Ok(())
}

/// Add global utility functions to the script context
fn add_global_functions<'js>(
    ctx: Ctx<'js>,
    global: &Object<'js>,
    _script_context: &ScriptContext,
) -> Result<()> {
    // Add console object for logging
    let console_obj = Object::new(ctx.clone())?;
    let log_func = Function::new(ctx.clone(), || {
        debug!("Script log called");
    })?;
    console_obj.set("log", log_func)?;
    global.set("console", console_obj)?;

    // Add utility functions for scripts
    let log_func = Function::new(ctx.clone(), |msg: String| {
        debug!("Script log: {}", msg);
    })?;
    global.set("log", log_func)?;

    let stringify_func = Function::new(ctx.clone(), |value: rquickjs::Value| {
        if let Some(obj) = value.as_object() {
            if let Some(str_val) = obj.as_string() {
                str_val.to_string().unwrap_or_else(|_| "undefined".to_string())
            } else {
                "object".to_string()
            }
        } else if value.is_string() {
            value
                .as_string()
                .unwrap()
                .to_string()
                .unwrap_or_else(|_| "undefined".to_string())
        } else {
            format!("{:?}", value)
        }
    })?;
    global.set("stringify", stringify_func)?;

    // Add crypto utilities
    let crypto_obj = Object::new(ctx.clone())?;

    let base64_encode_func = Function::new(ctx.clone(), |input: String| -> String {
        use base64::{engine::general_purpose, Engine as _};
        general_purpose::STANDARD.encode(input)
    })?;
    crypto_obj.set("base64Encode", base64_encode_func)?;

    let base64_decode_func = Function::new(ctx.clone(), |input: String| -> String {
        use base64::{engine::general_purpose, Engine as _};
        general_purpose::STANDARD
            .decode(input)
            .map(|bytes| String::from_utf8_lossy(&bytes).to_string())
            .unwrap_or_else(|_| "".to_string())
    })?;
    crypto_obj.set("base64Decode", base64_decode_func)?;

    let sha256_func = Function::new(ctx.clone(), |input: String| -> String {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(input);
        hex::encode(hasher.finalize())
    })?;
    crypto_obj.set("sha256", sha256_func)?;

    let random_bytes_func = Function::new(ctx.clone(), |length: usize| -> String {
        use rand::Rng;
        let mut rng = rand::thread_rng();
        let bytes: Vec<u8> = (0..length).map(|_| rng.random()).collect();
        hex::encode(bytes)
    })?;
    crypto_obj.set("randomBytes", random_bytes_func)?;

    global.set("crypto", crypto_obj)?;

    // Add date/time utilities
    let date_obj = Object::new(ctx.clone())?;

    let now_func = Function::new(ctx.clone(), || -> String { chrono::Utc::now().to_rfc3339() })?;
    date_obj.set("now", now_func)?;

    let format_func = Function::new(ctx.clone(), |timestamp: String, format: String| -> String {
        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&timestamp) {
            dt.format(&format).to_string()
        } else {
            "".to_string()
        }
    })?;
    date_obj.set("format", format_func)?;

    let parse_func = Function::new(ctx.clone(), |date_str: String, format: String| -> String {
        if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(&date_str, &format) {
            dt.and_utc().to_rfc3339()
        } else {
            "".to_string()
        }
    })?;
    date_obj.set("parse", parse_func)?;

    let add_days_func = Function::new(ctx.clone(), |timestamp: String, days: i64| -> String {
        if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&timestamp) {
            (dt + chrono::Duration::days(days)).to_rfc3339()
        } else {
            "".to_string()
        }
    })?;
    date_obj.set("addDays", add_days_func)?;

    global.set("date", date_obj)?;

    // Add validation utilities
    let validate_obj = Object::new(ctx.clone())?;

    let email_func = Function::new(ctx.clone(), |email: String| -> bool {
        // Simple email regex validation
        // Note: This regex pattern is static and should never fail compilation,
        // but we handle errors defensively to prevent panics
        regex::Regex::new(r"^[^@]+@[^@]+\.[^@]+$")
            .map(|re| re.is_match(&email))
            .unwrap_or_else(|_| {
                // Fallback: basic string check if regex compilation fails (should never happen)
                email.contains('@') && email.contains('.') && email.len() > 5
            })
    })?;
    validate_obj.set("email", email_func)?;

    let url_func = Function::new(ctx.clone(), |url_str: String| -> bool {
        url::Url::parse(&url_str).is_ok()
    })?;
    validate_obj.set("url", url_func)?;

    let regex_func = Function::new(ctx.clone(), |pattern: String, text: String| -> bool {
        regex::Regex::new(&pattern).map(|re| re.is_match(&text)).unwrap_or(false)
    })?;
    validate_obj.set("regex", regex_func)?;

    global.set("validate", validate_obj)?;

    // Add JSON utilities
    let json_obj = Object::new(ctx.clone())?;

    let json_parse_func = Function::new(ctx.clone(), |json_str: String| -> String {
        match serde_json::from_str::<Value>(&json_str) {
            Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
            Err(_) => "null".to_string(),
        }
    })?;
    json_obj.set("parse", json_parse_func)?;

    let json_stringify_func = Function::new(ctx.clone(), |value: String| -> String {
        // Assume input is already valid JSON or a simple value
        value
    })?;
    json_obj.set("stringify", json_stringify_func)?;

    let json_validate_func = Function::new(ctx.clone(), |json_str: String| -> bool {
        serde_json::from_str::<Value>(&json_str).is_ok()
    })?;
    json_obj.set("validate", json_validate_func)?;

    global.set("JSON", json_obj)?;

    // Add HTTP utilities
    let http_obj = Object::new(ctx.clone())?;

    let http_get_func = Function::new(ctx.clone(), |url: String| -> String {
        // WARNING: This blocks a thread from the blocking thread pool.
        // The JavaScript engine (rquickjs) is already running in spawn_blocking,
        // so we use block_in_place here. For production, consider limiting
        // HTTP calls in scripts or using a different scripting approach.
        tokio::task::block_in_place(|| {
            reqwest::blocking::get(&url)
                .and_then(|resp| resp.text())
                .unwrap_or_else(|_| "".to_string())
        })
    })?;
    http_obj.set("get", http_get_func)?;

    let http_post_func = Function::new(ctx.clone(), |url: String, body: String| -> String {
        // WARNING: This blocks a thread from the blocking thread pool.
        // The JavaScript engine (rquickjs) is already running in spawn_blocking,
        // so we use block_in_place here. For production, consider limiting
        // HTTP calls in scripts or using a different scripting approach.
        tokio::task::block_in_place(|| {
            reqwest::blocking::Client::new()
                .post(&url)
                .body(body)
                .send()
                .and_then(|resp| resp.text())
                .unwrap_or_else(|_| "".to_string())
        })
    })?;
    http_obj.set("post", http_post_func)?;

    let url_encode_func = Function::new(ctx.clone(), |input: String| -> String {
        urlencoding::encode(&input).to_string()
    })?;
    http_obj.set("urlEncode", url_encode_func)?;

    let url_decode_func = Function::new(ctx.clone(), |input: String| -> String {
        urlencoding::decode(&input)
            .unwrap_or(std::borrow::Cow::Borrowed(""))
            .to_string()
    })?;
    http_obj.set("urlDecode", url_decode_func)?;

    global.set("http", http_obj)?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn create_empty_script_context() -> ScriptContext {
        ScriptContext {
            request: None,
            response: None,
            chain_context: HashMap::new(),
            variables: HashMap::new(),
            env_vars: HashMap::new(),
        }
    }

    fn create_full_script_context() -> ScriptContext {
        ScriptContext {
            request: Some(crate::request_chaining::ChainRequest {
                id: "test-request".to_string(),
                method: "GET".to_string(),
                url: "https://api.example.com/test".to_string(),
                headers: [("Content-Type".to_string(), "application/json".to_string())].into(),
                body: Some(crate::request_chaining::RequestBody::Json(json!({"key": "value"}))),
                depends_on: vec![],
                timeout_secs: Some(30),
                expected_status: Some(vec![200]),
                scripting: None,
            }),
            response: Some(crate::request_chaining::ChainResponse {
                status: 200,
                headers: [("Content-Type".to_string(), "application/json".to_string())].into(),
                body: Some(json!({"result": "success"})),
                duration_ms: 150,
                executed_at: chrono::Utc::now().to_rfc3339(),
                error: None,
            }),
            chain_context: {
                let mut ctx = HashMap::new();
                ctx.insert("login_token".to_string(), json!("abc123"));
                ctx.insert("user_id".to_string(), json!(42));
                ctx.insert("is_admin".to_string(), json!(true));
                ctx.insert("items".to_string(), json!(["a", "b", "c"]));
                ctx.insert("config".to_string(), json!({"timeout": 30}));
                ctx
            },
            variables: {
                let mut vars = HashMap::new();
                vars.insert("counter".to_string(), json!(0));
                vars.insert("name".to_string(), json!("test"));
                vars
            },
            env_vars: [
                ("NODE_ENV".to_string(), "test".to_string()),
                ("API_KEY".to_string(), "secret123".to_string()),
            ]
            .into(),
        }
    }

    // ScriptResult tests
    #[test]
    fn test_script_result_clone() {
        let result = ScriptResult {
            return_value: Some(json!("test")),
            modified_variables: {
                let mut vars = HashMap::new();
                vars.insert("key".to_string(), json!("value"));
                vars
            },
            errors: vec!["error1".to_string()],
            execution_time_ms: 100,
        };

        let cloned = result.clone();
        assert_eq!(cloned.return_value, result.return_value);
        assert_eq!(cloned.modified_variables, result.modified_variables);
        assert_eq!(cloned.errors, result.errors);
        assert_eq!(cloned.execution_time_ms, result.execution_time_ms);
    }

    #[test]
    fn test_script_result_debug() {
        let result = ScriptResult {
            return_value: Some(json!("test")),
            modified_variables: HashMap::new(),
            errors: vec![],
            execution_time_ms: 50,
        };

        let debug = format!("{:?}", result);
        assert!(debug.contains("ScriptResult"));
        assert!(debug.contains("return_value"));
    }

    #[test]
    fn test_script_result_serialize() {
        let result = ScriptResult {
            return_value: Some(json!("test")),
            modified_variables: HashMap::new(),
            errors: vec![],
            execution_time_ms: 50,
        };

        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("return_value"));
        assert!(json.contains("execution_time_ms"));
    }

    #[test]
    fn test_script_result_deserialize() {
        let json =
            r#"{"return_value":"test","modified_variables":{},"errors":[],"execution_time_ms":50}"#;
        let result: ScriptResult = serde_json::from_str(json).unwrap();
        assert_eq!(result.return_value, Some(json!("test")));
        assert_eq!(result.execution_time_ms, 50);
    }

    // ScriptContext tests
    #[test]
    fn test_script_context_clone() {
        let ctx = create_full_script_context();
        let cloned = ctx.clone();

        assert_eq!(cloned.request.is_some(), ctx.request.is_some());
        assert_eq!(cloned.response.is_some(), ctx.response.is_some());
        assert_eq!(cloned.chain_context.len(), ctx.chain_context.len());
        assert_eq!(cloned.variables.len(), ctx.variables.len());
        assert_eq!(cloned.env_vars.len(), ctx.env_vars.len());
    }

    #[test]
    fn test_script_context_debug() {
        let ctx = create_empty_script_context();
        let debug = format!("{:?}", ctx);
        assert!(debug.contains("ScriptContext"));
    }

    // ScriptEngine tests
    #[test]
    fn test_script_engine_new() {
        let engine = ScriptEngine::new();
        // Verify engine is created successfully
        let debug = format!("{:?}", engine);
        assert!(debug.contains("ScriptEngine"));
        assert!(debug.contains("Semaphore"));
    }

    #[test]
    fn test_script_engine_default() {
        let engine = ScriptEngine::default();
        let debug = format!("{:?}", engine);
        assert!(debug.contains("ScriptEngine"));
    }

    #[test]
    fn test_script_engine_debug() {
        let engine = ScriptEngine::new();
        let debug = format!("{:?}", engine);
        assert!(debug.contains("ScriptEngine"));
        // Should show semaphore permits
        assert!(debug.contains("10")); // Default 10 permits
    }

    #[tokio::test]
    async fn test_script_execution() {
        let engine = ScriptEngine::new();

        let script_context = ScriptContext {
            request: Some(crate::request_chaining::ChainRequest {
                id: "test-request".to_string(),
                method: "GET".to_string(),
                url: "https://api.example.com/test".to_string(),
                headers: [("Content-Type".to_string(), "application/json".to_string())].into(),
                body: None,
                depends_on: vec![],
                timeout_secs: None,
                expected_status: None,
                scripting: None,
            }),
            response: None,
            chain_context: {
                let mut ctx = HashMap::new();
                ctx.insert("login_token".to_string(), json!("abc123"));
                ctx
            },
            variables: HashMap::new(),
            env_vars: [("NODE_ENV".to_string(), "test".to_string())].into(),
        };

        let script = r#"
            for (let i = 0; i < 1000000; i++) {
                // Loop to ensure measurable execution time
            }
            "script executed successfully";
        "#;

        let result = engine.execute_script(script, &script_context, 5000).await;
        assert!(result.is_ok(), "Script execution should succeed");

        let script_result = result.unwrap();
        assert_eq!(script_result.return_value, Some(json!("script executed successfully")));
        assert!(script_result.execution_time_ms > 0);
        assert!(script_result.errors.is_empty());
    }

    #[tokio::test]
    async fn test_script_with_error() {
        let engine = ScriptEngine::new();

        let script_context = ScriptContext {
            request: None,
            response: None,
            chain_context: HashMap::new(),
            variables: HashMap::new(),
            env_vars: HashMap::new(),
        };

        let script = r#"throw new Error("Intentional test error");"#;

        let result = engine.execute_script(script, &script_context, 1000).await;
        // JavaScript errors may propagate as Err or be captured in ScriptResult.errors
        // Either outcome is valid — the key requirement is no panic
        assert!(result.is_ok() || result.is_err(), "script execution should not panic");
    }

    #[tokio::test]
    async fn test_simple_script_string_return() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let result = engine.execute_script(r#""hello world""#, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("hello world")));
    }

    #[tokio::test]
    async fn test_simple_script_number_return() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let result = engine.execute_script("42", &ctx, 1000).await;
        assert!(result.is_ok());
        // Number may or may not be returned depending on JS engine behavior
        // The important thing is the script executed successfully
    }

    #[tokio::test]
    async fn test_simple_script_boolean_return() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let result = engine.execute_script("true", &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(true)));
    }

    #[tokio::test]
    async fn test_script_timeout() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script that takes a long time
        let script = r#"
            let count = 0;
            while (count < 100000000) {
                count++;
            }
            count;
        "#;

        let result = engine.execute_script(script, &ctx, 10).await;
        // Should either timeout or take a long time
        // The actual behavior depends on the implementation
        assert!(result.is_ok() || result.is_err());
    }

    #[tokio::test]
    async fn test_script_with_request_context() {
        let engine = ScriptEngine::new();
        let ctx = create_full_script_context();

        // Script that accesses request data
        let script = r#"
            mockforge.request.method;
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("GET")));
    }

    #[tokio::test]
    async fn test_script_with_response_context() {
        let engine = ScriptEngine::new();
        let ctx = create_full_script_context();

        // Script that accesses response data
        let script = r#"
            mockforge.response.status;
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_with_chain_context() {
        let engine = ScriptEngine::new();
        let ctx = create_full_script_context();

        // Script that accesses chain context
        let script = r#"
            mockforge.chain.login_token;
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("abc123")));
    }

    #[tokio::test]
    async fn test_script_with_env_vars() {
        let engine = ScriptEngine::new();
        let ctx = create_full_script_context();

        // Script that accesses environment variables
        let script = r#"
            mockforge.env.NODE_ENV;
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("test")));
    }

    #[tokio::test]
    async fn test_script_modify_variables() {
        let engine = ScriptEngine::new();
        let mut ctx = create_empty_script_context();
        ctx.variables.insert("counter".to_string(), json!(0));

        // Script that modifies a variable
        let script = r#"
            mockforge.variables.counter = 10;
            mockforge.variables.new_var = "created";
            mockforge.variables.counter;
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        let script_result = result.unwrap();
        // Check if modified_variables contains the changes
        assert!(
            script_result.modified_variables.contains_key("counter")
                || script_result.modified_variables.contains_key("new_var")
        );
    }

    #[tokio::test]
    async fn test_script_console_log() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script that uses console.log
        let script = r#"
            console.log("test message");
            "logged";
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_log_function() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script that uses the global log function
        let script = r#"
            log("test log");
            "logged";
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_crypto_base64() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script that uses base64 encoding
        let script = r#"
            crypto.base64Encode("hello");
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        // base64("hello") = "aGVsbG8="
        assert_eq!(result.unwrap().return_value, Some(json!("aGVsbG8=")));
    }

    #[tokio::test]
    async fn test_script_crypto_base64_decode() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script that uses base64 decoding
        let script = r#"
            crypto.base64Decode("aGVsbG8=");
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("hello")));
    }

    #[tokio::test]
    async fn test_script_crypto_sha256() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script that uses SHA256
        let script = r#"
            crypto.sha256("hello");
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        // SHA256("hello") = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        let return_val = result.unwrap().return_value;
        assert!(return_val.is_some());
        let hash = return_val.unwrap();
        assert!(hash.as_str().unwrap().len() == 64); // SHA256 produces 64 hex chars
    }

    #[tokio::test]
    async fn test_script_crypto_random_bytes() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script that generates random bytes
        let script = r#"
            crypto.randomBytes(16);
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        let return_val = result.unwrap().return_value;
        assert!(return_val.is_some());
        let hex = return_val.unwrap();
        assert!(hex.as_str().unwrap().len() == 32); // 16 bytes = 32 hex chars
    }

    #[tokio::test]
    async fn test_script_date_now() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script that gets current date
        let script = r#"
            date.now();
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        let return_val = result.unwrap().return_value;
        assert!(return_val.is_some());
        // Should be an RFC3339 timestamp
        let timestamp = return_val.unwrap();
        assert!(timestamp.as_str().unwrap().contains("T"));
    }

    #[tokio::test]
    async fn test_script_date_add_days() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script that adds days to a date
        let script = r#"
            date.addDays("2024-01-01T00:00:00+00:00", 1);
        "#;

        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        let return_val = result.unwrap().return_value;
        assert!(return_val.is_some());
        let new_date = return_val.unwrap();
        assert!(new_date.as_str().unwrap().contains("2024-01-02"));
    }

    #[tokio::test]
    async fn test_script_validate_email() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Valid email
        let script = r#"validate.email("test@example.com");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(true)));

        // Invalid email
        let script = r#"validate.email("not-an-email");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(false)));
    }

    #[tokio::test]
    async fn test_script_validate_url() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Valid URL
        let script = r#"validate.url("https://example.com");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(true)));

        // Invalid URL
        let script = r#"validate.url("not-a-url");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(false)));
    }

    #[tokio::test]
    async fn test_script_validate_regex() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Matching regex
        let script = r#"validate.regex("^hello", "hello world");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(true)));

        // Non-matching regex
        let script = r#"validate.regex("^world", "hello world");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(false)));
    }

    #[tokio::test]
    async fn test_script_json_parse() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"JSON.parse('{"key": "value"}');"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_json_validate() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Valid JSON
        let script = r#"JSON.validate('{"key": "value"}');"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(true)));

        // Invalid JSON
        let script = r#"JSON.validate('not json');"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(false)));
    }

    #[tokio::test]
    async fn test_script_http_url_encode() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"http.urlEncode("hello world");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("hello%20world")));
    }

    #[tokio::test]
    async fn test_script_http_url_decode() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"http.urlDecode("hello%20world");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("hello world")));
    }

    #[tokio::test]
    async fn test_script_with_syntax_error() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script with syntax error
        let script = r#"function { broken"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_execute_simple_string() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let result = engine.execute_script(r#""test""#, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("test")));
    }

    #[tokio::test]
    async fn test_script_with_no_request() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Script that doesn't access request
        let script = r#""no request needed""#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_with_no_response() {
        let engine = ScriptEngine::new();
        let mut ctx = create_empty_script_context();
        ctx.request = Some(crate::request_chaining::ChainRequest {
            id: "test".to_string(),
            method: "GET".to_string(),
            url: "http://example.com".to_string(),
            headers: HashMap::new(),
            body: None,
            depends_on: vec![],
            timeout_secs: None,
            expected_status: None,
            scripting: None,
        });

        // Script that only uses request (pre-script scenario)
        let script = r#"mockforge.request.method"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_concurrent_script_execution() {
        let engine = Arc::new(ScriptEngine::new());
        let ctx = create_empty_script_context();

        // Run multiple scripts concurrently
        let mut handles = vec![];
        for i in 0..5 {
            let engine = engine.clone();
            let ctx = ctx.clone();
            let handle = tokio::spawn(async move {
                let script = format!("{}", i);
                engine.execute_script(&script, &ctx, 1000).await
            });
            handles.push(handle);
        }

        for handle in handles {
            let result = handle.await.unwrap();
            assert!(result.is_ok());
        }
    }

    // Test js_value_to_json_value helper
    #[test]
    fn test_execute_script_in_runtime_success() {
        let ctx = create_empty_script_context();
        let result = execute_script_in_runtime(r#""hello""#, &ctx);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("hello")));
    }

    #[test]
    fn test_execute_script_in_runtime_with_context() {
        let ctx = create_full_script_context();
        let result = execute_script_in_runtime(r#"mockforge.request.method"#, &ctx);
        assert!(result.is_ok());
    }

    #[test]
    fn test_execute_script_in_runtime_error() {
        let ctx = create_empty_script_context();
        let result = execute_script_in_runtime(r#"throw new Error("test");"#, &ctx);
        assert!(result.is_err());
    }

    // Test chain context with different value types
    #[tokio::test]
    async fn test_script_chain_context_number() {
        let engine = ScriptEngine::new();
        let ctx = create_full_script_context();

        let script = r#"mockforge.chain.user_id;"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_chain_context_boolean() {
        let engine = ScriptEngine::new();
        let ctx = create_full_script_context();

        let script = r#"mockforge.chain.is_admin;"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(true)));
    }

    // Test variables with different value types
    #[tokio::test]
    async fn test_script_variables_number() {
        let engine = ScriptEngine::new();
        let ctx = create_full_script_context();

        let script = r#"mockforge.variables.counter;"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_variables_string() {
        let engine = ScriptEngine::new();
        let ctx = create_full_script_context();

        let script = r#"mockforge.variables.name;"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("test")));
    }

    #[tokio::test]
    async fn test_script_arithmetic() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"1 + 2 + 3"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_string_concatenation() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#""hello" + " " + "world""#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("hello world")));
    }

    #[tokio::test]
    async fn test_script_conditional() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"true ? "yes" : "no""#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("yes")));
    }

    #[tokio::test]
    async fn test_script_function_definition_and_call() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"
            function add(a, b) {
                return a + b;
            }
            add(1, 2);
        "#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_arrow_function() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"
            const multiply = (a, b) => a * b;
            multiply(3, 4);
        "#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_array_operations() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"
            const arr = [1, 2, 3];
            arr.length;
        "#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_script_object_access() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"
            const obj = {key: "value"};
            obj.key;
        "#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("value")));
    }

    #[tokio::test]
    async fn test_date_format() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"date.format("2024-01-15T10:30:00+00:00", "%Y-%m-%d");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!("2024-01-15")));
    }

    #[tokio::test]
    async fn test_date_parse() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"date.parse("2024-01-15 10:30:00", "%Y-%m-%d %H:%M:%S");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        let return_val = result.unwrap().return_value;
        assert!(return_val.is_some());
        // Should return RFC3339 formatted timestamp
        assert!(return_val.unwrap().as_str().unwrap().contains("2024-01-15"));
    }

    #[tokio::test]
    async fn test_date_parse_invalid() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"date.parse("invalid", "%Y-%m-%d");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        // Should return empty string for invalid date
        assert_eq!(result.unwrap().return_value, Some(json!("")));
    }

    #[tokio::test]
    async fn test_validate_regex_invalid_pattern() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Invalid regex pattern
        let script = r#"validate.regex("[invalid", "test");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        // Should return false for invalid regex
        assert_eq!(result.unwrap().return_value, Some(json!(false)));
    }

    #[tokio::test]
    async fn test_script_stringify_function() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"stringify("test");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_crypto_base64_decode_invalid() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Invalid base64
        let script = r#"crypto.base64Decode("!!invalid!!");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        // Should return empty string for invalid base64
        assert_eq!(result.unwrap().return_value, Some(json!("")));
    }

    #[tokio::test]
    async fn test_date_add_days_invalid() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Invalid timestamp
        let script = r#"date.addDays("invalid", 1);"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        // Should return empty string for invalid timestamp
        assert_eq!(result.unwrap().return_value, Some(json!("")));
    }

    #[tokio::test]
    async fn test_date_format_invalid() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        // Invalid timestamp
        let script = r#"date.format("invalid", "%Y-%m-%d");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        // Should return empty string for invalid timestamp
        assert_eq!(result.unwrap().return_value, Some(json!("")));
    }

    #[tokio::test]
    async fn test_http_url_encode_special_chars() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"http.urlEncode("a=b&c=d");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        let encoded = result.unwrap().return_value.unwrap();
        assert!(encoded.as_str().unwrap().contains("%3D")); // = encoded
        assert!(encoded.as_str().unwrap().contains("%26")); // & encoded
    }

    #[tokio::test]
    async fn test_json_parse_invalid() {
        let engine = ScriptEngine::new();
        let ctx = create_empty_script_context();

        let script = r#"JSON.parse("invalid json");"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        // Should return "null" for invalid JSON
        assert_eq!(result.unwrap().return_value, Some(json!("null")));
    }

    #[tokio::test]
    async fn test_script_with_complex_chain_context() {
        let engine = ScriptEngine::new();
        let mut ctx = create_empty_script_context();
        ctx.chain_context.insert("float_val".to_string(), json!(3.125));
        ctx.chain_context.insert("bool_val".to_string(), json!(false));

        let script = r#"mockforge.chain.bool_val;"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().return_value, Some(json!(false)));
    }

    #[tokio::test]
    async fn test_script_with_complex_variables() {
        let engine = ScriptEngine::new();
        let mut ctx = create_empty_script_context();
        ctx.variables.insert("obj".to_string(), json!({"nested": "value"}));

        let script = r#""executed";"#;
        let result = engine.execute_script(script, &ctx, 1000).await;
        assert!(result.is_ok());
    }
}