ferridriver-script 0.3.0

Sandboxed QuickJS scripting engine for ferridriver. Runs JS scripts against Page/Browser/Context with bound args, per-call isolation, scoped fs, and structured errors.
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
#![allow(clippy::expect_used, clippy::unwrap_used)]
//! Persistent-session semantics: a `Session` reuses one `QuickJS` VM
//! across many `execute` calls so user `globalThis` state survives
//! REPL-style, while a poisoning timeout marks the VM for rebuild.

use std::sync::Arc;
use std::time::Duration;

use ferridriver_script::{
  InMemoryVars, Outcome, PathSandbox, PluginBinding, RunContext, RunOptions, ScriptEngineConfig, ScriptErrorKind,
  Session, compile_and_extract_plugins,
};

/// A one-tool plugin whose handler bumps a `globalThis` counter so a
/// second invocation in the same session observes the first's state.
const DEMO_PLUGIN: &str = "defineTool({ name: 'demo', handler: async ({ args }) => { \
  globalThis.__n = (globalThis.__n || 0) + 1; return { n: globalThis.__n, got: args }; } });";

/// Bundle + compile the demo plugin through the production pipeline
/// (rolldown -> bytecode) and wrap it as a `PluginBinding`.
async fn demo_binding() -> (tempfile::TempDir, PluginBinding) {
  let tmp = tempfile::tempdir().expect("tempdir");
  let path = tmp.path().join("demo.js");
  std::fs::write(&path, DEMO_PLUGIN).expect("write plugin");
  let (compiled, failures) = compile_and_extract_plugins(&[path]).await;
  assert!(failures.is_empty(), "compile failures: {failures:?}");
  let cp = compiled.into_iter().next().expect("one compiled plugin");
  assert!(!cp.bytecode.is_empty(), "compiled bytecode must be non-empty");
  (tmp, PluginBinding { bytecode: cp.bytecode })
}

async fn run_demo_plugin_twice() {
  let (_plugin_tmp, binding) = demo_binding().await;
  let tmp = tempfile::tempdir().expect("tempdir");
  let sandbox = PathSandbox::new(tmp.path()).expect("sandbox");
  let ctx = RunContext {
    vars: Arc::new(InMemoryVars::new()),
    sandbox: Arc::new(sandbox),
    artifacts: None,
    page: None,
    browser_context: None,
    request: None,
    browser: None,
    plugins: vec![binding],
    trusted_modules: false,
    host: ferridriver_script::ExtensionHost::Script,
    caps: ferridriver_script::ScriptCaps::default(),
  };
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  let r1 = session
    .execute(
      "return await plugins['demo']({ x: 1 });",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match r1.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!({ "n": 1, "got": { "x": 1 } })),
    Outcome::Error { error } => panic!("plugin call 1 failed: {error:?}"),
  }

  // Second invocation in the SAME session sees the handler's prior
  // `globalThis` state — proves plugin install-once + persistent VM.
  let r2 = session
    .execute(
      "return await plugins['demo']({ x: 2 });",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match r2.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!({ "n": 2, "got": { "x": 2 } })),
    Outcome::Error { error } => panic!("plugin call 2 failed: {error:?}"),
  }
}

#[tokio::test(flavor = "multi_thread")]
async fn typescript_plugin_with_local_import_bundles_and_runs() {
  // Headline migration capability: a `.ts` plugin that imports a
  // plugin-local `.ts` helper. rolldown must transpile + inline the
  // import; the compiled bytecode then runs with no resolver in-session.
  let tmp = tempfile::tempdir().expect("tempdir");
  std::fs::write(
    tmp.path().join("helper.ts"),
    "export const tag = (n: number): string => `t${n}`;\n",
  )
  .expect("write helper");
  std::fs::write(
    tmp.path().join("plug.ts"),
    "import { tag } from './helper';\n\
     interface In { n: number }\n\
     defineTool({ name: 'ts', exposeAsTool: true, \
       async handler({ args }: { args: In }) { return { tag: tag(args.n) }; } });\n",
  )
  .expect("write plugin");

  let (compiled, failures) = compile_and_extract_plugins(&[tmp.path().join("plug.ts")]).await;
  assert!(failures.is_empty(), "compile failures: {failures:?}");
  let cp = compiled.into_iter().next().expect("one compiled plugin");

  let sb_tmp = tempfile::tempdir().expect("tempdir");
  let ctx = RunContext {
    vars: Arc::new(InMemoryVars::new()),
    sandbox: Arc::new(PathSandbox::new(sb_tmp.path()).expect("sandbox")),
    artifacts: None,
    page: None,
    browser_context: None,
    request: None,
    browser: None,
    plugins: vec![PluginBinding { bytecode: cp.bytecode }],
    trusted_modules: false,
    host: ferridriver_script::ExtensionHost::Script,
    caps: ferridriver_script::ScriptCaps::default(),
  };
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");
  let r = session
    .execute(
      "return await plugins['ts']({ n: 7 });",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match r.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!({ "tag": "t7" })),
    Outcome::Error { error } => panic!("ts plugin failed: {error:?}"),
  }
}

