Skip to main content

mlua_pkg/
lib.rs

1//! # mlua-pkg
2//!
3//! Composable Lua module loader built in Rust.
4//!
5//! # Design philosophy
6//!
7//! Lua's `require("name")` is a `name -> value` transformation.
8//! This crate defines that transformation as a **composable abstraction**,
9//! allowing multiple sources (memory, filesystem, Rust functions, assets)
10//! to be handled uniformly.
11//!
12//! # Resolution model
13//!
14//! ## Abstractions
15//!
16//! | Concept | Type | Role |
17//! |---------|------|------|
18//! | Resolution unit | [`Resolver`] | `name -> Option<Result<Value>>` |
19//! | Composition (Chain) | [`Registry`] | Resolvers in priority order, first match wins |
20//! | Composition (Prefix) | [`resolvers::PrefixResolver`] | Strip prefix and delegate to inner Resolver |
21//!
22//! Resolvers come in two kinds: **leaf** (directly produce values) and
23//! **combinator** (compose other Resolvers). Both implement the same
24//! [`Resolver`] trait, enabling infinite composition.
25//!
26//! ## Leaf Resolvers
27//!
28//! | Resolver | Source | Match condition |
29//! |----------|--------|----------------|
30//! | [`resolvers::MemoryResolver`] | `HashMap<String, String>` | Name is registered |
31//! | [`resolvers::NativeResolver`] | `Fn(&Lua) -> Result<Value>` | Name is registered |
32//! | [`resolvers::FsResolver`] | Filesystem | File exists |
33//! | [`resolvers::AssetResolver`] | Filesystem | Known extension + file exists |
34//!
35//! ## Combinators
36//!
37//! | Combinator | Behavior |
38//! |------------|----------|
39//! | [`Registry`] (Chain) | Try `[R1, R2, ..., Rn]` in order, adopt first `Some` |
40//! | [`resolvers::PrefixResolver`] | `"prefix.rest"` -> strip prefix -> delegate `"rest"` to inner Resolver |
41//!
42//! ## Resolution flow
43//!
44//! ```text
45//! require("name")
46//!   |
47//!   v
48//! package.searchers[1]  <- Registry inserts its hook here
49//!   |
50//!   +- Resolver A: resolve(lua, "name") -> None (not responsible)
51//!   +- Resolver B: resolve(lua, "name") -> Some(Ok(Value)) (first match wins)
52//!   |
53//!   v
54//! package.loaded["name"] = Value  <- Lua standard require auto-caches
55//! ```
56//!
57//! # Return value protocol
58//!
59//! | Return value | Meaning | Next Resolver |
60//! |-------------|---------|---------------|
61//! | `None` | Not this Resolver's responsibility | Tried |
62//! | `Some(Ok(value))` | Resolution succeeded | Skipped |
63//! | `Some(Err(e))` | Responsible but load failed | **Skipped** |
64//!
65//! `Some(Err)` intentionally does not fall through to the next Resolver.
66//! If a module was "found but broken", having another Resolver return
67//! something different would be a source of bugs.
68//!
69//! # Naming conventions
70//!
71//! | Name pattern | Example | Responsible Resolver |
72//! |-------------|---------|---------------------|
73//! | `@scope/name` | `@std/http` | [`resolvers::NativeResolver`] -- exact name match |
74//! | `prefix.name` | `game.engine` | [`resolvers::PrefixResolver`] -> delegates to inner Resolver |
75//! | `dot.separated` | `lib.helper` | [`resolvers::FsResolver`] -- `lib/helper.lua` |
76//! | `name.ext` | `config.json` | [`resolvers::AssetResolver`] -- auto-convert by extension |
77//!
78//! [`resolvers::FsResolver`] converts dot separators to path separators
79//! (`lib.helper` -> `lib/helper.lua`).
80//! [`resolvers::AssetResolver`] treats filenames literally
81//! (`config.json` -> `config.json`).
82//! The two naturally partition by the presence of a file extension.
83//!
84//! # Composition example
85//!
86//! ```text
87//! Registry (Chain)
88//! +- NativeResolver            @std/http  -> factory(lua)
89//! +- Prefix("sm", FsResolver)  sm.helper  -> strip -> helper.lua
90//! +- FsResolver(root/)         sm         -> sm/init.lua
91//! |                             lib.utils  -> lib/utils.lua
92//! +- AssetResolver              config.json -> parse -> Table
93//! ```
94//!
95//! [`resolvers::PrefixResolver`] acts as a namespace mount point.
96//! `require("sm")` (init.lua) is handled by the outer [`resolvers::FsResolver`],
97//! while `require("sm.helper")` is handled by [`resolvers::PrefixResolver`].
98//! Responsibilities are clearly separated.
99//!
100//! # Usage
101//!
102//! ```rust
103//! use mlua_pkg::{Registry, resolvers::*};
104//! use mlua::Lua;
105//!
106//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
107//! let lua = Lua::new();
108//! let mut reg = Registry::new();
109//!
110//! // 1st: Rust native modules (highest priority)
111//! reg.add(NativeResolver::new().add("@std/http", |lua| {
112//!     let t = lua.create_table()?;
113//!     t.set("version", 1)?;
114//!     Ok(mlua::Value::Table(t))
115//! }));
116//!
117//! // 2nd: Embedded Lua sources
118//! reg.add(MemoryResolver::new().add("utils", "return { pi = 3.14 }"));
119//!
120//! // 3rd: Filesystem (sandboxed)
121//! # let plugins = std::env::temp_dir().join("mlua_pkg_doctest_plugins");
122//! # std::fs::create_dir_all(&plugins)?;
123//! # let assets = std::env::temp_dir().join("mlua_pkg_doctest_assets");
124//! # std::fs::create_dir_all(&assets)?;
125//! reg.add(FsResolver::new(&plugins)?);
126//!
127//! // 4th: Assets (register parsers explicitly)
128//! reg.add(AssetResolver::new(&assets)?
129//!     .parser("json", json_parser())
130//!     .parser("sql", text_parser()));
131//! # std::fs::remove_dir_all(&plugins).ok();
132//! # std::fs::remove_dir_all(&assets).ok();
133//!
134//! reg.install(&lua)?;
135//!
136//! // Lua side: require("@std/http"), require("utils"), etc.
137//! # Ok(())
138//! # }
139//! ```
140//!
141//! # Lua integration
142//!
143//! [`Registry::install()`] inserts a hook at the front of Lua's
144//! `package.searchers` table. It takes priority over the standard
145//! `package.preload`, so registered Resolvers are tried first.
146//!
147//! Caching is delegated to Lua's standard `package.loaded`.
148//! On the second and subsequent `require` calls for the same module,
149//! Lua's cache hits and the Resolver is not invoked.
150//!
151//! # Error design
152//!
153//! | Error type | When raised | Defined in |
154//! |-----------|-------------|-----------|
155//! | [`ResolveError`] | During `resolve()` execution | This module |
156//! | [`sandbox::InitError`] | During `FsSandbox::new()` construction | [`sandbox`] |
157//! | [`sandbox::ReadError`] | During `SandboxedFs::read()` | [`sandbox`] |
158//!
159//! By separating construction-time and runtime errors at the type level,
160//! callers can choose the appropriate recovery strategy.
161
162pub mod error;
163pub mod fetcher;
164pub mod lockfile;
165pub mod manifest;
166pub mod resolvers;
167pub mod sandbox;
168
169pub use error::PkgError;
170
171use mlua::{Lua, Result, Value};
172use std::path::{Path, PathBuf};
173
174/// Resolve the Lua `require` entry point directory for a cached package.
175///
176/// Applies the entry fallback chain in order:
177///
178/// 1. If `override_entry` is `Some(p)`, check `cache_path.join(p)` only.
179///    If it is not a directory, return [`PkgError::EntryNotFound`] immediately
180///    (the override is explicit, so fallback would be surprising).
181/// 2. Otherwise, try the default candidates in order:
182///    - `cache_path/src/`
183///    - `cache_path/lua/`
184///    - `cache_path/` itself (`.`)
185///
186/// Returns the first candidate that is a directory, or
187/// [`PkgError::EntryNotFound`] if none exist.
188///
189/// # Notes
190///
191/// This function is used by the `install` CLI (ST5) to determine the symlink
192/// target for each vendored package. [`resolvers::VendoredResolver`] itself does
193/// not call this function — the lockfile already carries the resolved `entry`
194/// field, and the CLI's symlink points `vendored/<name>` at
195/// `../cache/…/<sha>/<entry>` before the resolver is constructed.
196///
197/// # Errors
198///
199/// Returns [`PkgError::EntryNotFound`] when no candidate directory exists.
200///
201/// # Example
202///
203/// ```rust,no_run
204/// use mlua_pkg::resolve_entry;
205/// use std::path::Path;
206///
207/// let entry = resolve_entry(Path::new("/cache/mypkg/abc123"), None)?;
208/// // => /cache/mypkg/abc123/src  (if that directory exists)
209/// # Ok::<(), mlua_pkg::PkgError>(())
210/// ```
211pub fn resolve_entry(
212    cache_path: &Path,
213    override_entry: Option<&Path>,
214) -> std::result::Result<PathBuf, PkgError> {
215    let candidates: Vec<PathBuf> = match override_entry {
216        Some(e) => vec![cache_path.join(e)],
217        None => vec![
218            cache_path.join("src"),
219            cache_path.join("lua"),
220            cache_path.to_path_buf(),
221        ],
222    };
223
224    for c in &candidates {
225        if c.is_dir() {
226            return Ok(c.clone());
227        }
228    }
229
230    Err(PkgError::EntryNotFound {
231        name: cache_path.display().to_string(),
232        attempted: candidates,
233    })
234}
235
236/// Configuration bundle for Lua dialect naming conventions.
237///
238/// Apply to [`FsResolver`](resolvers::FsResolver) and
239/// [`PrefixResolver`](resolvers::PrefixResolver) via `with_convention()`
240/// to prevent convention settings from scattering.
241///
242/// Individual `with_extension()` / `with_init_name()` / `with_separator()`
243/// methods remain available. Calling them after `with_convention()` overrides
244/// the corresponding field.
245///
246/// # Predefined conventions
247///
248/// | Constant | Extension | Init name | Separator |
249/// |----------|-----------|-----------|-----------|
250/// | [`LUA54`](Self::LUA54) | `lua` | `init` | `.` |
251/// | [`LUAU`](Self::LUAU) | `luau` | `init` | `.` |
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub struct LuaConvention {
254    /// File extension (`"lua"`, `"luau"`, etc.).
255    pub extension: &'static str,
256    /// Package entry point name (`"init"`, `"mod"`, etc.).
257    pub init_name: &'static str,
258    /// Module name separator. The `.` in `require("a.b")`.
259    pub module_separator: char,
260}
261
262impl LuaConvention {
263    /// Lua 5.4 standard convention.
264    pub const LUA54: Self = Self {
265        extension: "lua",
266        init_name: "init",
267        module_separator: '.',
268    };
269
270    /// Luau (Roblox Lua) convention.
271    pub const LUAU: Self = Self {
272        extension: "luau",
273        init_name: "init",
274        module_separator: '.',
275    };
276}
277
278impl Default for LuaConvention {
279    fn default() -> Self {
280        Self::LUA54
281    }
282}
283
284/// Error type for module resolution.
285///
286/// Structurally represents domain-specific errors that occur during `resolve()`.
287/// Converted to a Lua error via [`mlua::Error::external()`] and can be
288/// recovered on the caller side with `err.downcast_ref::<ResolveError>()`.
289///
290/// Construction-time errors (e.g. root directory not found) are returned as
291/// [`sandbox::InitError`] and are not included here.
292#[derive(Debug, thiserror::Error)]
293pub enum ResolveError {
294    /// Path access outside the sandbox detected.
295    #[error("path traversal blocked: {name}")]
296    PathTraversal { name: String },
297
298    /// Asset parse failure.
299    ///
300    /// Generalized to hold different error types per parser.
301    /// [`resolvers::json_parser()`] stores `serde_json::Error`;
302    /// custom parsers can store any error type.
303    #[error("asset parse error: {source}")]
304    AssetParse {
305        #[source]
306        source: Box<dyn std::error::Error + Send + Sync>,
307    },
308
309    /// File I/O error.
310    ///
311    /// Raised when a file exists but cannot be read
312    /// (e.g. permission denied, is a directory).
313    #[error("I/O error on {}: {source}", path.display())]
314    Io {
315        path: PathBuf,
316        source: std::io::Error,
317    },
318}
319
320/// Minimal abstraction for module resolution.
321///
322/// Receives `require(name)` and returns `Some(Result<Value>)` if this
323/// Resolver is responsible. Returns `None` if not.
324///
325/// # Return value protocol
326///
327/// - `None` = "unknown name". The next Resolver gets a chance.
328/// - `Some(Ok(v))` = resolution complete. This value is returned to Lua.
329/// - `Some(Err(e))` = "responsible but failed". Propagated immediately as an error.
330///
331/// # Example
332///
333/// ```rust
334/// use mlua_pkg::Resolver;
335/// use mlua::{Lua, Result, Value};
336///
337/// struct VersionResolver;
338///
339/// impl Resolver for VersionResolver {
340///     fn resolve(&self, lua: &Lua, name: &str) -> Option<Result<Value>> {
341///         if name == "version" {
342///             Some(lua.create_string("1.0.0").map(Value::String))
343///         } else {
344///             None
345///         }
346///     }
347/// }
348/// ```
349pub trait Resolver: Send + Sync {
350    fn resolve(&self, lua: &Lua, name: &str) -> Option<Result<Value>>;
351}
352
353/// Chain combinator for [`Resolver`]. Registration order = priority order. First match wins.
354///
355/// `install()` inserts a hook at the front (index 1) of Lua's `package.searchers`
356/// table, routing all `require` calls through the registered Resolver chain.
357/// Takes priority over Lua's standard `package.preload`.
358///
359/// Caching is delegated to Lua's standard `package.loaded`.
360/// Resolvers do not need to manage their own cache.
361/// On the second and subsequent `require` for the same module, the Resolver is not called.
362///
363/// # Lua searcher protocol
364///
365/// The hook conforms to the Lua 5.4 searcher protocol:
366/// - If the searcher returns a `function`, `require` calls it as a loader
367/// - If the searcher returns a `string`, it is collected as a "not found" reason in the error message
368///
369/// The loader receives `(name, loader_data)` (per Lua 5.4 spec).
370///
371/// # Thread safety
372///
373/// `Registry` itself is `Send + Sync` (all Resolvers must be `Send + Sync`).
374/// After [`install()`](Registry::install), the Registry is wrapped in `Arc` and
375/// shared via a Lua closure.
376///
377/// Thread safety of the installed hook depends on the `mlua` feature configuration:
378///
379/// | mlua feature | `Lua` bounds | Implication |
380/// |-------------|-------------|-------------|
381/// | (default) | `!Send` | `Lua` is confined to one thread. The hook is never called concurrently. |
382/// | `send` | `Send + Sync` | `Lua` can be shared across threads. `Resolver: Send + Sync` ensures safe concurrent access. |
383///
384/// The `Send + Sync` bound on [`Resolver`] is required for forward compatibility
385/// with mlua's `send` feature. Without the `send` feature, `Lua` is `!Send` and
386/// the hook is inherently single-threaded.
387pub struct Registry {
388    resolvers: Vec<Box<dyn Resolver>>,
389}
390
391impl Default for Registry {
392    fn default() -> Self {
393        Self::new()
394    }
395}
396
397impl Registry {
398    pub fn new() -> Self {
399        Self {
400            resolvers: Vec::new(),
401        }
402    }
403
404    /// Add a Resolver. Registration order = priority order.
405    pub fn add(&mut self, resolver: impl Resolver + 'static) -> &mut Self {
406        self.resolvers.push(Box::new(resolver));
407        self
408    }
409
410    /// Insert a hook at the front of `package.searchers`.
411    ///
412    /// Consumes `self` and shares it via `Arc`.
413    /// The Registry becomes immutable after install (Resolver priority is finalized).
414    ///
415    /// Returns an error if called more than once on the same Lua instance.
416    /// Multiple Registries coexisting in the same searchers table would make
417    /// priority order unpredictable, so this is intentionally prohibited.
418    pub fn install(self, lua: &Lua) -> Result<()> {
419        if lua.app_data_ref::<RegistryInstalled>().is_some() {
420            return Err(mlua::Error::runtime(
421                "Registry already installed on this Lua instance",
422            ));
423        }
424
425        let searchers: mlua::Table = lua
426            .globals()
427            .get::<mlua::Table>("package")?
428            .get("searchers")?;
429
430        let registry = std::sync::Arc::new(self);
431        let hook = lua.create_function(move |lua, name: String| {
432            for resolver in &registry.resolvers {
433                if let Some(result) = resolver.resolve(lua, &name) {
434                    let value = result?;
435                    let f = lua.create_function(move |_, (_name, _data): (String, Value)| {
436                        Ok(value.clone())
437                    })?;
438                    return Ok(Value::Function(f));
439                }
440            }
441            Ok(Value::String(
442                lua.create_string(format!("\n\tno resolver for '{name}'"))?,
443            ))
444        })?;
445
446        let len = searchers.raw_len();
447        for i in (1..=len).rev() {
448            let v: Value = searchers.raw_get(i)?;
449            searchers.raw_set(i + 1, v)?;
450        }
451        searchers.raw_set(1, hook)?;
452        lua.set_app_data(RegistryInstalled);
453
454        Ok(())
455    }
456}
457
458/// Marker for `install()` completion. Used to prevent double-install.
459struct RegistryInstalled;
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    struct Echo;
466
467    impl Resolver for Echo {
468        fn resolve(&self, lua: &Lua, name: &str) -> Option<Result<Value>> {
469            if name == "echo" {
470                Some(lua.create_string("hello from echo").map(Value::String))
471            } else {
472                None
473            }
474        }
475    }
476
477    #[test]
478    fn require_hits_resolver() {
479        let lua = Lua::new();
480        let mut reg = Registry::new();
481        reg.add(Echo);
482        reg.install(&lua).unwrap();
483
484        let val: String = lua.load(r#"return require("echo")"#).eval().unwrap();
485        assert_eq!(val, "hello from echo");
486    }
487
488    #[test]
489    fn require_miss_falls_through() {
490        let lua = Lua::new();
491        let mut reg = Registry::new();
492        reg.add(Echo);
493        reg.install(&lua).unwrap();
494
495        let result: mlua::Result<Value> = lua.load(r#"return require("nope")"#).eval();
496        assert!(result.is_err());
497    }
498
499    #[test]
500    fn registry_default() {
501        let reg = Registry::default();
502        assert_eq!(reg.resolvers.len(), 0);
503    }
504
505    #[test]
506    fn double_install_rejected() {
507        let lua = Lua::new();
508
509        let reg1 = Registry::new();
510        reg1.install(&lua).unwrap();
511
512        let reg2 = Registry::new();
513        let err = reg2.install(&lua).unwrap_err();
514        assert!(
515            err.to_string().contains("already installed"),
516            "expected 'already installed' error, got: {err}"
517        );
518    }
519
520    // -- resolve_entry helper tests --
521
522    // TC 4: entry fallback — src/ takes priority when it exists as a dir
523    #[test]
524    fn vendored_resolve_entry_src_priority() {
525        let tmp = tempfile::tempdir().unwrap();
526        let cache = tmp.path();
527
528        // Create src/ and lua/ sub-directories; resolve_entry should pick src/ first.
529        std::fs::create_dir_all(cache.join("src")).unwrap();
530        std::fs::create_dir_all(cache.join("lua")).unwrap();
531
532        let result = resolve_entry(cache, None).unwrap();
533        assert_eq!(result, cache.join("src"));
534    }
535
536    // TC 4b: fallback to lua/ when src/ is absent
537    #[test]
538    fn vendored_resolve_entry_lua_fallback() {
539        let tmp = tempfile::tempdir().unwrap();
540        let cache = tmp.path();
541
542        std::fs::create_dir_all(cache.join("lua")).unwrap();
543
544        let result = resolve_entry(cache, None).unwrap();
545        assert_eq!(result, cache.join("lua"));
546    }
547
548    // TC 4c: override entry is respected and src/ is not tried
549    #[test]
550    fn vendored_resolve_entry_override_respected() {
551        let tmp = tempfile::tempdir().unwrap();
552        let cache = tmp.path();
553
554        // "src/" exists but we override to "lib/"
555        std::fs::create_dir_all(cache.join("src")).unwrap();
556        std::fs::create_dir_all(cache.join("lib")).unwrap();
557
558        let result = resolve_entry(cache, Some(Path::new("lib"))).unwrap();
559        assert_eq!(result, cache.join("lib"));
560    }
561
562    // TC 5: all candidates absent → EntryNotFound
563    #[test]
564    fn vendored_resolve_entry_all_absent_returns_entry_not_found() {
565        let tmp = tempfile::tempdir().unwrap();
566        // cache dir exists but has no src/, lua/, or meaningful root
567        // (the root itself is a dir, so the last fallback `cache_path` would succeed)
568        // To test EntryNotFound we need all three to fail. Root is the tmp dir itself.
569        // Make a sub-path that does NOT exist as a directory.
570        let non_dir = tmp.path().join("no_such_dir");
571        // non_dir does not exist at all, so c.is_dir() = false for all candidates
572        // candidates: non_dir/src, non_dir/lua, non_dir itself (non-existent)
573
574        let err = resolve_entry(&non_dir, None).unwrap_err();
575        assert!(
576            matches!(err, PkgError::EntryNotFound { .. }),
577            "expected EntryNotFound, got: {err}"
578        );
579    }
580
581    // TC 5b: override entry absent → EntryNotFound immediately (no fallback)
582    #[test]
583    fn vendored_resolve_entry_override_absent_no_fallback() {
584        let tmp = tempfile::tempdir().unwrap();
585        let cache = tmp.path();
586
587        // src/ exists but override points to nonexistent "custom/"
588        std::fs::create_dir_all(cache.join("src")).unwrap();
589
590        let err = resolve_entry(cache, Some(Path::new("custom"))).unwrap_err();
591        assert!(
592            matches!(err, PkgError::EntryNotFound { .. }),
593            "expected EntryNotFound when override is absent, got: {err}"
594        );
595    }
596}