lanekeep-js 0.1.1

Embedded JavaScript sandbox and host API for lanekeep rules.
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
//! Module resolution and loading for rule files.
//!
//! Rules are ES modules. They may import from `lanekeep` and from each other; nothing else
//! resolves. There is no `node_modules` lookup, no bare-specifier resolution, and no way to
//! reach a file outside the rules root.
//!
//! # Confinement
//!
//! The rules root is canonicalized once at construction, and every resolved module is
//! canonicalized and checked against it. Canonicalizing rather than comparing strings is
//! what makes the check hold against symlinks: a link inside the root pointing at
//! `/etc/passwd` resolves to a path outside the root and is rejected, where a lexical
//! comparison would see an innocent-looking relative path and allow it.
//!
//! Traversal is also rejected lexically, before touching the filesystem, so `../../secrets`
//! produces a message about escaping the root rather than a confusing "not found".

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;

use lanekeep_lang::Language;
use rquickjs::loader::{ImportAttributes, Loader, Resolver};
use rquickjs::module::{Declared, Module};
use rquickjs::{Ctx, Error as JsError};
use thiserror::Error;

use crate::files::normalize;
use crate::typescript::strip_types;

/// The specifier that resolves to lanekeep's own module.
pub const HOST_MODULE: &str = "lanekeep";

/// The host module.
///
/// `defineRule` and `defineConfig` are identity functions, and that is not a placeholder —
/// it is what they are. Their entire purpose is to give the TypeScript compiler something
/// to infer against in the author's editor, which costs nothing at runtime.
const HOST_MODULE_SOURCE: &str = r"
    export function defineRule(rule) { return rule; }
    export function defineConfig(config) { return config; }
";

/// Resolves a built-in rule name to its embedded source.
///
/// A function rather than a dependency, so this crate stays unaware of which rules ship —
/// `lanekeep-js` sits below `lanekeep-rules`, and reaching upward for them would invert the
/// layering for no gain.
pub type BuiltinSource = fn(&str) -> Option<&'static str>;

/// The default: no built-ins, so a bare `lanekeep-js` resolves only project modules.
fn no_builtins(_name: &str) -> Option<&'static str> {
    None
}

/// The prefix a built-in specifier carries, as in `lanekeep/no-default-export`.
const BUILTIN_PREFIX: &str = "lanekeep/";

/// Extensions tried for a specifier that does not name one, in order.
const EXTENSIONS: &[&str] = &["ts", "tsx", "js", "jsx", "mjs"];

/// Why a module specifier could not be resolved.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ResolveError {
    /// A bare specifier, which would be an npm package.
    #[error(
        "cannot import `{specifier}`\n  \
         rule modules run in a sandbox with no package resolution, so only `lanekeep` and \
         relative paths starting with `./` or `../` can be imported\n  \
         if this needs a package, inline what you need from it instead"
    )]
    BareSpecifier {
        /// The specifier as written.
        specifier: String,
    },

    /// The specifier resolves outside the rules root.
    #[error(
        "cannot import `{specifier}`\n  \
         it resolves outside the rules directory, and rule modules may only import from \
         within it"
    )]
    EscapesRoot {
        /// The specifier as written.
        specifier: String,
    },

    /// Nothing exists at the specifier.
    #[error("cannot find module `{specifier}`\n  tried: {tried}")]
    NotFound {
        /// The specifier as written.
        specifier: String,
        /// The candidate paths that were tried.
        tried: String,
    },

    /// The module exists but could not be read.
    #[error("cannot read module `{path}`: {detail}")]
    Unreadable {
        /// The path that failed.
        path: String,
        /// The underlying reason.
        detail: String,
    },
}

/// Where rule modules live, and what may be imported.
#[derive(Debug, Clone)]
pub struct RuleRoot {
    root: PathBuf,
    builtins: BuiltinSource,
}

