libdeno 0.1.1

Embed the Deno runtime in Rust with direct npm: specifier support
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
//! libdeno — embed the Deno runtime in Rust with direct npm support.
//!
//! Runs a JS/TS entry file (or a local package.json project) on the official
//! deno module graph pipeline: npm: specifiers, remote modules, deno.json
//! import maps, jsr:, CJS packages, wasm, .node native addons, web workers
//! and `child_process.fork` are all handled by the graph loader.
//!
//! ```no_run
//! use libdeno::{LibdenoOptions, run};
//!
//! let options = LibdenoOptions {
//!   permissions: vec!["--allow-read=.".into(), "--allow-net=example.com".into()],
//!   args: vec![],
//!   cwd: None,
//! };
//! let exit_code = run("app.js", &options).unwrap();
//! ```

mod graph;
mod http;
mod module_loader;
mod node_loader;
mod permissions;
mod services;
mod subprocess;
mod worker_factory;

use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;

use deno_core::error::AnyError;
use deno_core::ModuleSpecifier;
use deno_runtime::deno_fs::FileSystem;
use deno_runtime::deno_fs::RealFs;
use deno_runtime::deno_inspector_server::MainInspectorSessionChannel;
use deno_runtime::deno_node::NodeExtInitServices;
use deno_runtime::deno_web::BlobStore;
use deno_runtime::deno_web::InMemoryBroadcastChannel;
use deno_runtime::worker::MainWorker;
use deno_runtime::worker::WorkerOptions;
use deno_runtime::worker::WorkerServiceOptions;
use deno_runtime::BootstrapOptions;

pub use subprocess::maybe_handle_child_mode;
pub use subprocess::run_in_subprocess;

use module_loader::GraphModuleLoader;
use node_loader::SimpleNodeRequireLoader;
use permissions::build_permissions;
use services::RuntimeServices;
use sys_traits::impls::RealSys;
use worker_factory::create_web_worker_factory;

/// Switches the process cwd to `LibdenoOptions.cwd` for the duration of a
/// [`run`], restoring the host's cwd on every exit path (Drop). Without this,
/// scripts would observe the host's cwd (`process.cwd()`/`Deno.cwd()`,
/// relative `Deno.readFile`, relative imports) while permissions and entry
/// resolution use `options.cwd` — a split that silently breaks relative reads
/// under restricted grants.
///
/// The cwd is process-global, so all [`run`]/[`run_in_subprocess`] calls are
/// serialized on [`CWD_LOCK`] while it is in effect.
struct CwdGuard(Option<PathBuf>);

impl CwdGuard {
    fn set(cwd: &Path) -> Self {
        let prev = std::env::current_dir().ok();
        if std::env::set_current_dir(cwd).is_err() {
            eprintln!(
                "libdeno: failed to chdir to cwd {}; relative paths resolve against the host cwd",
                cwd.display()
            );
            return Self(None);
        }
        Self(prev)
    }
}

impl Drop for CwdGuard {
    fn drop(&mut self) {
        if let Some(prev) = &self.0 {
            let _ = std::env::set_current_dir(prev);
        }
    }
}

/// Serializes [`run`]/[`run_in_subprocess`]: the process cwd is switched to
/// `LibdenoOptions.cwd` for the duration of a run, and the cwd a subprocess
/// inherits is captured at spawn, so concurrent calls would stomp each other.
/// The CLI has the same single-cwd model; runs are heavyweight (a full worker
/// bootstrap), so serialization costs nothing in practice.
pub(crate) static CWD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

// Generated by build.rs: the V8 snapshot and the residual lazy-load sources.
include!(concat!(env!("OUT_DIR"), "/EXTENSION_RESIDUAL_SOURCES.rs"));
static STARTUP_SNAPSHOT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/CLI_SNAPSHOT.bin"));

/// Options for a single [`run`] invocation.
#[derive(Debug, Clone, Default)]
pub struct LibdenoOptions {
    /// Permission capability strings in `--allow-*` CLI format, e.g.
    /// `"--allow-read=./src"`, `"--allow-net=example.com:8080"`.
    ///
    /// An empty list grants everything (the default). Passing any entry
    /// restricts the runtime to the declared capabilities; a flag without a
    /// value allows that capability globally.
    pub permissions: Vec<String>,
    /// Arguments exposed to the script via `process.argv` (after `argv[0]`).
    pub args: Vec<String>,
    /// Working directory that relative paths (entry, permissions, node_modules
    /// discovery) resolve against. Defaults to the process current directory.
    ///
    /// [`run`] switches the process cwd to this directory for the duration of
    /// the run (restoring it afterwards), so scripts see it as their working
    /// directory too. Concurrent runs in the same process are not supported.
    pub cwd: Option<PathBuf>,
}