#[tokio::test(flavor = "multi_thread")]
async fn allow_net_capability_is_enforced_on_the_request_binding() {
  // The `net` capability must default-deny once declared: a host not in
  // the list is rejected BEFORE the call, and an allowed host passes the
  // guard through to the real client (where it fails for an unrelated,
  // non-allow.net reason — proving the guard let it through).
  const NET_PLUGIN: &str = "defineTool({ name: 'net', \
    allow: { net: ['127.0.0.1'] }, \
    handler: async ({ args, request }) => { await request.get(args.url); return 'ok'; } });";
  let tmp = tempfile::tempdir().expect("tempdir");
  let path = tmp.path().join("net.js");
  std::fs::write(&path, NET_PLUGIN).expect("write plugin");
  let (compiled, failures) = compile_and_extract_plugins(&[path]).await;
  assert!(failures.is_empty(), "compile failures: {failures:?}");
  let cp = compiled.into_iter().next().expect("one compiled plugin");

  let sb_tmp = tempfile::tempdir().expect("tempdir");
  let request = Arc::new(ferridriver::http_client::HttpClient::new(
    ferridriver::http_client::HttpClientOptions::default(),
  ));
  let ctx = RunContext {
    vars: Arc::new(InMemoryVars::new()),
    sandbox: Arc::new(PathSandbox::new(sb_tmp.path()).expect("sandbox")),
    artifacts: None,
    page: None,
    browser_context: None,
    request: Some(request),
    browser: None,
    plugins: vec![PluginBinding { bytecode: cp.bytecode }],
    trusted_modules: false,
    host: ferridriver_script::ExtensionHost::Script,
    caps: ferridriver_script::ScriptCaps::default(),
  };
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  // Disallowed host: rejected by the capability guard, no call made.
  let blocked = session
    .execute(
      "return await plugins['net']({ url: 'http://blocked.test/' });",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match blocked.result.outcome {
    Outcome::Error { error } => {
      assert!(
        error.message.contains("not in allow.net") && error.message.contains("blocked.test"),
        "expected an allow.net denial naming the host, got: {}",
        error.message
      );
    },
    Outcome::Ok { .. } => panic!("disallowed host must be rejected by the net capability"),
  }

  // Allowed host: guard passes; the real client is reached and fails
  // for a non-capability reason (connection refused on port 1).
  let allowed = session
    .execute(
      "return await plugins['net']({ url: 'http://127.0.0.1:1/' });",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match allowed.result.outcome {
    Outcome::Error { error } => assert!(
      !error.message.contains("allow.net"),
      "allowed host must pass the guard; got an allow.net error instead: {}",
      error.message
    ),
    Outcome::Ok { .. } => {},
  }
}

/// Rule 9: the `allow.net` allow-list must bind the global `fetch` too,
/// not only the plugin's `request` arg. Before this fix a net-restricted
/// tool could reach any host via `fetch` (the global was wired straight
/// to the raw session context). Proven page-visible: a disallowed host
/// is rejected with the allow.net denial BEFORE any I/O; an allowed host
/// passes the guard and fails only for an unrelated connection reason.
#[tokio::test(flavor = "multi_thread")]
async fn allow_net_capability_is_enforced_on_the_global_fetch() {
  const NET_PLUGIN: &str = "defineTool({ name: 'netf', \
    allow: { net: ['127.0.0.1'] }, \
    handler: async ({ args }) => { const r = await fetch(args.url); return r.status; } });";
  let tmp = tempfile::tempdir().expect("tempdir");
  let path = tmp.path().join("netf.js");
  std::fs::write(&path, NET_PLUGIN).expect("write plugin");
  let (compiled, failures) = compile_and_extract_plugins(&[path]).await;
  assert!(failures.is_empty(), "compile failures: {failures:?}");
  let cp = compiled.into_iter().next().expect("one compiled plugin");

  let sb_tmp = tempfile::tempdir().expect("tempdir");
  let request = Arc::new(ferridriver::http_client::HttpClient::new(
    ferridriver::http_client::HttpClientOptions::default(),
  ));
  let ctx = RunContext {
    vars: Arc::new(InMemoryVars::new()),
    sandbox: Arc::new(PathSandbox::new(sb_tmp.path()).expect("sandbox")),
    artifacts: None,
    page: None,
    browser_context: None,
    request: Some(request),
    browser: None,
    plugins: vec![PluginBinding { bytecode: cp.bytecode }],
    trusted_modules: false,
    host: ferridriver_script::ExtensionHost::Script,
    caps: ferridriver_script::ScriptCaps::default(),
  };
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  // Disallowed host: rejected by the capability guard before any I/O.
  let blocked = session
    .execute(
      "return await plugins['netf']({ url: 'http://blocked.test/' });",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match blocked.result.outcome {
    Outcome::Error { error } => assert!(
      error.message.contains("not in allow.net") && error.message.contains("blocked.test"),
      "fetch to a disallowed host must be rejected by allow.net, got: {}",
      error.message
    ),
    Outcome::Ok { .. } => panic!("disallowed fetch host must be rejected by the net capability"),
  }

  // Allowed host: guard passes; the real client is reached and fails for
  // a non-capability reason (connection refused on port 1).
  let allowed = session
    .execute(
      "return await plugins['netf']({ url: 'http://127.0.0.1:1/' });",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match allowed.result.outcome {
    Outcome::Error { error } => assert!(
      !error.message.contains("allow.net"),
      "allowed fetch host must pass the guard; got an allow.net error: {}",
      error.message
    ),
    Outcome::Ok { .. } => {},
  }
}

/// The per-poll policy bracket must not leak across tools. Two tools in
/// one VM: `restricted` (allow.net = [127.0.0.1]) and `open` (no net
/// capability). Run concurrently via `Promise.all` so their handler
/// futures interleave at awaits. `restricted`'s fetch to a disallowed
/// host must still be denied, while `open`'s fetch is unrestricted —
/// proving the active policy follows whichever continuation is running,
/// not whichever ran last.
#[tokio::test(flavor = "multi_thread")]
async fn fetch_net_policy_does_not_leak_between_concurrent_tools() {
  const PLUGIN: &str = "defineTool({ name: 'restricted', allow: { net: ['127.0.0.1'] }, \
      handler: async ({ args }) => { try { await fetch(args.url); return 'reached'; } \
        catch (e) { return 'denied:' + String(e.message || e); } } }); \
    defineTool({ name: 'open', \
      handler: async ({ args }) => { try { await fetch(args.url); return 'reached'; } \
        catch (e) { return 'err:' + String(e.message || e); } } });";
  let tmp = tempfile::tempdir().expect("tempdir");
  let path = tmp.path().join("leak.js");
  std::fs::write(&path, PLUGIN).expect("write plugin");
  let (compiled, failures) = compile_and_extract_plugins(&[path]).await;
  assert!(failures.is_empty(), "compile failures: {failures:?}");
  let cp = compiled.into_iter().next().expect("one compiled plugin");

  let sb_tmp = tempfile::tempdir().expect("tempdir");
  let ctx = RunContext {
    vars: Arc::new(InMemoryVars::new()),
    sandbox: Arc::new(PathSandbox::new(sb_tmp.path()).expect("sandbox")),
    artifacts: None,
    page: None,
    browser_context: None,
    request: Some(Arc::new(ferridriver::http_client::HttpClient::new(
      ferridriver::http_client::HttpClientOptions::default(),
    ))),
    browser: None,
    plugins: vec![PluginBinding { bytecode: cp.bytecode }],
    trusted_modules: false,
    host: ferridriver_script::ExtensionHost::Script,
    caps: ferridriver_script::ScriptCaps::default(),
  };
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  let r = session
    .execute(
      "const [a, b] = await Promise.all([ \
         plugins['restricted']({ url: 'http://blocked.test/' }), \
         plugins['open']({ url: 'http://127.0.0.1:1/' }) ]); \
       return { restricted: a, open: b };",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match r.result.outcome {
    Outcome::Ok { success } => {
      let restricted = success.value["restricted"].as_str().unwrap_or_default();
      let open = success.value["open"].as_str().unwrap_or_default();
      assert!(
        restricted.contains("denied:") && restricted.contains("not in allow.net"),
        "restricted tool's fetch must be denied by allow.net even under concurrency, got: {restricted}"
      );
      assert!(
        !open.contains("not in allow.net"),
        "the unrestricted tool's fetch must not inherit another tool's allow.net, got: {open}"
      );
    },
    Outcome::Error { error } => panic!("concurrent tool run failed: {error:?}"),
  }
}

#[tokio::test(flavor = "multi_thread")]
async fn extension_branches_on_ferridriver_host_flag() {
  // One extension file, two contributions gated on the native
  // `ferridriver.host` flag: a tool only under MCP, a step only under
  // BDD. Under host=Mcp the tool registers (callable); under host=Bdd
  // it does NOT (the `plugins.<name>` binding is absent).
  const EXT: &str = "if (ferridriver.host === 'mcp') { \
      defineTool({ name: 'mcpOnly', handler: async () => 'tool-ran' }); \
    } \
    if (ferridriver.host === 'bdd') { Given('a step', () => {}); }";
  let tmp = tempfile::tempdir().expect("tempdir");
  let path = tmp.path().join("ext.js");
  std::fs::write(&path, EXT).expect("write ext");
  let (compiled, failures) = compile_and_extract_plugins(&[path]).await;
  assert!(failures.is_empty(), "compile failures: {failures:?}");
  let cp = compiled.into_iter().next().expect("one compiled");

  let mk = |host| {
    let sb = tempfile::tempdir().expect("tempdir");
    let ctx = RunContext {
      vars: Arc::new(InMemoryVars::new()),
      sandbox: Arc::new(PathSandbox::new(sb.path()).expect("sandbox")),
      artifacts: None,
      page: None,
      browser_context: None,
      request: None,
      browser: None,
      plugins: vec![PluginBinding {
        bytecode: cp.bytecode.clone(),
      }],
      trusted_modules: false,
      host,
      caps: ferridriver_script::ScriptCaps::default(),
    };
    (sb, ctx)
  };

  // host = Mcp -> the tool registered and is callable.
  let (_sb1, ctx) = mk(ferridriver_script::ExtensionHost::Mcp);
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");
  let r = session
    .execute("return await plugins['mcpOnly']({});", &[], RunOptions::default(), &ctx)
    .await;
  match r.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!("tool-ran")),
    Outcome::Error { error } => panic!("mcp host should expose the tool: {error:?}"),
  }

  // host = Bdd -> the tool was NOT registered; the binding is absent.
  let (_sb2, ctx) = mk(ferridriver_script::ExtensionHost::Bdd);
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");
  let r = session
    .execute("return typeof plugins['mcpOnly'];", &[], RunOptions::default(), &ctx)
    .await;
  match r.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!("undefined")),
    Outcome::Error { error } => panic!("bdd host lookup should be undefined, not error: {error:?}"),
  }
}

#[tokio::test(flavor = "multi_thread")]
async fn plugin_bytecode_path_installs_and_persists() {
  // Exercises the production path: rolldown-bundled plugin compiled once
  // to bytecode, `Module::load`ed into the session VM, handler state
  // persisting across two invocations in the same session.
  run_demo_plugin_twice().await;
}

fn make_ctx() -> (tempfile::TempDir, RunContext) {
  let tmp = tempfile::tempdir().expect("tempdir");
  let sandbox = PathSandbox::new(tmp.path()).expect("sandbox");
  let ctx = RunContext {
    vars: Arc::new(InMemoryVars::new()),
    sandbox: Arc::new(sandbox),
    artifacts: None,
    page: None,
    browser_context: None,
    request: None,
    browser: None,
    plugins: Vec::new(),
    trusted_modules: false,
    host: ferridriver_script::ExtensionHost::Script,
    caps: ferridriver_script::ScriptCaps::default(),
  };
  (tmp, ctx)
}

#[tokio::test(flavor = "multi_thread")]
async fn globals_persist_across_executions() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  let r1 = session
    .execute(
      "globalThis.h = () => 42; return null;",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  assert!(r1.result.is_ok(), "{:?}", r1.result);
  assert!(!r1.poisoned);

  // Second execution sees the function defined by the first (the user's
  // own chosen contract: `globalThis.h = () => 42` then `h()`).
  let r2 = session.execute("return h();", &[], RunOptions::default(), &ctx).await;
  match r2.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!(42)),
    Outcome::Error { error } => panic!("expected 42, got error: {error:?}"),
  }
  assert!(!r2.poisoned);
}

