bext-plugin-quickjs 0.2.0

QuickJS sandbox for bext — lightweight JavaScript plugin execution
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
//! QuickJS plugin runtime — loads and manages JS lifecycle plugins.
//!
//! Each plugin gets its own QuickJS Runtime with:
//! - Memory limit (default 64 MB)
//! - Max stack size (default 1 MB)
//! - Interrupt handler for wall-clock timeout enforcement
//! - Sandboxed API surface (no filesystem/network access except via bext.*)

use crate::api::{self, HostBridge};
use bext_plugin_api::lifecycle::LifecyclePlugin;
use bext_plugin_api::types::{PluginManifest, SandboxPermissions};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Instant;

/// Configuration for loading a single QuickJS plugin.
pub struct QuickJsPluginConfig {
    pub name: String,
    /// Path to the .js plugin file.
    pub path: PathBuf,
    pub priority: u32,
    pub permissions: SandboxPermissions,
    pub config: serde_json::Value,
}

/// A loaded QuickJS plugin: owns the runtime + context and implements LifecyclePlugin.
struct QuickJsPlugin {
    manifest: PluginManifest,
    priority: u32,
    rt: rquickjs::Runtime,
    ctx: rquickjs::Context,
    bridge: Arc<HostBridge>,
    /// Call deadline — refreshed before each lifecycle call.
    deadline: Arc<Mutex<Option<Instant>>>,
}

// rquickjs::Runtime and Context are Send (via the `parallel` feature) but not Sync.
// QuickJsPlugin is only used as a transient builder struct before being consumed by
// into_lifecycle_plugins(), where the non-Sync fields are moved into a Mutex.
// No Sync bound is needed here — QuickJsPluginRuntime is used single-threaded.

/// Manages loading and lifecycle of QuickJS plugins.
pub struct QuickJsPluginRuntime {
    storage_root: PathBuf,
    plugins: Vec<QuickJsPlugin>,
}

impl QuickJsPluginRuntime {
    pub fn new(storage_root: PathBuf) -> Self {
        Self {
            storage_root,
            plugins: Vec::new(),
        }
    }

    pub fn load_plugin(&mut self, config: QuickJsPluginConfig) -> Result<(), String> {
        if !config.path.exists() {
            return Err(format!("JS plugin not found: {}", config.path.display()));
        }

        tracing::info!(name = %config.name, path = %config.path.display(), "loading QuickJS plugin");

        let source = std::fs::read_to_string(&config.path).map_err(|e| format!("read JS: {e}"))?;

        // Create runtime with memory + stack limits
        let rt = rquickjs::Runtime::new().map_err(|e| format!("create QuickJS runtime: {e}"))?;

        rt.set_memory_limit(config.permissions.max_memory_mb as usize * 1024 * 1024);
        rt.set_max_stack_size(1024 * 1024); // 1 MB stack

        // Install interrupt handler for wall-clock timeout
        let deadline: Arc<Mutex<Option<Instant>>> = Arc::new(Mutex::new(None));
        let deadline_check = deadline.clone();
        rt.set_interrupt_handler(Some(Box::new(move || {
            if let Ok(guard) = deadline_check.lock() {
                if let Some(dl) = *guard {
                    return Instant::now() > dl;
                }
            }
            false
        })));

        // Create context and register APIs
        let bridge = Arc::new(HostBridge::new(
            config.name.clone(),
            config.permissions,
            &self.storage_root,
            config.config,
        ));

        let ctx =
            rquickjs::Context::full(&rt).map_err(|e| format!("create QuickJS context: {e}"))?;

        // Register globals and evaluate plugin source
        let bridge_ref = bridge.clone();
        ctx.with(|ctx| -> Result<(), String> {
            api::register_globals(&ctx, bridge_ref)
                .map_err(|e| format!("register globals: {e}"))?;

            // Evaluate the plugin source — this defines the exported functions
            ctx.eval::<(), _>(source.as_bytes())
                .map_err(|e| format!("eval plugin: {e}"))?;

            Ok(())
        })?;

        let manifest = PluginManifest {
            name: config.name.clone(),
            version: "1.0.0".into(),
            description: format!("QuickJS plugin: {}", config.path.display()),
            capabilities: vec![bext_plugin_api::types::PluginCapability::Lifecycle],
            provides_capabilities: Vec::new(),
            requires_capabilities: Vec::new(),
        };

        tracing::info!(name = %manifest.name, "QuickJS plugin loaded");

        self.plugins.push(QuickJsPlugin {
            manifest,
            priority: config.priority,
            rt,
            ctx,
            bridge,
            deadline,
        });

        Ok(())
    }