/// Errors from a [`run`] invocation.
#[derive(Debug, thiserror::Error)]
pub enum LibdenoError {
    /// The entry path could not be resolved to a module.
    #[error("failed to resolve entry module: {0}")]
    Entry(AnyError),
    /// Permission capability strings could not be parsed.
    #[error("invalid permission flags: {0}")]
    Permission(String),
    /// The runtime failed to start or the script failed.
    #[error("{0}")]
    Runtime(#[from] AnyError),
    /// A JS exception escaped the event loop (module execution / event loop).
    #[error("{0}")]
    Core(#[from] deno_core::error::CoreError),
    /// A JS exception escaped one of the lifecycle event dispatches.
    #[error("{0}")]
    Js(#[from] Box<deno_core::error::JsError>),
    /// I/O failure in the host (cwd resolution).
    #[error("{0}")]
    Io(#[from] std::io::Error),
}

/// Runs `entry` (a file, a directory, or a package.json) to completion and
/// returns the exit code the script requested (0 on normal completion).
///
/// Each call builds its own current-thread runtime and worker. Calls are
/// serialized process-wide: the process cwd is switched to `options.cwd` for
/// the duration of the run (and restored afterwards), so scripts observe a
/// consistent working directory.
pub fn run(entry: impl AsRef<Path>, options: &LibdenoOptions) -> Result<i32, LibdenoError> {
    // The process cwd is process-global; serialize so a concurrent run cannot
    // observe another run's cwd (see CWD_LOCK).
    let _lock = CWD_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| LibdenoError::Runtime(deno_core::anyhow::anyhow!(e)))?;
    runtime.block_on(run_inner(entry.as_ref(), options))
}

async fn run_inner(entry: &Path, options: &LibdenoOptions) -> Result<i32, LibdenoError> {
    // rustls needs an explicit CryptoProvider when both the aws-lc-rs and ring
    // providers are enabled in the dep graph (deno_tls enables aws-lc-rs;
    // reqwest's rustls features enable ring). The deno CLI does the same.
    let _ = deno_runtime::deno_tls::rustls::crypto::CryptoProvider::install_default(
        deno_runtime::deno_tls::rustls::crypto::aws_lc_rs::default_provider(),
    );

    let cwd = options.cwd.clone().unwrap_or(std::env::current_dir()?);
    // Scripts observe this directory as their working directory
    // (process.cwd()/Deno.cwd(), relative reads, relative imports); the
    // previous process cwd is restored when the run finishes.
    let _cwd_guard = CwdGuard::set(&cwd);
    let main_module = resolve_entry(entry, &cwd).map_err(LibdenoError::Entry)?;

    let fs: Arc<dyn FileSystem> = Arc::new(RealFs);
    let config_start_paths = main_module
        .to_file_path()
        .ok()
        .and_then(|p| p.parent().map(|d| vec![d.to_path_buf()]))
        .unwrap_or_else(|| vec![cwd.clone()]);
    let permission_parser: Arc<
        deno_runtime::deno_permissions::RuntimePermissionDescriptorParser<RealSys>,
    > = Arc::new(deno_runtime::deno_permissions::RuntimePermissionDescriptorParser::new(RealSys));
    let permissions = build_permissions(&options.permissions, permission_parser.clone(), &cwd)?;
    let services = Arc::new(
        RuntimeServices::new(cwd, config_start_paths, permissions.clone())
            .await
            .map_err(LibdenoError::Runtime)?,
    );

    // has_node_modules_dir must be derived from the resolver AFTER
    // RuntimeServices::new: that construction runs
    // initialize_npm_resolution_if_managed, which decides Managed vs BYONM.
    let has_node_modules_dir = {
        use deno_resolver::npm::NpmResolver;
        match services
            .shared
            .resolver_factory
            .npm_resolver()
            .map_err(LibdenoError::Runtime)?
        {
            NpmResolver::Managed(managed) => managed.root_node_modules_path().is_some(),
            NpmResolver::Byonm(byonm) => byonm.root_node_modules_path().is_some(),
        }
    };

    let module_loader: Rc<dyn deno_core::ModuleLoader> = Rc::new(GraphModuleLoader::new(
        services.shared.clone(),
        permissions.clone(),
    ));

    let node_resolver = services.shared.resolver_factory.node_resolver()?.clone();
    let pkg_json_resolver = services.shared.resolver_factory.pkg_json_resolver().clone();
    let cjs_tracker = services.shared.resolver_factory.cjs_tracker()?.clone();
    let in_npm_pkg_checker = services
        .shared
        .resolver_factory
        .in_npm_package_checker()?
        .clone();
    let node_require_loader: deno_runtime::deno_node::NodeRequireLoaderRc = Rc::new(
        SimpleNodeRequireLoader::new(cjs_tracker, in_npm_pkg_checker),
    );
    let node_sys = services.shared.sys.clone();
    let node_services = Some(NodeExtInitServices {
        node_require_loader: node_require_loader.clone(),
        node_resolver: node_resolver.clone(),
        pkg_json_resolver: pkg_json_resolver.clone(),
        sys: node_sys.clone(),
    });

    let blob_store = BlobStore::default_arc();
    let broadcast_channel = InMemoryBroadcastChannel::default();
    // Enable unstable APIs by default (kv, cron, ffi, webgpu...), matching an
    // "everything enabled" stance like `deno run --unstable`. The deno CLI
    // gates these behind flags; an embedded runtime has no flag surface.
    // The JS namespace (BootstrapOptions.unstable_features IDs) and the
    // op-level enforcement (FeatureChecker names) must stay in sync.
    const ENABLED_FEATURES: &[&str] = &["kv", "cron", "ffi", "webgpu"];
    let feature_checker = {
        let mut fc = deno_runtime::FeatureChecker::default();
        for feature in ENABLED_FEATURES {
            fc.enable_feature(feature);
        }
        Arc::new(fc)
    };
    let unstable_ids: Vec<i32> = deno_features::UNSTABLE_FEATURES
        .iter()
        .filter(|f| ENABLED_FEATURES.contains(&f.name))
        .map(|f| f.id)
        .collect();

    let worker_services = WorkerServiceOptions {
        blob_store: blob_store.clone(),
        broadcast_channel: broadcast_channel.clone(),
        deno_rt_native_addon_loader: None,
        feature_checker: feature_checker.clone(),
        fs: fs.clone(),
        module_loader: module_loader.clone(),
        node_services: node_services.clone(),
        npm_process_state_provider: Some(services.shared.npm_process_state_provider.clone()),
        permissions: permissions.clone(),
        root_cert_store_provider: None,
        fetch_dns_resolver: deno_runtime::deno_fetch::dns::Resolver::default(),
        shared_array_buffer_store: None,
        compiled_wasm_module_store: None,
        v8_code_cache: None,
        bundle_provider: None,
    };

    // Track against deno_runtime's release tag; scripts feature-detect on
    // Deno.version.deno, so this must be the embedded Deno release, NOT
    // libdeno's crate version. deno_runtime 0.265.0 == Deno v2.9.5.
    const DENO_VERSION: &str = "2.9.5";

    let main_bootstrap = BootstrapOptions {
        deno_version: DENO_VERSION.to_string(),
        user_agent: format!(
            "libdeno/{}/Deno/{}",
            env!("CARGO_PKG_VERSION"),
            DENO_VERSION
        ),
        has_node_modules_dir,
        location: Some(main_module.clone()),
        args: options.args.clone(),
        unstable_features: unstable_ids,
        // `child_process.fork`/`spawn(stdio: ["ipc"])` hands the child the IPC
        // pipe via NODE_CHANNEL_FD (+ serialization mode), mirroring the CLI's
        // node_ipc_init().
        node_ipc_init: std::env::var("NODE_CHANNEL_FD")
            .ok()
            .and_then(|v| v.parse::<i64>().ok())
            .map(|fd| {
                let serialization =
                    match std::env::var("NODE_CHANNEL_SERIALIZATION_MODE").as_deref() {
                        Ok("advanced") => {
                            deno_runtime::deno_node::ops::ipc::ChildIpcSerialization::Advanced
                        }
                        _ => deno_runtime::deno_node::ops::ipc::ChildIpcSerialization::Json,
                    };
                (fd, serialization)
            }),
        ..Default::default()
    };

    // Factory for `new Worker(...)`: nested workers reuse the same module
    // loader, services, and snapshot. Mirror of the CLI's worker factory.
    let create_web_worker_cb: Arc<deno_runtime::ops::worker_host::CreateWebWorkerCb> =
        create_web_worker_factory(
            blob_store,
            broadcast_channel,
            feature_checker,
            fs.clone(),
            services.shared.clone(),
            MainInspectorSessionChannel::default(),
            main_bootstrap.clone(),
        )?;

    let options = WorkerOptions {
        bootstrap: main_bootstrap,
        create_web_worker_cb,
        extensions: vec![],
        startup_snapshot: Some(STARTUP_SNAPSHOT),
        residual_lazy_js_sources: RESIDUAL_LAZY_JS,
        residual_lazy_esm_sources: RESIDUAL_LAZY_ESM,
        ..Default::default()
    };

    let mut worker = MainWorker::bootstrap_from_options(&main_module, worker_services, options);

    // Intercept Deno.exit: registering a WatcherExitHandle in the OpState makes
    // op_exit terminate the isolate and return (the CLI's --watch path) instead
    // of calling std::process::exit and killing the embedder's process. The
    // requested code is preserved in the ExitCode op state and returned below.
    let isolate_handle = worker.js_runtime.v8_isolate().thread_safe_handle();
    worker
        .js_runtime
        .op_state()
        .borrow_mut()
        .put(deno_runtime::deno_os::WatcherExitHandle(isolate_handle));

    let run_result: Result<(), LibdenoError> = async {
        worker.execute_main_module(&main_module).await?;
        worker.run_event_loop(false).await?;
        worker.dispatch_load_event()?;
        worker.run_event_loop(false).await?;
        worker.dispatch_beforeunload_event()?;
        worker.dispatch_unload_event()?;
        worker.dispatch_process_beforeexit_event()?;
        worker.dispatch_process_exit_event()?;
        Ok(())
    }
    .await;

    match run_result {
        Ok(()) => Ok(worker.exit_code()),
        // A termination error with the WatcherExited marker set means the script
        // called Deno.exit(n): return n instead of propagating the termination
        // error. (Deno.exit(0) is indistinguishable from natural completion.)
        Err(_)
            if worker
                .js_runtime
                .op_state()
                .borrow()
                .try_borrow::<deno_runtime::deno_os::WatcherExited>()
                .is_some() =>
        {
            Ok(worker.exit_code())
        }
        Err(e) => Err(e),
    }
}

/// Resolve the entry module: a file path, or a directory / package.json whose
/// `main` (default `index.js`) is used.
fn resolve_entry(path: &Path, cwd: &Path) -> Result<ModuleSpecifier, AnyError> {
    let path = if path.is_absolute() {
        path.to_path_buf()
    } else {
        cwd.join(path)
    };
    let file_path = if path.is_dir() {
        let pkg = path.join("package.json");
        if pkg.exists() {
            package_main(&pkg)?
        } else {
            path.join("index.js")
        }
    } else if path.file_name().and_then(|n| n.to_str()) == Some("package.json") {
        package_main(&path)?
    } else {
        path
    };
    ModuleSpecifier::from_file_path(&file_path)
        .map_err(|_| deno_core::anyhow::anyhow!("Invalid entry file path: {}", file_path.display()))
}

fn package_main(pkg_path: &Path) -> Result<PathBuf, AnyError> {
    let text = std::fs::read_to_string(pkg_path)?;
    let json: deno_core::serde_json::Value = deno_core::serde_json::from_str(&text)?;
    let main = json
        .get("main")
        .and_then(|v| v.as_str())
        .unwrap_or("index.js");
    Ok(pkg_path.parent().unwrap_or(Path::new(".")).join(main))
}

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

    fn temp_dir(name: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("libdeno-test-{}-{}", std::process::id(), name));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn resolve_entry_file() {
        let dir = temp_dir("entry-file");
        let file = dir.join("app.js");
        std::fs::write(&file, "").unwrap();
        let spec = resolve_entry(&file, &dir).unwrap();
        assert_eq!(spec.to_file_path().unwrap(), file);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_entry_directory_uses_package_main() {
        let dir = temp_dir("entry-dir-pkg");
        std::fs::write(
            dir.join("package.json"),
            r#"{"name":"app","main":"src/main.js"}"#,
        )
        .unwrap();
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/main.js"), "").unwrap();
        let spec = resolve_entry(&dir, &dir).unwrap();
        assert_eq!(spec.to_file_path().unwrap(), dir.join("src/main.js"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_entry_directory_defaults_to_index_js() {
        let dir = temp_dir("entry-dir-default");
        std::fs::write(dir.join("index.js"), "").unwrap();
        let spec = resolve_entry(&dir, &dir).unwrap();
        assert_eq!(spec.to_file_path().unwrap(), dir.join("index.js"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_entry_package_json_directly() {
        let dir = temp_dir("entry-pkgjson");
        std::fs::write(dir.join("package.json"), r#"{"main":"lib/index.js"}"#).unwrap();
        std::fs::create_dir_all(dir.join("lib")).unwrap();
        std::fs::write(dir.join("lib/index.js"), "").unwrap();
        let spec = resolve_entry(&dir.join("package.json"), &dir).unwrap();
        assert_eq!(spec.to_file_path().unwrap(), dir.join("lib/index.js"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn resolve_entry_relative_path_joins_cwd() {
        let dir = temp_dir("entry-relative");
        std::fs::write(dir.join("app.ts"), "").unwrap();
        let spec = resolve_entry(Path::new("app.ts"), &dir).unwrap();
        assert_eq!(spec.to_file_path().unwrap(), dir.join("app.ts"));
        let _ = std::fs::remove_dir_all(&dir);
    }
}