#[tokio::test(flavor = "multi_thread")]
async fn let_const_inside_call_do_not_persist() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  let r1 = session
    .execute("let x = 5; return x;", &[], RunOptions::default(), &ctx)
    .await;
  assert!(r1.result.is_ok(), "{:?}", r1.result);

  // `let`/`const` are scoped to the per-call async wrapper, not global.
  let r2 = session
    .execute("return typeof x;", &[], RunOptions::default(), &ctx)
    .await;
  match r2.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!("undefined")),
    Outcome::Error { error } => panic!("expected undefined, got error: {error:?}"),
  }
}

#[tokio::test(flavor = "multi_thread")]
async fn plain_throw_does_not_poison_and_state_survives() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  session
    .execute("globalThis.keep = 'alive'; return 1;", &[], RunOptions::default(), &ctx)
    .await;

  let thrown = session
    .execute("throw new Error('boom');", &[], RunOptions::default(), &ctx)
    .await;
  match thrown.result.outcome {
    Outcome::Error { error } => {
      assert_eq!(error.kind, ScriptErrorKind::Runtime);
      assert!(error.message.contains("boom"), "got: {}", error.message);
    },
    Outcome::Ok { .. } => panic!("expected the throw to surface as an error"),
  }
  // A plain JS throw must NOT poison the VM — state is intact.
  assert!(!thrown.poisoned, "plain throw must not poison the session");

  let after = session
    .execute("return globalThis.keep;", &[], RunOptions::default(), &ctx)
    .await;
  match after.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!("alive")),
    Outcome::Error { error } => panic!("state lost after throw: {error:?}"),
  }
}