    pub fn into_lifecycle_plugins(&mut self) -> Vec<Box<dyn LifecyclePlugin>> {
        std::mem::take(&mut self.plugins)
            .into_iter()
            .map(|p| {
                let max_time_secs = p.bridge.permissions.max_time_secs;
                Box::new(QuickJsLifecycleAdapter {
                    manifest: p.manifest,
                    priority: p.priority,
                    state: Mutex::new(QuickJsState {
                        ctx: p.ctx,
                        _rt: p.rt,
                        _bridge: p.bridge,
                        deadline: p.deadline,
                        max_time_secs,
                    }),
                }) as Box<dyn LifecyclePlugin>
            })
            .collect()
    }

    pub fn len(&self) -> usize {
        self.plugins.len()
    }

    pub fn is_empty(&self) -> bool {
        self.plugins.is_empty()
    }
}

// ---------------------------------------------------------------------------
// LifecyclePlugin adapter
// ---------------------------------------------------------------------------

struct QuickJsState {
    ctx: rquickjs::Context,
    _rt: rquickjs::Runtime,
    _bridge: Arc<HostBridge>,
    deadline: Arc<Mutex<Option<Instant>>>,
    max_time_secs: u64,
}

// rquickjs::Runtime and Context are Send (via `parallel` feature) but not Sync.
// QuickJsState is only accessed through std::sync::Mutex<QuickJsState> in the
// adapter, which requires T: Send (not T: Sync) to be Send + Sync itself.
// Therefore no unsafe impl is needed — all fields are already Send.

struct QuickJsLifecycleAdapter {
    manifest: PluginManifest,
    priority: u32,
    state: Mutex<QuickJsState>,
}

impl QuickJsLifecycleAdapter {
    /// Set a wall-clock deadline before calling a JS function.
    fn set_deadline(state: &QuickJsState, secs: u64) {
        if let Ok(mut dl) = state.deadline.lock() {
            *dl = Some(Instant::now() + std::time::Duration::from_secs(secs));
        }
    }

    fn clear_deadline(state: &QuickJsState) {
        if let Ok(mut dl) = state.deadline.lock() {
            *dl = None;
        }
    }

    /// Call a global JS function by name, passing JSON args. Returns Ok(()) if the
    /// function doesn't exist (not all hooks are required).
    fn call_lifecycle(
        state: &QuickJsState,
        fn_name: &str,
        args_json: &[&str],
    ) -> Result<(), String> {
        Self::set_deadline(state, state.max_time_secs);
        let result = state.ctx.with(|ctx| -> Result<(), String> {
            let globals = ctx.globals();
            let func: Option<rquickjs::Function> = globals.get(fn_name).ok();

            let func = match func {
                Some(f) if f.is_function() => f,
                _ => return Ok(()), // Hook not defined — that's fine
            };

            // Build JS arguments from JSON strings
            match args_json.len() {
                0 => {
                    func.call::<_, ()>(())
                        .map_err(|e| format!("{fn_name}: {e}"))?;
                }
                1 => {
                    let arg: rquickjs::Value = ctx
                        .json_parse(args_json[0].to_string())
                        .unwrap_or(rquickjs::Value::new_undefined(ctx.clone()));
                    func.call::<_, ()>((arg,))
                        .map_err(|e| format!("{fn_name}: {e}"))?;
                }
                2 => {
                    let arg0: rquickjs::Value = ctx
                        .json_parse(args_json[0].to_string())
                        .unwrap_or(rquickjs::Value::new_undefined(ctx.clone()));
                    let arg1: rquickjs::Value = ctx
                        .json_parse(args_json[1].to_string())
                        .unwrap_or(rquickjs::Value::new_undefined(ctx.clone()));
                    func.call::<_, ()>((arg0, arg1))
                        .map_err(|e| format!("{fn_name}: {e}"))?;
                }
                _ => {
                    return Err(format!("{fn_name}: too many args (max 2)"));
                }
            }

            Ok(())
        });
        Self::clear_deadline(state);
        result
    }
}

impl LifecyclePlugin for QuickJsLifecycleAdapter {
    fn name(&self) -> &str {
        &self.manifest.name
    }