impl RuleRoot {
    /// Anchor resolution at a directory.
    ///
    /// # Errors
    ///
    /// Fails if the directory does not exist or cannot be canonicalized.
    pub fn new(root: impl AsRef<Path>) -> Result<Self, ResolveError> {
        let root = root.as_ref();
        let canonical = root.canonicalize().map_err(|e| ResolveError::Unreadable {
            path: root.display().to_string(),
            detail: e.to_string(),
        })?;
        Ok(Self {
            root: canonical,
            builtins: no_builtins,
        })
    }

    /// Serve built-in rules from embedded sources.
    ///
    /// Built-ins resolve before anything on disk, so a project file cannot shadow one —
    /// a rule whose behavior depended on whether a same-named file happened to exist
    /// would be impossible to reason about.
    #[must_use]
    pub const fn with_builtins(mut self, builtins: BuiltinSource) -> Self {
        self.builtins = builtins;
        self
    }

    /// The canonical root.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.root
    }

    /// Resolve a specifier against the module that imported it.
    ///
    /// # Errors
    ///
    /// Returns [`ResolveError`] for a bare specifier, an escape from the root, or a
    /// specifier matching no file.
    pub fn resolve(&self, base: &str, specifier: &str) -> Result<PathBuf, ResolveError> {
        if specifier == HOST_MODULE {
            return Ok(PathBuf::from(HOST_MODULE));
        }

        // Built-ins resolve before the filesystem is consulted at all.
        if let Some(name) = specifier.strip_prefix(BUILTIN_PREFIX) {
            return if (self.builtins)(name).is_some() {
                Ok(PathBuf::from(specifier))
            } else {
                Err(ResolveError::NotFound {
                    specifier: specifier.to_owned(),
                    tried: "no built-in rule by that name".to_owned(),
                })
            };
        }

        // The entry module arrives as an already-resolved absolute path, because that is
        // what the caller hands the engine to import. Accepting one is therefore necessary,
        // but only for the entry: an empty base means nothing imported this.
        //
        // A rule writing `import '/etc/passwd'` always has a base — the importing module's
        // own path — so it falls through to the bare-specifier rejection below rather than
        // through this door. Containment is still checked either way.
        if Path::new(specifier).is_absolute() {
            if !base.is_empty() {
                return Err(ResolveError::BareSpecifier {
                    specifier: specifier.to_owned(),
                });
            }
            return self.resolve_within(specifier, &normalize(Path::new(specifier)));
        }

        if !specifier.starts_with('.') {
            return Err(ResolveError::BareSpecifier {
                specifier: specifier.to_owned(),
            });
        }

        let base_dir = if base == HOST_MODULE || base.is_empty() {
            self.root.clone()
        } else {
            Path::new(base)
                .parent()
                .map_or_else(|| self.root.clone(), Path::to_path_buf)
        };

        self.resolve_within(specifier, &normalize(&base_dir.join(specifier)))
    }

    /// Find a file for an already-joined path, enforcing containment.
    fn resolve_within(&self, specifier: &str, joined: &Path) -> Result<PathBuf, ResolveError> {
        if !joined.starts_with(&self.root) {
            return Err(ResolveError::EscapesRoot {
                specifier: specifier.to_owned(),
            });
        }

        let mut tried = Vec::new();
        for candidate in candidates(joined) {
            tried.push(candidate.display().to_string());
            if !candidate.is_file() {
                continue;
            }

            // Canonicalize the file that was actually found. This is the check that holds
            // against symlinks — the lexical test above cannot see through one.
            let canonical = candidate
                .canonicalize()
                .map_err(|e| ResolveError::Unreadable {
                    path: candidate.display().to_string(),
                    detail: e.to_string(),
                })?;
            if !canonical.starts_with(&self.root) {
                return Err(ResolveError::EscapesRoot {
                    specifier: specifier.to_owned(),
                });
            }
            return Ok(canonical);
        }

        Err(ResolveError::NotFound {
            specifier: specifier.to_owned(),
            tried: tried.join(", "),
        })
    }

    /// Read a resolved module, stripping types when it is TypeScript.
    ///
    /// Containment is re-checked here rather than trusted from [`RuleRoot::resolve`].
    /// Reading is the operation that actually touches a file, so it should be the thing
    /// that enforces the boundary — otherwise the guarantee depends on every caller having
    /// gone through the resolver first, which is exactly the sort of assumption that holds
    /// until someone adds a second caller.
    ///
    /// # Errors
    ///
    /// Returns [`ResolveError::EscapesRoot`] if the path is outside the root, or
    /// [`ResolveError::Unreadable`] if the file cannot be read or stripping rejects it.
    pub fn read(
        &self,
        path: &Path,
        typescript: &dyn Language,
        javascript: &dyn Language,
    ) -> Result<String, ResolveError> {
        if path == Path::new(HOST_MODULE) {
            return Ok(HOST_MODULE_SOURCE.to_owned());
        }

        if let Some(name) = path.to_str().and_then(|p| p.strip_prefix(BUILTIN_PREFIX))
            && let Some(source) = (self.builtins)(name)
        {
            // Built-ins are TypeScript like any other rule, so they go through the same
            // stripping — including its verification step. A built-in that failed to strip
            // would be a build-time bug in this repository, and should look like one.
            return strip_types(typescript, javascript, source).map_err(|e| {
                ResolveError::Unreadable {
                    path: path.display().to_string(),
                    detail: e.to_string(),
                }
            });
        }

        let canonical = path.canonicalize().map_err(|e| ResolveError::Unreadable {
            path: path.display().to_string(),
            detail: e.to_string(),
        })?;
        if !canonical.starts_with(&self.root) {
            return Err(ResolveError::EscapesRoot {
                specifier: path.display().to_string(),
            });
        }

        let source = std::fs::read_to_string(path).map_err(|e| ResolveError::Unreadable {
            path: path.display().to_string(),
            detail: e.to_string(),
        })?;

        // Plain JavaScript is passed through untouched rather than run through the
        // stripper, which would only be able to fail on it.
        let is_typescript = path
            .extension()
            .and_then(|e| e.to_str())
            .is_some_and(|e| matches!(e, "ts" | "tsx" | "mts" | "cts"));
        if !is_typescript {
            return Ok(source);
        }

        strip_types(typescript, javascript, &source).map_err(|e| ResolveError::Unreadable {
            path: path.display().to_string(),
            detail: e.to_string(),
        })
    }
}