#[tokio::test(flavor = "multi_thread")]
async fn timeout_poisons_the_session() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  let timed = session
    .execute(
      "while (true) { /* spin */ }",
      &[],
      RunOptions {
        timeout: Some(Duration::from_millis(150)),
        ..RunOptions::default()
      },
      &ctx,
    )
    .await;
  match timed.result.outcome {
    Outcome::Error { error } => assert_eq!(error.kind, ScriptErrorKind::Timeout),
    Outcome::Ok { .. } => panic!("expected timeout"),
  }
  // A fired timeout interrupt halts the interpreter mid-run: the VM is
  // poisoned and the caller must discard it.
  assert!(timed.poisoned, "a timeout must poison the session");
}

#[tokio::test(flavor = "multi_thread")]
async fn framework_globals_refresh_each_call() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  // `vars` is a framework binding refreshed every call; its backing
  // store is shared, so a value set in call 1 is visible in call 2.
  session
    .execute("vars.set('k', 'v'); return null;", &[], RunOptions::default(), &ctx)
    .await;
  let r = session
    .execute("return vars.get('k');", &[], RunOptions::default(), &ctx)
    .await;
  match r.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!("v")),
    Outcome::Error { error } => panic!("expected 'v', got error: {error:?}"),
  }
}

// ── Runtime shims: timers, URL, web polyfills, proper console ─────────────