    fn priority(&self) -> u32 {
        self.priority
    }

    fn on_server_start(&self, config_json: &str) -> Result<(), String> {
        let guard = self
            .state
            .lock()
            .map_err(|e| format!("lock poisoned: {e}"))?;
        Self::call_lifecycle(&guard, "onServerStart", &[config_json])
    }

    fn on_server_stop(&self) -> Result<(), String> {
        let guard = self
            .state
            .lock()
            .map_err(|e| format!("lock poisoned: {e}"))?;
        Self::call_lifecycle(&guard, "onServerStop", &[])
    }

    fn on_request_complete(&self, event_json: &str) -> Result<(), String> {
        let guard = self
            .state
            .lock()
            .map_err(|e| format!("lock poisoned: {e}"))?;
        Self::call_lifecycle(&guard, "onRequestComplete", &[event_json])
    }

    fn on_cache_write(&self, key: &str, tags_json: &str) -> Result<(), String> {
        let guard = self
            .state
            .lock()
            .map_err(|e| format!("lock poisoned: {e}"))?;
        let key_json = serde_json::to_string(key).unwrap_or_default();
        Self::call_lifecycle(&guard, "onCacheWrite", &[&key_json, tags_json])
    }

    fn on_cache_invalidate(&self, pattern: &str, count: u32) -> Result<(), String> {
        let guard = self
            .state
            .lock()
            .map_err(|e| format!("lock poisoned: {e}"))?;
        let pattern_json = serde_json::to_string(pattern).unwrap_or_default();
        let count_json = count.to_string();
        Self::call_lifecycle(&guard, "onCacheInvalidate", &[&pattern_json, &count_json])
    }

    fn on_reload(&self) -> Result<(), String> {
        let guard = self
            .state
            .lock()
            .map_err(|e| format!("lock poisoned: {e}"))?;
        Self::call_lifecycle(&guard, "onReload", &[])
    }

    fn cleanup(&self) -> Result<(), String> {
        let guard = self
            .state
            .lock()
            .map_err(|e| format!("lock poisoned: {e}"))?;
        Self::call_lifecycle(&guard, "cleanup", &[])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    /// Helper: create a temp dir + write a JS file, return (dir, file_path).
    fn write_temp_plugin(name: &str, source: &str) -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().expect("create tempdir");
        let path = dir.path().join(format!("{name}.js"));
        std::fs::write(&path, source).expect("write plugin file");
        (dir, path)
    }

    /// Helper: load a plugin from source and return the lifecycle adapter.
    fn load_lifecycle(
        name: &str,
        source: &str,
        permissions: SandboxPermissions,
        config: serde_json::Value,
    ) -> (tempfile::TempDir, Box<dyn LifecyclePlugin>) {
        let (dir, path) = write_temp_plugin(name, source);
        let storage_root = dir.path().join("storage");
        let _ = std::fs::create_dir_all(&storage_root);

        let mut rt = QuickJsPluginRuntime::new(storage_root);
        rt.load_plugin(QuickJsPluginConfig {
            name: name.into(),
            path,
            priority: 500,
            permissions,
            config,
        })
        .expect("load plugin");

        let mut plugins = rt.into_lifecycle_plugins();
        assert_eq!(plugins.len(), 1);
        let plugin = plugins.remove(0);
        (dir, plugin)
    }

    // ── Basic runtime tests ──────────────────────────────────────────

    #[test]
    fn runtime_empty() {
        let rt = QuickJsPluginRuntime::new(PathBuf::from("/tmp/bext-quickjs"));
        assert!(rt.is_empty());
        assert_eq!(rt.len(), 0);
    }

    #[test]
    fn load_nonexistent_fails() {
        let mut rt = QuickJsPluginRuntime::new(PathBuf::from("/tmp/bext-quickjs"));
        let result = rt.load_plugin(QuickJsPluginConfig {
            name: "test".into(),
            path: "/nonexistent/plugin.js".into(),
            priority: 1000,
            permissions: SandboxPermissions::default(),
            config: serde_json::Value::Null,
        });
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not found"));
    }

    // ── Plugin with onServerStart ────────────────────────────────────