/// Candidate files for a specifier, in resolution order.
fn candidates(base: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();

    // An explicit extension is taken at face value.
    if base.extension().is_some() {
        out.push(base.to_path_buf());
    }

    for extension in EXTENSIONS {
        out.push(base.with_extension(extension));
    }
    for extension in EXTENSIONS {
        out.push(base.join(format!("index.{extension}")));
    }

    out
}

/// Adapts [`RuleRoot`] to the engine's resolver interface.
#[derive(Debug, Clone)]
pub struct RuleResolver {
    root: RuleRoot,
}

impl RuleResolver {
    /// Build a resolver for a rules root.
    #[must_use]
    pub const fn new(root: RuleRoot) -> Self {
        Self { root }
    }
}

impl Resolver for RuleResolver {
    fn resolve(
        &mut self,
        _ctx: &Ctx<'_>,
        base: &str,
        name: &str,
        _attributes: Option<ImportAttributes<'_>>,
    ) -> rquickjs::Result<String> {
        match self.root.resolve(base, name) {
            Ok(path) => Ok(path.display().to_string()),
            // The engine's error channel carries only a message, so the diagnostic is
            // rendered here rather than lost.
            Err(err) => Err(JsError::new_resolving_message(
                base.to_owned(),
                name.to_owned(),
                err.to_string(),
            )),
        }
    }
}

/// Every module the loader read, with the source it read.
///
/// This is what makes `ruleset_hash` cover the whole import graph rather than only the
/// entry files. A rule that imports a shared helper has to invalidate when that helper
/// changes, and the only component that knows the helper was involved is the loader.
///
/// Ordered, so the hash derived from it does not depend on load order — which varies with
/// import structure and is not something a user changed.
pub type LoadedModules = Rc<RefCell<BTreeMap<PathBuf, String>>>;