#[tokio::test(flavor = "multi_thread")]
async fn set_timeout_resolves_inside_execute() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");
  let r = session
    .execute(
      "return await new Promise((resolve) => setTimeout(() => resolve(7), 20));",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match r.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!(7)),
    Outcome::Error { error } => panic!("setTimeout did not resolve: {error:?}"),
  }
  assert!(!r.poisoned);
}

#[tokio::test(flavor = "multi_thread")]
async fn timer_handle_persists_and_clears_across_calls() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  // Call 1: arm a long timeout, stash its handle on globalThis.
  let r1 = session
    .execute(
      "globalThis.__t = setTimeout(() => { globalThis.__fired = true; }, 10000); \
       return typeof globalThis.__t;",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  assert!(r1.result.is_ok(), "{:?}", r1.result);

  // Call 2: the handle survived REPL-style; clearTimeout accepts it.
  let r2 = session
    .execute(
      "clearTimeout(globalThis.__t); return globalThis.__fired === true;",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match r2.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!(false), "timer must not have fired"),
    Outcome::Error { error } => panic!("clearTimeout across calls failed: {error:?}"),
  }
}

#[tokio::test(flavor = "multi_thread")]
async fn url_and_search_params_work() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");
  let r = session
    .execute(
      "const p = new URLSearchParams('a=1&b=2'); p.append('b', '3'); \
       return [p.get('a'), p.getAll('b').join(',')];",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match r.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!(["1", "2,3"])),
    Outcome::Error { error } => panic!("URLSearchParams failed: {error:?}"),
  }
}