    #[test]
    fn on_server_start_called() {
        let source = r#"
            function onServerStart(config) {
                // Store something to prove we ran
                bext.storage.set("started", "yes");
            }
        "#;
        let (dir, plugin) = load_lifecycle(
            "starter",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        let result = plugin.on_server_start("{}");
        assert!(result.is_ok(), "on_server_start failed: {:?}", result);

        // Verify storage was written
        let storage_path = dir.path().join("storage").join("starter").join("started");
        assert!(storage_path.exists(), "storage file should exist");
        let val = std::fs::read_to_string(&storage_path).unwrap();
        assert_eq!(val, "yes");
    }

    // ── Plugin with no functions (all hooks are no-ops) ──────────────

    #[test]
    fn no_functions_all_noop() {
        let source = r#"
            // This plugin defines no lifecycle hooks
            var x = 42;
        "#;
        let (_dir, plugin) = load_lifecycle(
            "empty",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        assert!(plugin.on_server_start("{}").is_ok());
        assert!(plugin.on_server_stop().is_ok());
        assert!(plugin.on_request_complete("{}").is_ok());
        assert!(plugin.on_cache_write("key", "[]").is_ok());
        assert!(plugin.on_cache_invalidate("*", 5).is_ok());
        assert!(plugin.on_reload().is_ok());
        assert!(plugin.cleanup().is_ok());
    }

    // ── onRequestComplete receives correct event data ────────────────

    #[test]
    fn on_request_complete_receives_event() {
        let source = r#"
            function onRequestComplete(event) {
                bext.storage.set("status", String(event.status));
                bext.storage.set("path", event.path);
            }
        "#;
        let (dir, plugin) = load_lifecycle(
            "reqlog",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        let event = serde_json::json!({
            "path": "/api/products",
            "method": "GET",
            "status": 200,
            "render_time_us": 1500
        });
        let result = plugin.on_request_complete(&event.to_string());
        assert!(result.is_ok(), "on_request_complete failed: {:?}", result);

        let storage_dir = dir.path().join("storage").join("reqlog");
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("status")).unwrap(),
            "200"
        );
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("path")).unwrap(),
            "/api/products"
        );
    }

    // ── Plugin manifest (name from config) ───────────────────────────

    #[test]
    fn plugin_manifest_name() {
        let source = "var x = 1;";
        let (_dir, plugin) = load_lifecycle(
            "my-plugin",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        assert_eq!(plugin.name(), "my-plugin");
        assert_eq!(plugin.priority(), 500);
    }

    // ── Memory limit enforcement ─────────────────────────────────────

    #[test]
    fn memory_limit_enforcement() {
        // Try to allocate a huge array that exceeds the memory limit
        let source = r#"
            function onServerStart(config) {
                // Allocate big arrays in a loop to bust the heap limit
                var arrays = [];
                for (var i = 0; i < 100000; i++) {
                    arrays.push(new Array(10000));
                }
            }
        "#;
        let (dir, path) = write_temp_plugin("memhog", source);
        let storage_root = dir.path().join("storage");
        let _ = std::fs::create_dir_all(&storage_root);

        let mut rt = QuickJsPluginRuntime::new(storage_root);
        let perms = SandboxPermissions {
            max_memory_mb: 2, // Only 2 MB
            ..Default::default()
        };
        rt.load_plugin(QuickJsPluginConfig {
            name: "memhog".into(),
            path,
            priority: 1000,
            permissions: perms,
            config: serde_json::Value::Null,
        })
        .expect("load plugin");

        let mut plugins = rt.into_lifecycle_plugins();
        let plugin = plugins.remove(0);

        // Should error due to memory limit
        let result = plugin.on_server_start("{}");
        assert!(result.is_err(), "expected memory limit error");
    }

    // ── Timeout enforcement ──────────────────────────────────────────

    #[test]
    fn timeout_enforcement() {
        let source = r#"
            function onServerStart(config) {
                while (true) {} // infinite loop
            }
        "#;
        let (dir, path) = write_temp_plugin("looper", source);
        let storage_root = dir.path().join("storage");
        let _ = std::fs::create_dir_all(&storage_root);

        let mut rt = QuickJsPluginRuntime::new(storage_root);
        let perms = SandboxPermissions {
            max_time_secs: 1, // 1 second timeout
            ..Default::default()
        };
        rt.load_plugin(QuickJsPluginConfig {
            name: "looper".into(),
            path,
            priority: 1000,
            permissions: perms,
            config: serde_json::Value::Null,
        })
        .expect("load plugin");

        let mut plugins = rt.into_lifecycle_plugins();
        let plugin = plugins.remove(0);

        let start = Instant::now();
        let result = plugin.on_server_start("{}");
        let elapsed = start.elapsed();

        assert!(result.is_err(), "expected timeout error");
        // Should finish within a reasonable time (allow up to 3s for interrupt checking)
        assert!(
            elapsed < std::time::Duration::from_secs(5),
            "timeout took too long: {:?}",
            elapsed
        );
    }

    // ── Console.log doesn't panic ────────────────────────────────────

    #[test]
    fn console_log_no_panic() {
        let source = r#"
            function onServerStart(config) {
                console.log("hello from plugin");
                console.warn("warning msg");
                console.error("error msg");
                console.info("info msg");
                console.debug("debug msg");
            }
        "#;
        let (_dir, plugin) = load_lifecycle(
            "logger",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        let result = plugin.on_server_start("{}");
        assert!(result.is_ok(), "console logging failed: {:?}", result);
    }

    // ── Storage get/set/delete roundtrip ─────────────────────────────

    #[test]
    fn storage_roundtrip() {
        // Use loose equality (== null) since rquickjs maps None → undefined
        let source = r#"
            function onServerStart(config) {
                // Set a value
                var ok = bext.storage.set("counter", "42");
                if (!ok) throw new Error("storage.set failed");

                // Get it back
                var val = bext.storage.get("counter");
                if (val !== "42") throw new Error("expected '42', got: " + val);

                // Delete it
                bext.storage.delete("counter");

                // Should be null/undefined now (loose equality covers both)
                var deleted = bext.storage.get("counter");
                if (deleted != null) throw new Error("expected null/undefined after delete, got: " + deleted);

                // Record success
                bext.storage.set("roundtrip", "passed");
            }
        "#;
        let (dir, plugin) = load_lifecycle(
            "storagetest",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        let result = plugin.on_server_start("{}");
        assert!(result.is_ok(), "storage roundtrip failed: {:?}", result);

        let storage_dir = dir.path().join("storage").join("storagetest");
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("roundtrip")).unwrap(),
            "passed"
        );
    }

    // ── bext.config is readable ──────────────────────────────────────

    #[test]
    fn config_accessible() {
        let source = r#"
            function onServerStart(config) {
                // bext.config is injected at load time
                bext.storage.set("markup", String(bext.config.markup_pct));
                bext.storage.set("discount", String(bext.config.vip_discount));
            }
        "#;
        let config = serde_json::json!({
            "markup_pct": 15,
            "vip_discount": 0.1
        });
        let (dir, plugin) =
            load_lifecycle("configtest", source, SandboxPermissions::default(), config);

        let result = plugin.on_server_start("{}");
        assert!(result.is_ok(), "config access failed: {:?}", result);

        let storage_dir = dir.path().join("storage").join("configtest");
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("markup")).unwrap(),
            "15"
        );
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("discount")).unwrap(),
            "0.1"
        );
    }

    // ── onCacheWrite receives key + tags ─────────────────────────────

    #[test]
    fn on_cache_write_args() {
        let source = r#"
            function onCacheWrite(key, tags) {
                bext.storage.set("cache-key", key);
                bext.storage.set("cache-tags", JSON.stringify(tags));
            }
        "#;
        let (dir, plugin) = load_lifecycle(
            "cachetest",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        let result = plugin.on_cache_write("/products/1", r#"["product","page"]"#);
        assert!(result.is_ok(), "on_cache_write failed: {:?}", result);

        let storage_dir = dir.path().join("storage").join("cachetest");
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("cache-key")).unwrap(),
            "/products/1"
        );
    }

    // ── onCacheInvalidate receives pattern + count ───────────────────

    #[test]
    fn on_cache_invalidate_args() {
        let source = r#"
            function onCacheInvalidate(pattern, count) {
                bext.storage.set("inv-pattern", pattern);
                bext.storage.set("inv-count", String(count));
            }
        "#;
        let (dir, plugin) = load_lifecycle(
            "invtest",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        let result = plugin.on_cache_invalidate("/products/*", 7);
        assert!(result.is_ok(), "on_cache_invalidate failed: {:?}", result);

        let storage_dir = dir.path().join("storage").join("invtest");
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("inv-pattern")).unwrap(),
            "/products/*"
        );
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("inv-count")).unwrap(),
            "7"
        );
    }

    // ── onReload + cleanup ───────────────────────────────────────────

    #[test]
    fn on_reload_and_cleanup() {
        let source = r#"
            function onReload() {
                bext.storage.set("reloaded", "true");
            }
            function cleanup() {
                bext.storage.set("cleaned", "true");
            }
        "#;
        let (dir, plugin) = load_lifecycle(
            "lifecycletest",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        assert!(plugin.on_reload().is_ok());
        assert!(plugin.cleanup().is_ok());

        let storage_dir = dir.path().join("storage").join("lifecycletest");
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("reloaded")).unwrap(),
            "true"
        );
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("cleaned")).unwrap(),
            "true"
        );
    }

    // ── Multiple plugins in one runtime ──────────────────────────────

    #[test]
    fn multiple_plugins() {
        let dir = tempfile::tempdir().expect("create tempdir");
        let storage_root = dir.path().join("storage");
        let _ = std::fs::create_dir_all(&storage_root);

        let path1 = dir.path().join("plugin1.js");
        std::fs::write(
            &path1,
            r#"function onServerStart(c) { bext.storage.set("who", "plugin1"); }"#,
        )
        .unwrap();
        let path2 = dir.path().join("plugin2.js");
        std::fs::write(
            &path2,
            r#"function onServerStart(c) { bext.storage.set("who", "plugin2"); }"#,
        )
        .unwrap();

        let mut rt = QuickJsPluginRuntime::new(storage_root.clone());
        rt.load_plugin(QuickJsPluginConfig {
            name: "p1".into(),
            path: path1,
            priority: 100,
            permissions: SandboxPermissions::default(),
            config: serde_json::Value::Null,
        })
        .unwrap();
        rt.load_plugin(QuickJsPluginConfig {
            name: "p2".into(),
            path: path2,
            priority: 200,
            permissions: SandboxPermissions::default(),
            config: serde_json::Value::Null,
        })
        .unwrap();

        assert_eq!(rt.len(), 2);
        assert!(!rt.is_empty());

        let plugins = rt.into_lifecycle_plugins();
        assert_eq!(plugins.len(), 2);

        for p in &plugins {
            assert!(p.on_server_start("{}").is_ok());
        }

        // Each plugin wrote to its own storage
        assert_eq!(
            std::fs::read_to_string(storage_root.join("p1").join("who")).unwrap(),
            "plugin1"
        );
        assert_eq!(
            std::fs::read_to_string(storage_root.join("p2").join("who")).unwrap(),
            "plugin2"
        );
    }

    // ── JS syntax error during load ──────────────────────────────────

    #[test]
    fn syntax_error_on_load() {
        let source = r#"
            function onServerStart( {{{ INVALID SYNTAX
        "#;
        let (dir, path) = write_temp_plugin("badsyntax", source);
        let storage_root = dir.path().join("storage");
        let _ = std::fs::create_dir_all(&storage_root);

        let mut rt = QuickJsPluginRuntime::new(storage_root);
        let result = rt.load_plugin(QuickJsPluginConfig {
            name: "badsyntax".into(),
            path,
            priority: 1000,
            permissions: SandboxPermissions::default(),
            config: serde_json::Value::Null,
        });
        assert!(result.is_err(), "expected syntax error");
    }

    // ── bext.metric doesn't panic ────────────────────────────────────

    #[test]
    fn metric_emission() {
        let source = r#"
            function onRequestComplete(event) {
                bext.metric("request_count", 1.0, '{"method":"GET"}');
                bext.metric("latency_us", 1500.0); // omitted tags — JS wrapper defaults to "{}"
            }
        "#;
        let (_dir, plugin) = load_lifecycle(
            "metrictest",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        let result = plugin.on_request_complete(r#"{"status":200}"#);
        assert!(result.is_ok(), "metric emission failed: {:?}", result);
    }

    // ── onServerStop ─────────────────────────────────────────────────

    #[test]
    fn on_server_stop() {
        let source = r#"
            function onServerStop() {
                bext.storage.set("stopped", "yes");
            }
        "#;
        let (dir, plugin) = load_lifecycle(
            "stoptest",
            source,
            SandboxPermissions::default(),
            serde_json::json!({}),
        );

        assert!(plugin.on_server_stop().is_ok());

        let storage_dir = dir.path().join("storage").join("stoptest");
        assert_eq!(
            std::fs::read_to_string(storage_dir.join("stopped")).unwrap(),
            "yes"
        );
    }
}