/// Adapts [`RuleRoot`] to the engine's loader interface.
///
/// `Debug` is hand-written because `Arc<dyn Language>` is not `Debug`, and requiring it on
/// the trait would burden every language implementation for one impl here.
#[derive(Clone)]
pub struct RuleLoader {
    root: RuleRoot,
    typescript: Arc<dyn Language>,
    javascript: Arc<dyn Language>,
    loaded: LoadedModules,
}

impl std::fmt::Debug for RuleLoader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RuleLoader")
            .field("root", &self.root)
            .field("typescript", &self.typescript.id())
            .field("javascript", &self.javascript.id())
            .field("loaded", &self.loaded.borrow().len())
            .finish()
    }
}

impl RuleLoader {
    /// Build a loader for a rules root.
    ///
    /// The languages are supplied rather than assumed so this crate does not have to know
    /// which grammars exist.
    #[must_use]
    pub fn new(
        root: RuleRoot,
        typescript: Arc<dyn Language>,
        javascript: Arc<dyn Language>,
    ) -> Self {
        Self {
            root,
            typescript,
            javascript,
            loaded: Rc::new(RefCell::new(BTreeMap::new())),
        }
    }

    /// A handle on what this loader has read, for hashing the rule graph.
    #[must_use]
    pub fn loaded(&self) -> LoadedModules {
        Rc::clone(&self.loaded)
    }
}