#[tokio::test(flavor = "multi_thread")]
async fn web_polyfills_text_codec_base64_microtask() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");
  let r = session
    .execute(
      "const enc = new TextEncoder().encode('hi€'); \
       const dec = new TextDecoder().decode(enc); \
       let mt = 0; queueMicrotask(() => { mt = 1; }); \
       await Promise.resolve(); \
       return { len: enc.length, dec, b64: btoa('hi'), round: atob(btoa('xy')), mt };",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match r.result.outcome {
    Outcome::Ok { success } => {
      assert_eq!(
        success.value["len"],
        serde_json::json!(5),
        "hi€ = 5 UTF-8 bytes: {success:?}"
      );
      assert_eq!(success.value["dec"], serde_json::json!("hi€"));
      assert_eq!(success.value["b64"], serde_json::json!("aGk="));
      assert_eq!(success.value["round"], serde_json::json!("xy"));
      assert_eq!(
        success.value["mt"],
        serde_json::json!(1),
        "queueMicrotask must have run"
      );
    },
    Outcome::Error { error } => panic!("web polyfills failed: {error:?}"),
  }
}

#[tokio::test(flavor = "multi_thread")]
async fn console_uses_node_style_formatter_and_is_captured() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");
  let r = session
    .execute(
      "console.log('n =', 42, { a: 1 }); console.warn(['x', 'y']); return null;",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  assert!(r.result.is_ok(), "{:?}", r.result);
  let console = &r.result.console;
  assert_eq!(console.len(), 2, "two console entries: {console:?}");
  // Top-level string + number stay unquoted; object renders Node-style
  // (not JSON.stringify's {"a":1}).
  let line0 = &console[0].message;
  assert!(line0.starts_with("n = 42 "), "got: {line0}");
  assert!(line0.contains("a: 1"), "object Node-style, got: {line0}");
  // Arrays render structurally (`[ x, y ]`) rather than via
  // JSON.stringify (`["x","y"]`) — the Node-ish renderer.
  assert!(
    console[1].message.contains("[ x, y ]"),
    "array rendered structurally, got: {}",
    console[1].message
  );
}

#[tokio::test(flavor = "multi_thread")]
async fn native_url_class_parses_and_exposes_search_params() {
  let (_tmp, ctx) = make_ctx();
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");
  let r = session
    .execute(
      "const u = new URL('https://ex.com:8443/a/b?x=1&y=2#frag'); \
       return { href: u.href, host: u.host, hostname: u.hostname, port: u.port, \
                proto: u.protocol, path: u.pathname, search: u.search, hash: u.hash, \
                origin: u.origin, sp: u.searchParams.get('y'), str: String(u) };",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match r.result.outcome {
    Outcome::Ok { success } => {
      let v = &success.value;
      assert_eq!(v["host"], serde_json::json!("ex.com:8443"), "{v}");
      assert_eq!(v["hostname"], serde_json::json!("ex.com"));
      assert_eq!(v["port"], serde_json::json!("8443"));
      assert_eq!(v["proto"], serde_json::json!("https:"));
      assert_eq!(v["path"], serde_json::json!("/a/b"));
      assert_eq!(v["search"], serde_json::json!("?x=1&y=2"));
      assert_eq!(v["hash"], serde_json::json!("#frag"));
      assert_eq!(v["origin"], serde_json::json!("https://ex.com:8443"));
      assert_eq!(v["sp"], serde_json::json!("2"), "searchParams via native URL: {v}");
      assert_eq!(v["str"], serde_json::json!("https://ex.com:8443/a/b?x=1&y=2#frag"));
    },
    Outcome::Error { error } => panic!("native URL failed: {error:?}"),
  }
}

async fn binding_from(src: &str) -> (tempfile::TempDir, Result<PluginBinding, String>) {
  let tmp = tempfile::tempdir().expect("tempdir");
  let path = tmp.path().join("ext.ts");
  std::fs::write(&path, src).expect("write plugin");
  let (compiled, failures) = compile_and_extract_plugins(&[path]).await;
  if let Some((_, e)) = failures.into_iter().next() {
    return (tmp, Err(e.message));
  }
  let cp = compiled.into_iter().next().expect("one compiled plugin");
  (tmp, Ok(PluginBinding { bytecode: cp.bytecode }))
}

#[tokio::test(flavor = "multi_thread")]
async fn duplicate_tool_name_is_rejected_at_load() {
  // Two defineTool calls with the same name must fail the file (the
  // shared registry rejects the second) instead of silently letting the
  // last registration clobber the binding.
  let (_tmp, res) = binding_from(
    "defineTool({ name: 'dup', handler: async () => 1 });\n\
     defineTool({ name: 'dup', handler: async () => 2 });\n",
  )
  .await;
  let err = res.expect_err("duplicate tool name must fail compilation");
  assert!(err.contains("duplicate tool name `dup`"), "unexpected error: {err}");

  // An empty name is likewise rejected.
  let (_tmp2, res2) = binding_from("defineTool({ name: '  ', handler: async () => 1 });\n").await;
  let err2 = res2.expect_err("empty tool name must fail compilation");
  assert!(err2.contains("non-empty string"), "unexpected error: {err2}");
}

#[tokio::test(flavor = "multi_thread")]
async fn per_tool_timeout_ms_is_enforced_for_every_caller() {
  // `timeoutMs` races the handler natively in dispatch_tool, so the
  // bound holds for an in-VM `plugins.<name>()` call (not only the MCP
  // entry point). A handler that sleeps past the bound rejects; a fast
  // one resolves.
  let (_tmp, binding) = binding_from(
    "defineTool({ name: 'slow', timeoutMs: 50, handler: async () => { \
       await new Promise(r => setTimeout(r, 400)); return 'late'; } });\n\
     defineTool({ name: 'fast', timeoutMs: 5000, handler: async () => 'quick' });\n",
  )
  .await;
  let binding = binding.expect("compiles");

  let tmp = tempfile::tempdir().expect("tempdir");
  let sandbox = PathSandbox::new(tmp.path()).expect("sandbox");
  let ctx = RunContext {
    vars: Arc::new(InMemoryVars::new()),
    sandbox: Arc::new(sandbox),
    artifacts: None,
    page: None,
    browser_context: None,
    request: None,
    browser: None,
    plugins: vec![binding],
    trusted_modules: false,
    host: ferridriver_script::ExtensionHost::Script,
    caps: ferridriver_script::ScriptCaps::default(),
  };
  let session = Session::create(ScriptEngineConfig::default(), &ctx)
    .await
    .expect("session create");

  let slow = session
    .execute(
      "try { await plugins['slow'](); return 'resolved'; } catch (e) { return String(e); }",
      &[],
      RunOptions::default(),
      &ctx,
    )
    .await;
  match slow.result.outcome {
    Outcome::Ok { success } => {
      let s = success.value.as_str().unwrap_or_default();
      assert!(
        s.contains("timed out after 50ms"),
        "slow tool should have timed out, got: {s}"
      );
    },
    Outcome::Error { error } => panic!("expected caught rejection, not engine error: {error:?}"),
  }

  let fast = session
    .execute("return await plugins['fast']();", &[], RunOptions::default(), &ctx)
    .await;
  match fast.result.outcome {
    Outcome::Ok { success } => assert_eq!(success.value, serde_json::json!("quick")),
    Outcome::Error { error } => panic!("fast tool within its timeout must resolve: {error:?}"),
  }
}