impl Loader for RuleLoader {
    fn load<'js>(
        &mut self,
        ctx: &Ctx<'js>,
        name: &str,
        _attributes: Option<ImportAttributes<'js>>,
    ) -> rquickjs::Result<Module<'js, Declared>> {
        let source = self
            .root
            .read(
                Path::new(name),
                self.typescript.as_ref(),
                self.javascript.as_ref(),
            )
            .map_err(|err| JsError::new_loading_message(name.to_owned(), err.to_string()))?;

        // Recorded before declaring, so a module that fails to compile still counts as
        // part of the graph. Otherwise fixing the compile error would not invalidate.
        self.loaded
            .borrow_mut()
            .insert(PathBuf::from(name), source.clone());

        Module::declare(ctx.clone(), name, source)
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use lanekeep_lang_js::{JavaScript, TypeScript};

    use super::*;

    /// A rules directory laid out for a test, cleaned up on drop.
    struct Fixture {
        dir: PathBuf,
    }

    impl Fixture {
        fn new(name: &str, files: &[(&str, &str)]) -> Self {
            let dir = std::env::temp_dir().join(format!("lanekeep-loader-{name}"));
            let _ = fs::remove_dir_all(&dir);
            fs::create_dir_all(&dir).expect("creates fixture dir");
            for (path, contents) in files {
                let full = dir.join(path);
                if let Some(parent) = full.parent() {
                    fs::create_dir_all(parent).expect("creates parent");
                }
                fs::write(&full, contents).expect("writes fixture file");
            }
            Self { dir }
        }

        fn root(&self) -> RuleRoot {
            RuleRoot::new(&self.dir).expect("canonicalizes")
        }

        fn entry(&self, name: &str) -> String {
            self.dir
                .join(name)
                .canonicalize()
                .expect("exists")
                .display()
                .to_string()
        }
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.dir);
        }
    }

    /// Stands in for the real built-in table, so these tests do not depend on which rules
    /// happen to ship.
    fn stub_builtins(name: &str) -> Option<&'static str> {
        match name {
            "always" => Some("export default { id: 'lanekeep/always' } satisfies unknown;"),
            _ => None,
        }
    }

    #[test]
    fn resolves_a_built_in_by_specifier() {
        let fixture = Fixture::new("builtin-resolve", &[("a.ts", "export const a = 1;")]);
        let root = fixture.root().with_builtins(stub_builtins);
        assert_eq!(
            root.resolve("", "lanekeep/always").expect("resolves"),
            Path::new("lanekeep/always")
        );
    }

    #[test]
    fn an_unknown_built_in_is_not_found() {
        // Not "bare specifier": the `lanekeep/` prefix says what the author meant, and an
        // error about npm resolution would send them somewhere useless.
        let fixture = Fixture::new("builtin-unknown", &[("a.ts", "export const a = 1;")]);
        let root = fixture.root().with_builtins(stub_builtins);
        let error = root
            .resolve("", "lanekeep/no-such-rule")
            .expect_err("does not resolve");
        assert!(
            matches!(error, ResolveError::NotFound { .. }),
            "expected NotFound, got {error:?}"
        );
        assert!(error.to_string().contains("built-in"), "{error}");
    }

    #[test]
    fn a_file_cannot_shadow_a_built_in() {
        // A rules directory containing `lanekeep/always.ts` must not change what the
        // specifier means. A rule whose behavior depended on whether a same-named file
        // happened to exist would be unreasonable to debug.
        let fixture = Fixture::new(
            "builtin-shadow",
            &[("lanekeep/always.ts", "export default 'the wrong one';")],
        );
        let root = fixture.root().with_builtins(stub_builtins);
        let resolved = root.resolve("", "lanekeep/always").expect("resolves");
        assert_eq!(resolved, Path::new("lanekeep/always"));

        let source = root
            .read(&resolved, &TypeScript, &JavaScript)
            .expect("reads");
        assert!(
            !source.contains("the wrong one"),
            "a project file shadowed a built-in: {source}"
        );
    }

    #[test]
    fn a_built_in_is_stripped_of_its_types() {
        let fixture = Fixture::new("builtin-strip", &[("a.ts", "export const a = 1;")]);
        let root = fixture.root().with_builtins(stub_builtins);
        let source = root
            .read(Path::new("lanekeep/always"), &TypeScript, &JavaScript)
            .expect("reads");
        assert!(
            !source.contains("satisfies"),
            "type syntax survived stripping: {source}"
        );
    }

    #[test]
    fn built_ins_are_absent_unless_provided() {
        // The default. A crate embedding `lanekeep-js` without the rules crate resolves
        // project modules only, rather than silently resolving names to nothing.
        let fixture = Fixture::new("builtin-default", &[("a.ts", "export const a = 1;")]);
        let root = fixture.root();
        assert!(root.resolve("", "lanekeep/always").is_err());
    }

    #[test]
    fn resolves_the_host_module() {
        let fixture = Fixture::new("host", &[("a.ts", "export const a = 1;")]);
        let root = fixture.root();
        assert_eq!(
            root.resolve("", HOST_MODULE).expect("resolves"),
            Path::new(HOST_MODULE)
        );
    }

    #[test]
    fn the_host_module_exports_the_authoring_helpers() {
        let fixture = Fixture::new("host-src", &[]);
        let source = fixture
            .root()
            .read(Path::new(HOST_MODULE), &TypeScript, &JavaScript)
            .expect("reads");
        assert!(source.contains("defineRule"), "{source}");
        assert!(source.contains("defineConfig"), "{source}");
    }

    #[test]
    fn resolves_a_relative_import() {
        let fixture = Fixture::new(
            "relative",
            &[
                ("main.ts", "import './helper';"),
                ("helper.ts", "export const h = 1;"),
            ],
        );
        let root = fixture.root();

        let resolved = root
            .resolve(&fixture.entry("main.ts"), "./helper")
            .expect("resolves");
        assert!(resolved.ends_with("helper.ts"), "{resolved:?}");
    }

    #[test]
    fn tries_extensions_in_order() {
        // A `.ts` file wins over a `.js` file of the same name, because a rule directory
        // containing both is almost always a stale build artifact next to its source.
        let fixture = Fixture::new(
            "extensions",
            &[
                ("main.ts", ""),
                ("dup.ts", "export const from = 'ts';"),
                ("dup.js", "export const from = 'js';"),
            ],
        );
        let resolved = fixture
            .root()
            .resolve(&fixture.entry("main.ts"), "./dup")
            .expect("resolves");
        assert!(
            resolved.ends_with("dup.ts"),
            "expected the TypeScript file: {resolved:?}"
        );
    }

    #[test]
    fn resolves_a_directory_index() {
        let fixture = Fixture::new(
            "index",
            &[("main.ts", ""), ("rules/index.ts", "export const r = 1;")],
        );
        let resolved = fixture
            .root()
            .resolve(&fixture.entry("main.ts"), "./rules")
            .expect("resolves");
        assert!(resolved.ends_with("index.ts"), "{resolved:?}");
    }

    #[test]
    fn resolves_an_explicit_extension() {
        let fixture = Fixture::new(
            "explicit",
            &[("main.ts", ""), ("helper.ts", "export const h = 1;")],
        );
        let resolved = fixture
            .root()
            .resolve(&fixture.entry("main.ts"), "./helper.ts")
            .expect("resolves");
        assert!(resolved.ends_with("helper.ts"), "{resolved:?}");
    }

    // --- what must not resolve --------------------------------------------------------

    #[test]
    fn rejects_bare_specifiers() {
        let fixture = Fixture::new("bare", &[("main.ts", "")]);
        let root = fixture.root();

        for specifier in [
            "lodash",
            "react",
            "node:fs",
            "fs",
            "@scope/pkg",
            "typescript",
        ] {
            let err = root
                .resolve(&fixture.entry("main.ts"), specifier)
                .expect_err("bare specifiers must not resolve");
            assert!(
                matches!(err, ResolveError::BareSpecifier { .. }),
                "{specifier} gave {err:?}"
            );
        }
    }

    #[test]
    fn a_bare_specifier_explains_why() {
        let fixture = Fixture::new("bare-msg", &[("main.ts", "")]);
        let err = fixture
            .root()
            .resolve(&fixture.entry("main.ts"), "lodash")
            .expect_err("bare specifiers do not resolve");

        assert!(matches!(err, ResolveError::BareSpecifier { .. }), "{err:?}");
        let rendered = err.to_string();
        assert!(rendered.contains("no package resolution"), "{rendered}");
        assert!(rendered.contains("lanekeep"), "{rendered}");
    }

    #[test]
    fn rejects_traversal_out_of_the_root() {
        let fixture = Fixture::new("traversal", &[("main.ts", "")]);
        let root = fixture.root();
        let base = fixture.entry("main.ts");

        for specifier in ["../outside", "../../etc/passwd", "./../../secrets", "../"] {
            let err = root
                .resolve(&base, specifier)
                .expect_err("traversal must not resolve");
            assert!(
                matches!(err, ResolveError::EscapesRoot { .. }),
                "{specifier} gave {err:?}"
            );
        }
    }

    #[test]
    fn traversal_is_rejected_even_when_the_target_exists() {
        // The lexical check has to fire regardless of what is on disk, or the error a
        // reader sees depends on whether the file they tried to reach happened to be there.
        let fixture = Fixture::new(
            "traversal-real",
            &[("nested/main.ts", ""), ("secret.ts", "export const s = 1;")],
        );
        let root = RuleRoot::new(fixture.dir.join("nested")).expect("canonicalizes");

        let err = root
            .resolve(&fixture.entry("nested/main.ts"), "../secret")
            .expect_err("must not escape");
        assert!(matches!(err, ResolveError::EscapesRoot { .. }), "{err:?}");
    }

    #[cfg(unix)]
    #[test]
    fn rejects_a_symlink_pointing_outside_the_root() {
        // The case a lexical check cannot see. `./link` looks entirely innocent; only
        // canonicalizing the file that was found reveals where it goes.
        let fixture = Fixture::new(
            "symlink",
            &[
                ("nested/main.ts", ""),
                ("outside.ts", "export const o = 1;"),
            ],
        );
        let root_dir = fixture.dir.join("nested");
        let link = root_dir.join("link.ts");
        std::os::unix::fs::symlink(fixture.dir.join("outside.ts"), &link).expect("creates symlink");

        let root = RuleRoot::new(&root_dir).expect("canonicalizes");
        let err = root
            .resolve(&fixture.entry("nested/main.ts"), "./link")
            .expect_err("a symlink out of the root must be rejected");
        assert!(matches!(err, ResolveError::EscapesRoot { .. }), "{err:?}");
    }

    #[test]
    fn a_rule_may_not_import_an_absolute_path() {
        // The entry module legitimately arrives as an absolute path, so the resolver has
        // to accept one. This checks that door is only open for the entry — a rule with a
        // base of its own is refused.
        //
        // The absolute path is built from `temp_dir` rather than written literally,
        // because `Path::is_absolute` is platform-specific: `/etc/passwd` is absolute on
        // Unix and merely rooted on Windows, while `C:\...` is the reverse. A literal
        // would take a different branch on each platform and assert a different error.
        let fixture = Fixture::new("absolute", &[("main.ts", "")]);
        let root = fixture.root();
        let base = fixture.entry("main.ts");

        let outside = std::env::temp_dir().join("lanekeep-absolute-probe.ts");
        let outside = outside.display().to_string();

        // Written by a rule: refused, whichever way the platform classifies it.
        for specifier in [outside.as_str(), "/etc/passwd", "C:\\Windows\\System32\\x"] {
            assert!(
                root.resolve(&base, specifier).is_err(),
                "a rule must not import `{specifier}`"
            );
        }

        // As an entry point: still refused, because it is outside the root.
        let err = root
            .resolve("", &outside)
            .expect_err("an entry outside the root must be refused");
        assert!(matches!(err, ResolveError::EscapesRoot { .. }), "{err:?}");
    }

    #[test]
    fn reports_what_it_tried_when_nothing_matches() {
        let fixture = Fixture::new("missing", &[("main.ts", "")]);
        let err = fixture
            .root()
            .resolve(&fixture.entry("main.ts"), "./nope")
            .expect_err("nothing to find");

        match err {
            ResolveError::NotFound { tried, .. } => {
                assert!(tried.contains("nope.ts"), "should list candidates: {tried}");
                assert!(
                    tried.contains("index.ts"),
                    "should list index candidates: {tried}"
                );
            }
            other => panic!("wrong error: {other:?}"),
        }
    }

    // --- reading ------------------------------------------------------------------------

    #[test]
    fn strips_types_when_reading_typescript() {
        let fixture = Fixture::new(
            "read-ts",
            &[("a.ts", "export const a: number = 1;\ninterface B {}\n")],
        );
        let root = fixture.root();
        let path = root.resolve("", "./a").expect("resolves");
        let source = root.read(&path, &TypeScript, &JavaScript).expect("reads");

        assert!(!source.contains(": number"), "{source}");
        assert!(!source.contains("interface"), "{source}");
        assert!(source.contains("export const a"), "{source}");
    }

    #[test]
    fn reading_refuses_a_path_outside_the_root_even_if_resolution_was_skipped() {
        // Defense in depth. `resolve` already enforces this, but a future caller that
        // builds a path some other way must not be able to read past the boundary.
        let fixture = Fixture::new(
            "read-escape",
            &[
                ("nested/main.ts", ""),
                ("outside.ts", "export const o = 1;"),
            ],
        );
        let root = RuleRoot::new(fixture.dir.join("nested")).expect("canonicalizes");

        let err = root
            .read(&fixture.dir.join("outside.ts"), &TypeScript, &JavaScript)
            .expect_err("reading outside the root must be refused");
        assert!(matches!(err, ResolveError::EscapesRoot { .. }), "{err:?}");
    }

    #[test]
    fn passes_javascript_through_untouched() {
        let contents = "export const a = 1;\n";
        let fixture = Fixture::new("read-js", &[("a.js", contents)]);
        let root = fixture.root();
        let path = root.resolve("", "./a.js").expect("resolves");
        assert_eq!(
            root.read(&path, &TypeScript, &JavaScript).expect("reads"),
            contents
        );
    }

    // --- end to end, through the engine ---------------------------------------------
    //
    // Everything above tests the resolution logic directly. These go through the engine's
    // Resolver and Loader adapters, which is the part that is actually wired up at runtime
    // and could be correct in isolation while being connected wrongly.

    fn sandbox_for(fixture: &Fixture) -> crate::Sandbox {
        crate::Sandbox::with_modules(
            crate::Limits::default(),
            crate::RunClock::start(std::time::Duration::from_secs(30)),
            fixture.root(),
            Arc::new(TypeScript),
            Arc::new(JavaScript),
        )
        .expect("sandbox builds")
    }

    #[test]
    fn loads_a_rule_module_that_imports_the_host_module() {
        let fixture = Fixture::new(
            "e2e-host",
            &[(
                "rule.ts",
                "import { defineRule } from 'lanekeep';\n\
                 export default defineRule({ id: 'local/example' });\n",
            )],
        );
        let sandbox = sandbox_for(&fixture);
        let path = fixture.root().resolve("", "./rule").expect("resolves");

        let module: std::collections::HashMap<String, String> =
            sandbox.import_default(&path).expect("module evaluates");
        assert_eq!(module.get("id").map(String::as_str), Some("local/example"));
    }

    #[test]
    fn loads_a_module_that_imports_a_sibling_and_strips_its_types() {
        let fixture = Fixture::new(
            "e2e-sibling",
            &[
                (
                    "rule.ts",
                    "import { defineRule } from 'lanekeep';\n\
                     import { NAME } from './shared';\n\
                     export default defineRule({ id: NAME });\n",
                ),
                (
                    "shared.ts",
                    "interface Unused { a: number }\n\
                     export const NAME: string = 'local/from-sibling';\n",
                ),
            ],
        );
        let sandbox = sandbox_for(&fixture);
        let path = fixture.root().resolve("", "./rule").expect("resolves");

        let module: std::collections::HashMap<String, String> =
            sandbox.import_default(&path).expect("module evaluates");
        assert_eq!(
            module.get("id").map(String::as_str),
            Some("local/from-sibling")
        );
    }

    #[test]
    fn a_bare_import_fails_at_load_with_the_explanation() {
        let fixture = Fixture::new(
            "e2e-bare",
            &[(
                "rule.ts",
                "import lodash from 'lodash';\nexport default lodash;\n",
            )],
        );
        let sandbox = sandbox_for(&fixture);
        let path = fixture.root().resolve("", "./rule").expect("resolves");

        let err = sandbox
            .import_default::<std::collections::HashMap<String, String>>(&path)
            .expect_err("lodash cannot resolve");
        let rendered = err.to_string();
        assert!(rendered.contains("lodash"), "{rendered}");
    }

    #[test]
    fn a_traversing_import_fails_at_load() {
        let fixture = Fixture::new(
            "e2e-traversal",
            &[
                (
                    "nested/rule.ts",
                    "import x from '../outside';\nexport default x;\n",
                ),
                ("outside.ts", "export default 1;\n"),
            ],
        );
        let root = RuleRoot::new(fixture.dir.join("nested")).expect("canonicalizes");
        let sandbox = crate::Sandbox::with_modules(
            crate::Limits::default(),
            crate::RunClock::start(std::time::Duration::from_secs(30)),
            root.clone(),
            Arc::new(TypeScript),
            Arc::new(JavaScript),
        )
        .expect("sandbox builds");

        let path = root.resolve("", "./rule").expect("resolves");
        assert!(
            sandbox
                .import_default::<std::collections::HashMap<String, String>>(&path)
                .is_err(),
            "an import escaping the root must not load"
        );
    }

    #[test]
    fn a_module_that_fails_to_strip_reports_the_reason() {
        let fixture = Fixture::new("read-bad", &[("a.ts", "enum E { A }\n")]);
        let root = fixture.root();
        let path = root.resolve("", "./a").expect("resolves");
        let err = root
            .read(&path, &TypeScript, &JavaScript)
            .expect_err("enums are rejected");

        let rendered = err.to_string();
        assert!(
            rendered.contains("enum"),
            "should name the construct: {rendered}"
        );
    }
}