repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/integration/mod.rs
tests/integration/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::num::NonZeroUsize; use std::panic::AssertUnwindSafe; use std::path::PathBuf; use std::sync::Arc; use file_test_runner::RunOptions; use file_test_runner::TestResult; use file_test_runner::collection::CollectedTest; use file_test_runner::collection::CollectedTestCategory; use test_util::TestMacroCase; use test_util::test_runner::FlakyTestTracker; use test_util::test_runner::Parallelism; use test_util::test_runner::run_maybe_flaky_test; // These files have `_tests.rs` suffix to make it easier to tell which file is // the test (ex. `lint_tests.rs`) and which is the implementation (ex. `lint.rs`) // when both are open, especially for two tabs in VS Code #[path = "bench_tests.rs"] mod bench; #[path = "cache_tests.rs"] mod cache; #[path = "check_tests.rs"] mod check; #[path = "compile_tests.rs"] mod compile; #[path = "coverage_tests.rs"] mod coverage; #[path = "eval_tests.rs"] mod eval; #[path = "flags_tests.rs"] mod flags; #[path = "fmt_tests.rs"] mod fmt; #[path = "init_tests.rs"] mod init; #[path = "inspector_tests.rs"] mod inspector; #[path = "install_tests.rs"] mod install; #[path = "jsr_tests.rs"] mod jsr; #[path = "jupyter_tests.rs"] mod jupyter; #[path = "lsp_tests.rs"] mod lsp; #[path = "npm_tests.rs"] mod npm; #[path = "pm_tests.rs"] mod pm; #[path = "publish_tests.rs"] mod publish; #[path = "repl_tests.rs"] mod repl; #[path = "run_tests.rs"] mod run; #[path = "serve_tests.rs"] mod serve; #[path = "shared_library_tests.rs"] mod shared_library_tests; #[path = "task_tests.rs"] mod task; #[path = "test_tests.rs"] mod test; #[path = "upgrade_tests.rs"] mod upgrade; #[path = "watcher_tests.rs"] mod watcher; pub fn main() { let mut main_category: CollectedTestCategory<&'static TestMacroCase> = CollectedTestCategory { name: module_path!().to_string(), path: PathBuf::from(file!()), children: Default::default(), }; test_util::collect_and_filter_tests(&mut main_category); if main_category.is_empty() { return; // no tests to run for the filter } let run_test = move |test: &CollectedTest<&'static TestMacroCase>, flaky_test_tracker: &FlakyTestTracker, parallelism: Option<&Parallelism>| { if test.data.ignore { return TestResult::Ignored; } let run_test = || { let _test_timeout_holder = test.data.timeout.map(|timeout_secs| { test_util::test_runner::with_timeout( test.name.clone(), std::time::Duration::from_secs(timeout_secs as u64), ) }); let (mut captured_output, result) = test_util::print::with_captured_output(|| { TestResult::from_maybe_panic_or_result(AssertUnwindSafe(|| { (test.data.func)(); TestResult::Passed { duration: None } })) }); match result { TestResult::Passed { .. } | TestResult::Ignored => result, TestResult::Failed { output, duration } => { if !captured_output.is_empty() { captured_output.push(b'\n'); } captured_output.extend_from_slice(&output); TestResult::Failed { duration, output: captured_output, } } // no support for sub tests TestResult::SubTests { .. } => unreachable!(), } }; run_maybe_flaky_test( &test.name, test.data.flaky || *test_util::IS_CI, flaky_test_tracker, parallelism, run_test, ) }; let (watcher_tests, main_tests) = main_category.partition(|t| t.name.contains("::watcher::")); // watcher tests are really flaky, so run them sequentially let flaky_test_tracker = Arc::new(FlakyTestTracker::default()); let reporter = test_util::test_runner::get_test_reporter( "integration", flaky_test_tracker.clone(), ); file_test_runner::run_tests( &watcher_tests, RunOptions { parallelism: NonZeroUsize::new(1).unwrap(), reporter: reporter.clone(), }, { let flaky_test_tracker = flaky_test_tracker.clone(); move |test| run_test(test, &flaky_test_tracker, None) }, ); let parallelism = Parallelism::default(); file_test_runner::run_tests( &main_tests, RunOptions { parallelism: parallelism.max_parallelism(), reporter: reporter.clone(), }, move |test| run_test(test, &flaky_test_tracker, Some(&parallelism)), ); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/integration/jsr_tests.rs
tests/integration/jsr_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. use deno_cache_dir::HttpCache; use deno_lockfile::Lockfile; use deno_lockfile::NewLockfileOptions; use deno_semver::jsr::JsrDepPackageReq; use deno_semver::package::PackageNv; use serde_json::Value; use serde_json::json; use test_util as util; use url::Url; use util::TestContextBuilder; use util::assert_contains; use util::assert_not_contains; use util::test; #[test] fn fast_check_cache() { let test_context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let deno_dir = test_context.deno_dir(); let temp_dir = test_context.temp_dir(); let type_check_cache_path = deno_dir.path().join("check_cache_v2"); temp_dir.write( "main.ts", r#"import { add } from "jsr:@denotest/add@1"; const value: number = add(1, 2); console.log(value);"#, ); temp_dir.path().join("deno.json").write_json(&json!({ "vendor": true })); test_context .new_command() .args("check main.ts") .run() .skip_output_check(); type_check_cache_path.remove_file(); let check_debug_cmd = test_context .new_command() .args("check --log-level=debug main.ts"); let output = check_debug_cmd.run(); assert_contains!( output.combined_output(), "Using FastCheck cache for: @denotest/add@1.0.0" ); // modify the file in the vendor folder let vendor_dir = temp_dir.path().join("vendor"); let pkg_dir = vendor_dir.join("http_127.0.0.1_4250/@denotest/add/1.0.0/"); pkg_dir .join("mod.ts") .append("\nexport * from './other.ts';"); let nested_pkg_file = pkg_dir.join("other.ts"); nested_pkg_file.write("export function other(): string { return ''; }"); // invalidated let output = check_debug_cmd.run(); assert_not_contains!( output.combined_output(), "Using FastCheck cache for: @denotest/add@1.0.0" ); // ensure cache works let output = check_debug_cmd.run(); assert_contains!(output.combined_output(), "Already type checked"); // now validated type_check_cache_path.remove_file(); let output = check_debug_cmd.run(); let building_fast_check_msg = "Building fast check graph"; assert_contains!(output.combined_output(), building_fast_check_msg); assert_contains!( output.combined_output(), "Using FastCheck cache for: @denotest/add@1.0.0" ); // cause a fast check error in the nested package nested_pkg_file .append("\nexport function asdf(a: number) { let err: number = ''; return Math.random(); }"); check_debug_cmd.run().skip_output_check(); // ensure the cache still picks it up for this file type_check_cache_path.remove_file(); let output = check_debug_cmd.run(); assert_contains!(output.combined_output(), building_fast_check_msg); assert_contains!( output.combined_output(), "Using FastCheck cache for: @denotest/add@1.0.0" ); // see that the type checking error in the internal function gets surfaced with --all test_context .new_command() .args("check --all main.ts") .run() .assert_matches_text( "Check main.ts TS2322 [ERROR]: Type 'string' is not assignable to type 'number'. export function asdf(a: number) { let err: number = ''; return Math.random(); } ~~~ at http://127.0.0.1:4250/@denotest/add/1.0.0/other.ts:2:39 error: Type checking failed. ", ) .assert_exit_code(1); // now fix the package nested_pkg_file.write("export function test() {}"); let output = check_debug_cmd.run(); assert_contains!(output.combined_output(), building_fast_check_msg); assert_not_contains!( output.combined_output(), "Using FastCheck cache for: @denotest/add@1.0.0" ); // finally ensure it uses the cache type_check_cache_path.remove_file(); let output = check_debug_cmd.run(); assert_contains!(output.combined_output(), building_fast_check_msg); assert_contains!( output.combined_output(), "Using FastCheck cache for: @denotest/add@1.0.0" ); } struct TestNpmPackageInfoProvider; #[async_trait::async_trait(?Send)] impl deno_lockfile::NpmPackageInfoProvider for TestNpmPackageInfoProvider { async fn get_npm_package_info( &self, values: &[deno_semver::package::PackageNv], ) -> Result< Vec<deno_lockfile::Lockfile5NpmInfo>, Box<dyn std::error::Error + Send + Sync>, > { Ok(values.iter().map(|_| Default::default()).collect()) } } #[test] async fn specifiers_in_lockfile() { let test_context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let temp_dir = test_context.temp_dir(); temp_dir.write( "main.ts", r#"import version from "jsr:@denotest/no-module-graph@0.1"; console.log(version);"#, ); temp_dir.write("deno.json", "{}"); // to automatically create a lockfile test_context .new_command() .args("run --quiet main.ts") .run() .assert_matches_text("0.1.1\n"); let lockfile_path = temp_dir.path().join("deno.lock"); let mut lockfile = Lockfile::new( NewLockfileOptions { file_path: lockfile_path.to_path_buf(), content: &lockfile_path.read_to_string(), overwrite: false, }, &TestNpmPackageInfoProvider, ) .await .unwrap(); *lockfile .content .packages .specifiers .get_mut( &JsrDepPackageReq::from_str("jsr:@denotest/no-module-graph@0.1").unwrap(), ) .unwrap() = "0.1.0".into(); lockfile_path.write(lockfile.as_json_string()); test_context .new_command() .args("run --quiet main.ts") .run() .assert_matches_text("0.1.0\n"); } fn remove_version_from_meta_json(registry_json: &mut Value, version: &str) { registry_json .as_object_mut() .unwrap() .get_mut("versions") .unwrap() .as_object_mut() .unwrap() .remove(version); } fn remove_version_for_package( deno_dir: &util::TempDir, package: &str, version: &str, ) { let specifier = Url::parse(&format!("http://127.0.0.1:4250/{}/meta.json", package)) .unwrap(); let cache = deno_cache_dir::GlobalHttpCache::new( sys_traits::impls::RealSys, deno_dir.path().join("remote").to_path_buf(), ); let entry = cache .get(&cache.cache_item_key(&specifier).unwrap(), None) .unwrap() .unwrap(); let mut registry_json: serde_json::Value = serde_json::from_slice(&entry.content).unwrap(); remove_version_from_meta_json(&mut registry_json, version); cache .set( &specifier, entry.metadata.headers.clone(), registry_json.to_string().as_bytes(), ) .unwrap(); } #[test] fn reload_info_not_found_cache_but_exists_remote() { // This tests that when a local machine doesn't have a version // specified in a dependency that exists in the npm registry let test_context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let deno_dir = test_context.deno_dir(); let temp_dir = test_context.temp_dir(); temp_dir.write( "main.ts", "import { add } from 'jsr:@denotest/add@1'; console.log(add(1, 2));", ); // cache successfully to the deno_dir let output = test_context.new_command().args("cache main.ts").run(); output.assert_matches_text(concat!( "Download http://127.0.0.1:4250/@denotest/add/meta.json\n", "Download http://127.0.0.1:4250/@denotest/add/1.0.0_meta.json\n", "Download http://127.0.0.1:4250/@denotest/add/1.0.0/mod.ts\n", )); // modify the package information in the cache to remove the latest version remove_version_for_package(deno_dir, "@denotest/add", "1.0.0"); // should error when `--cache-only` is used now because the version is not in the cache let output = test_context .new_command() .args("run --cached-only main.ts") .run(); output.assert_exit_code(1); output.assert_matches_text("error: JSR package manifest for '@denotest/add' failed to load. Could not resolve version constraint using only cached data. Try running again without --cached-only at file:///[WILDCARD]main.ts:1:21 "); // now try running without it, it should download the package now test_context .new_command() .args("run main.ts") .run() .assert_matches_text(concat!( "Download http://127.0.0.1:4250/@denotest/add/meta.json\n", "Download http://127.0.0.1:4250/@denotest/add/1.0.0_meta.json\n", "3\n", )) .assert_exit_code(0); } #[test] fn install_cache_busts_if_version_not_found() { // Tests that if you try to deno install a package, if we can't find the version in the cached // meta.json, we bust the cache to . let test_context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let deno_dir = test_context.deno_dir(); let temp_dir = test_context.temp_dir(); temp_dir.write( "deno.json", r#"{ "imports": { "@denotest/has-pre-release": "jsr:@denotest/has-pre-release@2.0.0-beta.1" } }"#, ); // cache successfully to the deno_dir let output = test_context.new_command().args("install").run(); output.assert_matches_text(concat!( "Download http://127.0.0.1:4250/@denotest/has-pre-release/meta.json\n", "Download http://127.0.0.1:4250/@denotest/has-pre-release/2.0.0-beta.1_meta.json\n", "Download http://127.0.0.1:4250/@denotest/has-pre-release/2.0.0-beta.1/mod.ts\n", )); // modify the package information in the cache to remove the latest version remove_version_for_package( deno_dir, "@denotest/has-pre-release", "2.0.0-beta.2", ); temp_dir.write( "deno.json", r#"{ "imports": { "@denotest/has-pre-release": "jsr:@denotest/has-pre-release@2.0.0-beta.2" } }"#, ); // should error when `--cache-only` is used now because the version is not in the cache let output = test_context.new_command().args("install").run(); output.assert_matches_text(concat!( "Download http://127.0.0.1:4250/@denotest/has-pre-release/meta.json\n", "Download http://127.0.0.1:4250/@denotest/has-pre-release/2.0.0-beta.2_meta.json\n", "Download http://127.0.0.1:4250/@denotest/has-pre-release/2.0.0-beta.2/mod.ts\n", )); output.assert_exit_code(0); } #[test] async fn lockfile_bad_package_integrity() { let test_context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let temp_dir = test_context.temp_dir(); temp_dir.write( "main.ts", r#"import version from "jsr:@denotest/no-module-graph@0.1"; console.log(version);"#, ); temp_dir.write("deno.json", "{}"); // to automatically create a lockfile test_context .new_command() .args("run --quiet main.ts") .run() .assert_matches_text("0.1.1\n"); let lockfile_path = temp_dir.path().join("deno.lock"); let mut lockfile = Lockfile::new( NewLockfileOptions { file_path: lockfile_path.to_path_buf(), content: &lockfile_path.read_to_string(), overwrite: false, }, &TestNpmPackageInfoProvider, ) .await .unwrap(); let pkg_nv = "@denotest/no-module-graph@0.1.1"; let original_integrity = get_lockfile_pkg_integrity(&lockfile, pkg_nv); set_lockfile_pkg_integrity(&mut lockfile, pkg_nv, "bad_integrity"); lockfile_path.write(lockfile.as_json_string()); let actual_integrity = test_context.get_jsr_package_integrity("@denotest/no-module-graph/0.1.1"); let integrity_check_failed_msg = format!("[WILDCARD]Integrity check failed for package. The source code is invalid, as it does not match the expected hash in the lock file. Package: @denotest/no-module-graph@0.1.1 Actual: {} Expected: bad_integrity This could be caused by: * the lock file may be corrupt * the source itself may be corrupt Investigate the lockfile; delete it to regenerate the lockfile or --reload to reload the source code from the server. ", actual_integrity); test_context .new_command() .args("run --quiet main.ts") .run() .assert_matches_text(&integrity_check_failed_msg) .assert_exit_code(10); // now try with a vendor folder temp_dir .path() .join("deno.json") .write_json(&json!({ "vendor": true })); // should fail again test_context .new_command() .args("run --quiet main.ts") .run() .assert_matches_text(&integrity_check_failed_msg) .assert_exit_code(10); // now update to the correct integrity set_lockfile_pkg_integrity(&mut lockfile, pkg_nv, &original_integrity); lockfile_path.write(lockfile.as_json_string()); // should pass now test_context .new_command() .args("run --quiet main.ts") .run() .assert_matches_text("0.1.1\n") .assert_exit_code(0); // now update to a bad integrity again set_lockfile_pkg_integrity(&mut lockfile, pkg_nv, "bad_integrity"); lockfile_path.write(lockfile.as_json_string()); // shouldn't matter because we have a vendor folder test_context .new_command() .args("run --quiet main.ts") .run() .assert_matches_text("0.1.1\n") .assert_exit_code(0); // now remove the vendor dir and it should fail again temp_dir.path().join("vendor").remove_dir_all(); test_context .new_command() .args("run --quiet main.ts") .run() .assert_matches_text(&integrity_check_failed_msg) .assert_exit_code(10); } #[test] fn bad_manifest_checksum() { let test_context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let temp_dir = test_context.temp_dir(); temp_dir.write( "main.ts", r#"import { add } from "jsr:@denotest/bad-manifest-checksum@1.0.0"; console.log(add);"#, ); // test it properly checks the checksum on download test_context .new_command() .args("run main.ts") .run() .assert_matches_text( "Download http://127.0.0.1:4250/@denotest/bad-manifest-checksum/meta.json Download http://127.0.0.1:4250/@denotest/bad-manifest-checksum/1.0.0_meta.json Download http://127.0.0.1:4250/@denotest/bad-manifest-checksum/1.0.0/mod.ts error: Integrity check failed in package. The package may have been tampered with. Specifier: http://127.0.0.1:4250/@denotest/bad-manifest-checksum/1.0.0/mod.ts Actual: 9a30ac96b5d5c1b67eca69e1e2cf0798817d9578c8d7d904a81a67b983b35cba Expected: bad-checksum If you modified your global cache, run again with the --reload flag to restore its state. If you want to modify dependencies locally run again with the --vendor flag or specify `\"vendor\": true` in a deno.json then modify the contents of the vendor/ folder. ", ) .assert_exit_code(10); // test it properly checks the checksum when loading from the cache test_context .new_command() .args("run main.ts") .run() .assert_matches_text( "error: Integrity check failed in package. The package may have been tampered with. Specifier: http://127.0.0.1:4250/@denotest/bad-manifest-checksum/1.0.0/mod.ts Actual: 9a30ac96b5d5c1b67eca69e1e2cf0798817d9578c8d7d904a81a67b983b35cba Expected: bad-checksum If you modified your global cache, run again with the --reload flag to restore its state. If you want to modify dependencies locally run again with the --vendor flag or specify `\"vendor\": true` in a deno.json then modify the contents of the vendor/ folder. ", ) .assert_exit_code(10); } fn get_lockfile_pkg_integrity(lockfile: &Lockfile, pkg_nv: &str) -> String { lockfile .content .packages .jsr .get(&PackageNv::from_str(pkg_nv).unwrap()) .unwrap() .integrity .clone() } fn set_lockfile_pkg_integrity( lockfile: &mut Lockfile, pkg_nv: &str, integrity: &str, ) { lockfile .content .packages .jsr .get_mut(&PackageNv::from_str(pkg_nv).unwrap()) .unwrap() .integrity = integrity.to_string(); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/integration/run_tests.rs
tests/integration/run_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::io::BufReader; use std::io::Cursor; use std::io::Read; use std::io::Write; use std::process::Command; use std::process::Stdio; use std::sync::Arc; use bytes::Bytes; use hickory_proto::serialize::txt::Parser; use hickory_server::authority::AuthorityObject; use pretty_assertions::assert_eq; use rustls::ClientConnection; use rustls_tokio_stream::TlsStream; use serde_json::json; use test_util as util; use test_util::TempDir; use test_util::eprintln; use test_util::itest; use test_util::println; use test_util::test; use util::PathRef; use util::TestContext; use util::TestContextBuilder; use util::assert_contains; use util::assert_not_contains; const CODE_CACHE_DB_FILE_NAME: &str = "v8_code_cache_v2"; // tests to ensure that when `--location` is set, all code shares the same // localStorage cache based on the origin of the location URL. #[test] fn webstorage_location_shares_origin() { let deno_dir = util::new_deno_dir(); let output = util::deno_cmd_with_deno_dir(&deno_dir) .current_dir(util::testdata_path()) .arg("run") .arg("--location") .arg("https://example.com/a.ts") .arg("run/webstorage/fixture.ts") .stdout(Stdio::piped()) .spawn() .unwrap() .wait_with_output() .unwrap(); assert!(output.status.success()); assert_eq!(output.stdout, b"Storage { length: 0 }\n"); let output = util::deno_cmd_with_deno_dir(&deno_dir) .current_dir(util::testdata_path()) .arg("run") .arg("--location") .arg("https://example.com/b.ts") .arg("run/webstorage/logger.ts") .stdout(Stdio::piped()) .spawn() .unwrap() .wait_with_output() .unwrap(); assert!(output.status.success()); assert_eq!(output.stdout, b"Storage { hello: \"deno\", length: 1 }\n"); } // test to ensure that when a --config file is set, but no --location, that // storage persists against unique configuration files. #[test] fn webstorage_config_file() { let context = TestContext::default(); context .new_command() .args( "run --config run/webstorage/config_a.jsonc run/webstorage/fixture.ts", ) .run() .assert_matches_text("Storage { length: 0 }\n"); context .new_command() .args("run --config run/webstorage/config_b.jsonc run/webstorage/logger.ts") .run() .assert_matches_text("Storage { length: 0 }\n"); context .new_command() .args("run --config run/webstorage/config_a.jsonc run/webstorage/logger.ts") .run() .assert_matches_text("Storage { hello: \"deno\", length: 1 }\n"); } // tests to ensure `--config` does not effect persisted storage when a // `--location` is provided. #[test] fn webstorage_location_precedes_config() { let context = TestContext::default(); context.new_command() .args("run --location https://example.com/a.ts --config run/webstorage/config_a.jsonc run/webstorage/fixture.ts") .run() .assert_matches_text("Storage { length: 0 }\n"); context.new_command() .args("run --location https://example.com/b.ts --config run/webstorage/config_b.jsonc run/webstorage/logger.ts") .run() .assert_matches_text("Storage { hello: \"deno\", length: 1 }\n"); } // test to ensure that when there isn't a configuration or location, that the // main module is used to determine how to persist storage data. #[test] fn webstorage_main_module() { let context = TestContext::default(); context .new_command() .args("run run/webstorage/fixture.ts") .run() .assert_matches_text("Storage { length: 0 }\n"); context .new_command() .args("run run/webstorage/logger.ts") .run() .assert_matches_text("Storage { length: 0 }\n"); context .new_command() .args("run run/webstorage/fixture.ts") .run() .assert_matches_text("Storage { hello: \"deno\", length: 1 }\n"); } #[test] fn _083_legacy_external_source_map() { let _g = util::http_server(); let deno_dir = TempDir::new(); let module_url = url::Url::parse( "http://localhost:4545/run/083_legacy_external_source_map.ts", ) .unwrap(); // Write a faulty old external source map. let faulty_map_path = deno_dir.path().join("gen/http/localhost_PORT4545/9576bd5febd0587c5c4d88d57cb3ac8ebf2600c529142abe3baa9a751d20c334.js.map"); faulty_map_path.parent().create_dir_all(); faulty_map_path.write(r#"{\"version\":3,\"file\":\"\",\"sourceRoot\":\"\",\"sources\":[\"http://localhost:4545/083_legacy_external_source_map.ts\"],\"names\":[],\"mappings\":\";AAAA,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC\"}"#); let output = Command::new(util::deno_exe_path()) .env("DENO_DIR", deno_dir.path()) .current_dir(util::testdata_path()) .arg("run") .arg(module_url.to_string()) .output() .unwrap(); // Before https://github.com/denoland/deno/issues/6965 was fixed, the faulty // old external source map would cause a panic while formatting the error // and the exit code would be 101. The external source map should be ignored // in favor of the inline one. assert_eq!(output.status.code(), Some(1)); let out = std::str::from_utf8(&output.stdout).unwrap(); assert_eq!(out, ""); } itest!(_089_run_allow_list { args: "run --allow-run=curl run/089_run_allow_list.ts", envs: vec![ ("LD_LIBRARY_PATH".to_string(), "".to_string()), ("DYLD_FALLBACK_LIBRARY_PATH".to_string(), "".to_string()) ], output: "run/089_run_allow_list.ts.out", }); #[test(flaky)] fn _090_run_permissions_request() { TestContext::default() .new_command() .args_vec(["run", "--quiet", "run/090_run_permissions_request.ts"]) .with_pty(|mut console| { console.expect(concat!( "┏ ⚠️ Deno requests run access to \"ls\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-run\r\n", "┠─ Run again with --allow-run to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all run permissions)", )); console.human_delay(); console.write_line_raw("y"); console.expect("Granted run access to \"ls\"."); console.expect(concat!( "┏ ⚠️ Deno requests run access to \"cat\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-run\r\n", "┠─ Run again with --allow-run to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all run permissions)", )); console.human_delay(); console.write_line_raw("n"); console.expect("Denied run access to \"cat\"."); console.expect("granted"); console.expect("denied"); }); } #[test(flaky)] fn _090_run_permissions_request_sync() { TestContext::default() .new_command() .args_vec(["run", "--quiet", "run/090_run_permissions_request_sync.ts"]) .with_pty(|mut console| { console.expect(concat!( "┏ ⚠️ Deno requests run access to \"ls\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-run\r\n", "┠─ Run again with --allow-run to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all run permissions)", )); console.human_delay(); console.write_line_raw("y"); console.expect("Granted run access to \"ls\"."); console.expect(concat!( "┏ ⚠️ Deno requests run access to \"cat\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-run\r\n", "┠─ Run again with --allow-run to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all run permissions)", )); console.human_delay(); console.write_line_raw("n"); console.expect("Denied run access to \"cat\"."); console.expect("granted"); console.expect("denied"); }); } #[test(flaky)] fn permissions_prompt_allow_all() { TestContext::default() .new_command() .args_vec(["run", "--quiet", "run/permissions_prompt_allow_all.ts"]) .with_pty(|mut console| { // "run" permissions console.expect(concat!( "┏ ⚠️ Deno requests run access to \"FOO\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-run\r\n", "┠─ Run again with --allow-run to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all run permissions)", )); console.human_delay(); console.write_line_raw("A"); console.expect("Granted all run access."); // "read" permissions console.expect(concat!( "┏ ⚠️ Deno requests read access to \"FOO\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-read\r\n", "┠─ Run again with --allow-read to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all read permissions)", )); console.human_delay(); console.write_line_raw("A"); console.expect("Granted all read access."); // "write" permissions console.expect(concat!( "┏ ⚠️ Deno requests write access to \"FOO\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-write\r\n", "┠─ Run again with --allow-write to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all write permissions)", )); console.human_delay(); console.write_line_raw("A"); console.expect("Granted all write access."); // "net" permissions console.expect(concat!( "┏ ⚠️ Deno requests net access to \"foo\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-net\r\n", "┠─ Run again with --allow-net to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all net permissions)", )); console.human_delay(); console.write_line_raw("A"); console.expect("Granted all net access."); // "env" permissions console.expect(concat!( "┏ ⚠️ Deno requests env access to \"FOO\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-env\r\n", "┠─ Run again with --allow-env to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all env permissions)", )); console.human_delay(); console.write_line_raw("A"); console.expect("Granted all env access."); // "sys" permissions console.expect(concat!( "┏ ⚠️ Deno requests sys access to \"loadavg\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-sys\r\n", "┠─ Run again with --allow-sys to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all sys permissions)", )); console.human_delay(); console.write_line_raw("A"); console.expect("Granted all sys access."); // "ffi" permissions console.expect(concat!( "┏ ⚠️ Deno requests ffi access to \"FOO\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-ffi\r\n", "┠─ Run again with --allow-ffi to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all ffi permissions)", )); console.human_delay(); console.write_line_raw("A"); console.expect("Granted all ffi access.") }, ); } #[test(flaky)] fn permissions_prompt_allow_all_2() { TestContext::default() .new_command() .args_vec(["run", "--quiet", "run/permissions_prompt_allow_all_2.ts"]) .with_pty(|mut console| { // "env" permissions console.expect(concat!( "┏ ⚠️ Deno requests env access to \"FOO\".\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-env\r\n", "┠─ Run again with --allow-env to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all env permissions)", )); console.human_delay(); console.write_line_raw("A"); console.expect("Granted all env access."); // "sys" permissions console.expect(concat!( "┏ ⚠️ Deno requests sys access to \"loadavg\".\r\n", "┠─ Requested by `Deno.loadavg()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-sys\r\n", "┠─ Run again with --allow-sys to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all sys permissions)", )); console.human_delay(); console.write_line_raw("A"); console.expect("Granted all sys access."); let text = console.read_until("Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all read permissions)"); // "read" permissions test_util::assertions::assert_wildcard_match(&text, concat!( "\r\n", "┏ ⚠️ Deno requests read access to \"[WILDCARD]tests[WILDCHAR]testdata\".\r\n", "┠─ Requested by `Deno.lstatSync()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-read\r\n", "┠─ Run again with --allow-read to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all read permissions)", )); console.human_delay(); console.write_line_raw("A"); console.expect("Granted all read access."); }); } #[test(flaky)] fn permissions_prompt_allow_all_lowercase_a() { TestContext::default() .new_command() .args_vec(["run", "--quiet", "run/permissions_prompt_allow_all.ts"]) .with_pty(|mut console| { // "run" permissions console.expect(concat!( "┏ ⚠️ Deno requests run access to \"FOO\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-run\r\n", "┠─ Run again with --allow-run to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all run permissions)", )); console.human_delay(); console.write_line_raw("a"); console.expect("Unrecognized option."); }); } #[test(flaky)] fn permission_request_long() { TestContext::default() .new_command() .args_vec(["run", "--quiet", "run/permission_request_long.ts"]) .with_pty(|mut console| { console.expect(concat!( "was larger than the configured maximum length (10240 bytes): denying request.\r\n", "❌ WARNING: This may indicate that code is trying to bypass or hide permission check requests.\r\n", "❌ Run again with --allow-read to bypass this check if this is really what you want to do.\r\n", )); }); } #[test(flaky)] fn permissions_cache() { TestContext::default() .new_command() .args_vec(["run", "--quiet", "run/permissions_cache.ts"]) .with_pty(|mut console| { console.expect(concat!( "prompt\r\n", "┏ ⚠️ Deno requests read access to \"foo\".\r\n", "┠─ Requested by `Deno.permissions.request()` API.\r\n", "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-read\r\n", "┠─ Run again with --allow-read to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all read permissions)", )); console.human_delay(); console.write_line_raw("y"); console.expect("Granted read access to \"foo\"."); console.expect("granted"); console.expect("prompt"); }); } #[test(flaky)] fn permissions_trace() { TestContext::default() .new_command() .env("DENO_TRACE_PERMISSIONS", "1") .args_vec(["run", "--quiet", "run/permissions_trace.ts"]) .with_pty(|mut console| { let text = console.read_until("Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all sys permissions)"); test_util::assertions::assert_wildcard_match(&text, concat!( "┏ ⚠️ Deno requests sys access to \"hostname\".\r\n", "┠─ Requested by `Deno.hostname()` API.\r\n", "┃ β”œβ”€ Object.hostname (ext:deno_os/30_os.js:43:10)\r\n", "┃ β”œβ”€ foo (file://[WILDCARD]/run/permissions_trace.ts:2:8)\r\n", "┃ β”œβ”€ bar (file://[WILDCARD]/run/permissions_trace.ts:6:3)\r\n", "┃ └─ file://[WILDCARD]/run/permissions_trace.ts:9:1\r\n", "┠─ Learn more at: https://docs.deno.com/go/--allow-sys\r\n", "┠─ Run again with --allow-sys to bypass this prompt.\r\n", "β”— Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all sys permissions)", )); console.human_delay(); console.write_line_raw("y"); console.expect("Granted sys access to \"hostname\"."); }); } #[test] fn permissions_audit() { let ctx = TestContext::default(); let dir = ctx.temp_dir(); let path = dir.path().join(std::path::Path::new("audit.jsonl")); ctx .new_command() .env("DENO_AUDIT_PERMISSIONS", &path) .args_vec(["run", "-A", "run/permissions_audit.ts"]) .run() .skip_output_check(); let file = std::fs::read_to_string(path).unwrap(); test_util::assertions::assert_wildcard_match( &file, r#"{"v":1,"datetime":"[WILDCARD]","permission":"sys","value":"hostname"} {"v":1,"datetime":"[WILDCARD]","permission":"read","value":"[WILDCARD]"} {"v":1,"datetime":"[WILDCARD]","permission":"write","value":"[WILDCARD]"} {"v":1,"datetime":"[WILDCARD]","permission":"env","value":"FOO"} "#, ); } #[test] fn permissions_audit_with_traces() { let ctx = TestContext::default(); let dir = ctx.temp_dir(); let path = dir.path().join(std::path::Path::new("audit.jsonl")); ctx .new_command() .env("DENO_AUDIT_PERMISSIONS", &path) .env("DENO_TRACE_PERMISSIONS", "1") .args_vec(["run", "-A", "run/permissions_audit.ts"]) .run() .skip_output_check(); let file = std::fs::read_to_string(path).unwrap(); test_util::assertions::assert_wildcard_match( &file, r#"{"v":1,"datetime":"[WILDCARD]","permission":"sys","value":"hostname","stack":[WILDCARD]} {"v":1,"datetime":"[WILDCARD]","permission":"read","value":"[WILDCARD]","stack":[WILDCARD]} {"v":1,"datetime":"[WILDCARD]","permission":"write","value":"[WILDCARD]","stack":[WILDCARD]} {"v":1,"datetime":"[WILDCARD]","permission":"env","value":"FOO","stack":[WILDCARD]} "#, ); } itest!(lock_write_fetch { args: "run --quiet --allow-import --allow-read --allow-write --allow-env --allow-run run/lock_write_fetch/main.ts", output: "run/lock_write_fetch/main.out", http_server: true, exit_code: 0, }); #[test] fn lock_redirects() { let context = TestContextBuilder::new() .use_temp_cwd() .use_http_server() .add_npm_env_vars() .build(); let temp_dir = context.temp_dir(); temp_dir.write("deno.json", "{}"); // cause a lockfile to be created temp_dir.write( "main.ts", "import 'http://localhost:4546/run/001_hello.js';", ); context .new_command() .args("run --allow-import main.ts") .run() .skip_output_check(); let initial_lockfile_text = r#"{ "version": "5", "redirects": { "http://localhost:4546/run/001_hello.js": "http://localhost:4545/run/001_hello.js" }, "remote": { "http://localhost:4545/run/001_hello.js": "c479db5ea26965387423ca438bb977d0b4788d5901efcef52f69871e4c1048c5" } } "#; assert_eq!(temp_dir.read_to_string("deno.lock"), initial_lockfile_text); context .new_command() .args("run --allow-import main.ts") .run() .assert_matches_text("Hello World\n"); assert_eq!(temp_dir.read_to_string("deno.lock"), initial_lockfile_text); // now try changing where the redirect occurs in the lockfile temp_dir.write("deno.lock", r#"{ "version": "5", "redirects": { "http://localhost:4546/run/001_hello.js": "http://localhost:4545/echo.ts" }, "remote": { "http://localhost:4545/run/001_hello.js": "c479db5ea26965387423ca438bb977d0b4788d5901efcef52f69871e4c1048c5" } } "#); // also, add some npm dependency to ensure it doesn't end up in // the redirects as they're currently stored separately temp_dir.write( "main.ts", "import 'http://localhost:4546/run/001_hello.js';\n import 'npm:@denotest/esm-basic';\n", ); // it should use the echo script instead context .new_command() .args("run --allow-import main.ts Hi there") .run() .assert_matches_text(concat!( "Download http://localhost:4545/echo.ts\n", "Download http://localhost:4260/@denotest%2fesm-basic\n", "Download http://localhost:4260/@denotest/esm-basic/1.0.0.tgz\n", "Hi, there", )); util::assertions::assert_wildcard_match( &temp_dir.read_to_string("deno.lock"), r#"{ "version": "5", "specifiers": { "npm:@denotest/esm-basic@*": "1.0.0" }, "npm": { "@denotest/esm-basic@1.0.0": { "integrity": "sha512-[WILDCARD]" } }, "redirects": { "http://localhost:4546/run/001_hello.js": "http://localhost:4545/echo.ts" }, "remote": { "http://localhost:4545/echo.ts": "829eb4d67015a695d70b2a33c78b631b29eea1dbac491a6bfcf394af2a2671c2", "http://localhost:4545/run/001_hello.js": "c479db5ea26965387423ca438bb977d0b4788d5901efcef52f69871e4c1048c5" } } "#, ); } #[test] fn lock_deno_json_package_json_deps() { let context = TestContextBuilder::new() .use_temp_cwd() .use_http_server() .add_npm_env_vars() .add_jsr_env_vars() .build(); let temp_dir = context.temp_dir().path(); let deno_json = temp_dir.join("deno.json"); let package_json = temp_dir.join("package.json"); // add a jsr and npm dependency deno_json.write_json(&json!({ "nodeModulesDir": "auto", "imports": { "esm-basic": "npm:@denotest/esm-basic", "module_graph": "jsr:@denotest/module-graph@1.4", } })); let main_ts = temp_dir.join("main.ts"); main_ts.write("import 'esm-basic'; import 'module_graph';"); context .new_command() .args("cache main.ts") .run() .skip_output_check(); let lockfile = temp_dir.join("deno.lock"); let esm_basic_integrity = get_lockfile_npm_package_integrity(&lockfile, "@denotest/esm-basic@1.0.0"); lockfile.assert_matches_json(json!({ "version": "5", "specifiers": { "jsr:@denotest/module-graph@1.4": "1.4.0", "npm:@denotest/esm-basic@*": "1.0.0" }, "jsr": { "@denotest/module-graph@1.4.0": { "integrity": "32de0973c5fa55772326fcd504a757f386d2b010db3e13e78f3bcf851e69473d" } }, "npm": { "@denotest/esm-basic@1.0.0": { "integrity": esm_basic_integrity, "tarball": "http://localhost:4260/@denotest/esm-basic/1.0.0.tgz" } }, "workspace": { "dependencies": [ "jsr:@denotest/module-graph@1.4", "npm:@denotest/esm-basic@*" ] } })); // now remove the npm dependency from the deno.json and move // it to a package.json that uses an alias deno_json.write_json(&json!({ "nodeModulesDir": "auto", "imports": { "module_graph": "jsr:@denotest/module-graph@1.4", } })); package_json.write_json(&json!({ "dependencies": { "esm-basic": "npm:@denotest/esm-basic" } })); context .new_command() .args("cache main.ts") .run() .skip_output_check(); main_ts.write("import 'module_graph';"); context .new_command() // ensure this doesn't clear out packageJson below .args("cache --no-npm main.ts") .run() .skip_output_check(); lockfile.assert_matches_json(json!({ "version": "5", "specifiers": { "jsr:@denotest/module-graph@1.4": "1.4.0", "npm:@denotest/esm-basic@*": "1.0.0" }, "jsr": { "@denotest/module-graph@1.4.0": { "integrity": "32de0973c5fa55772326fcd504a757f386d2b010db3e13e78f3bcf851e69473d" } }, "npm": { "@denotest/esm-basic@1.0.0": { "integrity": esm_basic_integrity, "tarball": "http://localhost:4260/@denotest/esm-basic/1.0.0.tgz" } }, "workspace": { "dependencies": [ "jsr:@denotest/module-graph@1.4" ], "packageJson": { "dependencies": [ "npm:@denotest/esm-basic@*" ] } } })); // now remove the package.json package_json.remove_file(); // cache and it will remove the package.json context .new_command() .args("cache main.ts") .run() .skip_output_check(); lockfile.assert_matches_json(json!({ "version": "5", "specifiers": { "jsr:@denotest/module-graph@1.4": "1.4.0", }, "jsr": { "@denotest/module-graph@1.4.0": { "integrity": "32de0973c5fa55772326fcd504a757f386d2b010db3e13e78f3bcf851e69473d" } }, "workspace": { "dependencies": [ "jsr:@denotest/module-graph@1.4" ] } })); // now remove the deps from the deno.json deno_json.write_json(&json!({ "nodeModulesDir": "auto" })); main_ts.write(""); context .new_command() .args("cache main.ts") .run() .skip_output_check(); lockfile.assert_matches_json(json!({ "version": "5" })); } #[test] fn lock_deno_json_package_json_deps_workspace() { let context = TestContextBuilder::new() .use_temp_cwd() .use_http_server() .add_npm_env_vars() .add_jsr_env_vars() .build(); let temp_dir = context.temp_dir().path(); // deno.json let deno_json = temp_dir.join("deno.json"); deno_json.write_json(&json!({ "nodeModulesDir": "auto" })); // package.json let package_json = temp_dir.join("package.json"); package_json.write_json(&json!({ "workspaces": ["package-a"], "dependencies": { "@denotest/cjs-default-export": "1" } })); // main.ts let main_ts = temp_dir.join("main.ts"); main_ts.write("import '@denotest/cjs-default-export';"); // package-a/package.json let a_package = temp_dir.join("package-a"); a_package.create_dir_all(); let a_package_json = a_package.join("package.json"); a_package_json.write_json(&json!({ "dependencies": { "@denotest/esm-basic": "1" } })); // package-a/main.ts let main_ts = a_package.join("main.ts"); main_ts.write("import '@denotest/esm-basic';"); context .new_command() .args("run package-a/main.ts") .run() .skip_output_check(); let lockfile = temp_dir.join("deno.lock"); let esm_basic_integrity = get_lockfile_npm_package_integrity(&lockfile, "@denotest/esm-basic@1.0.0"); let cjs_default_export_integrity = get_lockfile_npm_package_integrity( &lockfile, "@denotest/cjs-default-export@1.0.0", ); lockfile.assert_matches_json(json!({ "version": "5", "specifiers": { "npm:@denotest/cjs-default-export@1": "1.0.0", "npm:@denotest/esm-basic@1": "1.0.0" }, "npm": { "@denotest/cjs-default-export@1.0.0": { "integrity": cjs_default_export_integrity, "tarball": "http://localhost:4260/@denotest/cjs-default-export/1.0.0.tgz" }, "@denotest/esm-basic@1.0.0": { "integrity": esm_basic_integrity, "tarball": "http://localhost:4260/@denotest/esm-basic/1.0.0.tgz" } }, "workspace": { "packageJson": { "dependencies": [ "npm:@denotest/cjs-default-export@1" ] }, "members": { "package-a": { "packageJson": { "dependencies": [ "npm:@denotest/esm-basic@1" ] } } } } })); // run a command that causes discovery of the root package.json beside the lockfile context .new_command() .args("run main.ts") .run() .skip_output_check(); // now we should see the dependencies let cjs_default_export_integrity = get_lockfile_npm_package_integrity( &lockfile, "@denotest/cjs-default-export@1.0.0", ); let expected_lockfile = json!({ "version": "5", "specifiers": { "npm:@denotest/cjs-default-export@1": "1.0.0", "npm:@denotest/esm-basic@1": "1.0.0" }, "npm": { "@denotest/cjs-default-export@1.0.0": { "integrity": cjs_default_export_integrity, "tarball": "http://localhost:4260/@denotest/cjs-default-export/1.0.0.tgz" }, "@denotest/esm-basic@1.0.0": { "integrity": esm_basic_integrity, "tarball": "http://localhost:4260/@denotest/esm-basic/1.0.0.tgz" } }, "workspace": { "packageJson": { "dependencies": [ "npm:@denotest/cjs-default-export@1" ] }, "members": { "package-a": { "packageJson": { "dependencies": [ "npm:@denotest/esm-basic@1" ] } } } } }); lockfile.assert_matches_json(expected_lockfile.clone()); // now run the command again in the package with the nested package.json context .new_command() .args("run package-a/main.ts") .run() .skip_output_check(); // the lockfile should stay the same as the above because the package.json // was found in a different directory lockfile.assert_matches_json(expected_lockfile.clone()); } fn get_lockfile_npm_package_integrity( lockfile: &PathRef, package_name: &str, ) -> String { // todo(dsherret): it would be nice if the test server didn't produce // different hashes depending on what operating system it's running on lockfile .read_json_value() .get("npm") .unwrap() .get(package_name) .unwrap() .get("integrity") .unwrap() .as_str() .unwrap() .to_string() } itest!(error_013_missing_script { args: "run --reload missing_file_name", exit_code: 1, output: "run/error_013_missing_script.out", }); // We have an allow-import flag but not allow-read, it should still result in error. itest!(error_016_dynamic_import_permissions2 { args: "run --reload --allow-import run/error_016_dynamic_import_permissions2.js", output: "run/error_016_dynamic_import_permissions2.out", exit_code: 1, http_server: true, }); itest!(error_026_remote_import_error { args: "run --allow-import run/error_026_remote_import_error.ts", output: "run/error_026_remote_import_error.ts.out", exit_code: 1,
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/integration/shared_library_tests.rs
tests/integration/shared_library_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. #[cfg(all(target_os = "linux", target_arch = "x86_64"))] #[test_util::test] // https://github.com/denoland/deno/issues/18266 fn linux_shared_libraries() { use test_util as util; const EXPECTED: [&str; 7] = [ "linux-vdso.so.1", "libdl.so.2", "libgcc_s.so.1", "libpthread.so.0", "libm.so.6", "libc.so.6", "/lib64/ld-linux-x86-64.so.2", ]; let ldd = std::process::Command::new("ldd") .arg("-L") .arg(util::deno_exe_path()) .output() .expect("Failed to execute ldd"); let output = std::str::from_utf8(&ldd.stdout).unwrap(); // Ensure that the output contains only the expected shared libraries. for line in output.lines().skip(1) { let path = line.split_whitespace().next().unwrap(); assert!( EXPECTED.contains(&path), "Unexpected shared library: {}", path ); } } #[cfg(target_os = "macos")] #[test_util::test] // https://github.com/denoland/deno/issues/18243 // This test is to prevent inadvertently linking to more shared system libraries that usually // increases dyld startup time. fn macos_shared_libraries() { use test_util as util; // target/release/deno: // /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 1953.1.0) // /System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices (compatibility version 1.0.0, current version 1228.0.0) // /System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore (compatibility version 1.2.0, current version 1.11.0, weak) // /System/Library/Frameworks/Metal.framework/Versions/A/Metal (compatibility version 1.0.0, current version 341.16.0, weak) // /System/Library/Frameworks/CoreGraphics.framework/Versions/A/CoreGraphics (compatibility version 64.0.0, current version 1774.0.4, weak) // /System/Library/Frameworks/MetalPerformanceShaders.framework/Versions/A/MetalPerformanceShaders (compatibility version 1.0.0, current version 127.0.19, weak) // /usr/lib/libiconv.2.dylib (compatibility version 7.0.0, current version 7.0.0) // /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1319.0.0) // /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0) // path and whether its weak or not const EXPECTED: [(&str, bool); 11] = [ ( "/System/Library/Frameworks/Security.framework/Versions/A/Security", false, ), ( "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation", false, ), ( "/System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices", false, ), ( "/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation", false, ), ( "/System/Library/Frameworks/QuartzCore.framework/Versions/A/QuartzCore", true, ), ( "/System/Library/Frameworks/Metal.framework/Versions/A/Metal", true, ), ( "/System/Library/Frameworks/CoreGraphics.framework/Versions/A/CoreGraphics", true, ), ( "/System/Library/Frameworks/MetalPerformanceShaders.framework/Versions/A/MetalPerformanceShaders", true, ), ("/usr/lib/libiconv.2.dylib", false), ("/usr/lib/libSystem.B.dylib", false), ("/usr/lib/libobjc.A.dylib", false), ]; let otool = std::process::Command::new("otool") .arg("-L") .arg(util::deno_exe_path()) .output() .expect("Failed to execute otool"); let output = std::str::from_utf8(&otool.stdout).unwrap(); // Ensure that the output contains only the expected shared libraries. for line in output.lines().skip(1) { let (path, attributes) = line.trim().split_once(' ').unwrap(); assert!( EXPECTED.contains(&(path, attributes.ends_with("weak)"))), "Unexpected shared library: {}", path ); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/integration/cache_tests.rs
tests/integration/cache_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. use test_util::TestContext; use test_util::TestContextBuilder; use test_util::test; // This test only runs on linux, because it hardcodes the XDG_CACHE_HOME env var // which is only used on linux. #[cfg(target_os = "linux")] #[test] fn xdg_cache_home_dir() { let context = TestContext::with_http_server(); let deno_dir = context.temp_dir(); let xdg_cache_home = deno_dir.path().join("cache"); context .new_command() .env_remove("HOME") .env_remove("DENO_DIR") .env_clear() .env("XDG_CACHE_HOME", &xdg_cache_home) .args( "cache --allow-import --reload --no-check http://localhost:4548/subdir/redirects/a.ts", ) .run() .skip_output_check() .assert_exit_code(0); assert!(xdg_cache_home.read_dir().count() > 0); } // TODO(2.0): reenable #[ignore] #[test] fn cache_matching_package_json_dep_should_not_install_all() { let context = TestContextBuilder::for_npm().use_temp_cwd().build(); let temp_dir = context.temp_dir(); temp_dir.write( "package.json", r#"{ "dependencies": { "@types/node": "22.12.0", "@denotest/esm-basic": "*" } }"#, ); let output = context .new_command() .args("cache npm:@types/node@22.12.0") .run(); output.assert_matches_text(concat!( "Download http://localhost:4260/@types/node\n", "Download http://localhost:4260/@types/node/node-18.8.2.tgz\n", "Initialize @types/node@22.12.0\n", )); } // Regression test for https://github.com/denoland/deno/issues/17299 #[test] fn cache_put_overwrite() { let test_context = TestContextBuilder::new().use_temp_cwd().build(); let temp_dir = test_context.temp_dir(); let part_one = r#" const req = new Request('http://localhost/abc'); const res1 = new Response('res1'); const res2 = new Response('res2'); const cache = await caches.open('test'); await cache.put(req, res1); await cache.put(req, res2); const res = await cache.match(req).then((res) => res?.text()); console.log(res); "#; let part_two = r#" const req = new Request("http://localhost/abc"); const res1 = new Response("res1"); const res2 = new Response("res2"); const cache = await caches.open("test"); // Swap the order of put() calls. await cache.put(req, res2); await cache.put(req, res1); const res = await cache.match(req).then((res) => res?.text()); console.log(res); "#; temp_dir.write("cache_put.js", part_one); let run_command = test_context.new_command().args_vec(["run", "cache_put.js"]); let output = run_command.run(); output.assert_matches_text("res2\n"); output.assert_exit_code(0); // The wait will surface the bug as we check last written time // when we overwrite a response. std::thread::sleep(std::time::Duration::from_secs(1)); temp_dir.write("cache_put.js", part_two); let output = run_command.run(); output.assert_matches_text("res1\n"); output.assert_exit_code(0); } #[test] fn loads_type_graph() { let output = TestContext::default() .new_command() .args("cache --reload -L debug run/type_directives_js_main.js") .run(); output.assert_matches_text("[WILDCARD] - FileFetcher::fetch_no_follow - specifier: file:///[WILDCARD]/subdir/type_reference.d.ts[WILDCARD]"); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/integration/fmt_tests.rs
tests/integration/fmt_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. use serde_json::json; use test_util as util; use test_util::itest; use test_util::test; use util::PathRef; use util::TestContext; use util::TestContextBuilder; use util::assert_contains; use util::assert_not_contains; #[test] fn fmt_test() { let context = TestContext::default(); let t = context.deno_dir(); let testdata_fmt_dir = util::testdata_path().join("fmt"); let fixed_js = testdata_fmt_dir.join("badly_formatted_fixed.js"); let badly_formatted_original_js = testdata_fmt_dir.join("badly_formatted.mjs"); let badly_formatted_js = t.path().join("badly_formatted.js"); badly_formatted_original_js.copy(&badly_formatted_js); let fixed_md = testdata_fmt_dir.join("badly_formatted_fixed.md"); let badly_formatted_original_md = testdata_fmt_dir.join("badly_formatted.md"); let badly_formatted_md = t.path().join("badly_formatted.md"); badly_formatted_original_md.copy(&badly_formatted_md); let fixed_json = testdata_fmt_dir.join("badly_formatted_fixed.json"); let badly_formatted_original_json = testdata_fmt_dir.join("badly_formatted.json"); let badly_formatted_json = t.path().join("badly_formatted.json"); badly_formatted_original_json.copy(&badly_formatted_json); let fixed_css = testdata_fmt_dir.join("badly_formatted_fixed.css"); let badly_formatted_original_css = testdata_fmt_dir.join("badly_formatted.css"); let badly_formatted_css = t.path().join("badly_formatted.css"); badly_formatted_original_css.copy(&badly_formatted_css); let fixed_html = testdata_fmt_dir.join("badly_formatted_fixed.html"); let badly_formatted_original_html = testdata_fmt_dir.join("badly_formatted.html"); let badly_formatted_html = t.path().join("badly_formatted.html"); badly_formatted_original_html.copy(&badly_formatted_html); let fixed_component = testdata_fmt_dir.join("badly_formatted_fixed.svelte"); let badly_formatted_original_component = testdata_fmt_dir.join("badly_formatted.svelte"); let badly_formatted_component = t.path().join("badly_formatted.svelte"); badly_formatted_original_component.copy(&badly_formatted_component); let fixed_ipynb = testdata_fmt_dir.join("badly_formatted_fixed.ipynb"); let badly_formatted_original_ipynb = testdata_fmt_dir.join("badly_formatted.ipynb"); let badly_formatted_ipynb = t.path().join("badly_formatted.ipynb"); badly_formatted_original_ipynb.copy(&badly_formatted_ipynb); let fixed_yaml = testdata_fmt_dir.join("badly_formatted_fixed.yaml"); let badly_formatted_original_yaml = testdata_fmt_dir.join("badly_formatted.yaml"); let badly_formatted_yaml = t.path().join("badly_formatted.yaml"); badly_formatted_original_yaml.copy(&badly_formatted_yaml); let fixed_sql = testdata_fmt_dir.join("badly_formatted_fixed.sql"); let badly_formatted_original_sql = testdata_fmt_dir.join("badly_formatted.sql"); let badly_formatted_sql = t.path().join("badly_formatted.sql"); badly_formatted_original_sql.copy(&badly_formatted_sql); // First, check formatting by ignoring the badly formatted file. let output = context .new_command() .current_dir(&testdata_fmt_dir) .args_vec(vec![ "fmt".to_string(), "--unstable-css".to_string(), "--unstable-html".to_string(), "--unstable-component".to_string(), "--unstable-yaml".to_string(), "--unstable-sql".to_string(), format!( "--ignore={badly_formatted_js},{badly_formatted_md},{badly_formatted_json},{badly_formatted_css},{badly_formatted_html},{badly_formatted_component},{badly_formatted_yaml},{badly_formatted_ipynb},{badly_formatted_sql}", ), format!( "--check {badly_formatted_js} {badly_formatted_md} {badly_formatted_json} {badly_formatted_css} {badly_formatted_html} {badly_formatted_component} {badly_formatted_yaml} {badly_formatted_ipynb} {badly_formatted_sql}", ), ]) .run(); // No target files found output.assert_exit_code(1); output.skip_output_check(); // Check without ignore. let output = context .new_command() .current_dir(&testdata_fmt_dir) .args_vec(vec![ "fmt".to_string(), "--check".to_string(), "--unstable-css".to_string(), "--unstable-html".to_string(), "--unstable-component".to_string(), "--unstable-yaml".to_string(), "--unstable-sql".to_string(), badly_formatted_js.to_string(), badly_formatted_md.to_string(), badly_formatted_json.to_string(), badly_formatted_css.to_string(), badly_formatted_html.to_string(), badly_formatted_component.to_string(), badly_formatted_yaml.to_string(), badly_formatted_ipynb.to_string(), badly_formatted_sql.to_string(), ]) .run(); output.assert_exit_code(1); output.skip_output_check(); // Format the source file. let output = context .new_command() .current_dir(&testdata_fmt_dir) .args_vec(vec![ "fmt".to_string(), "--unstable-css".to_string(), "--unstable-html".to_string(), "--unstable-component".to_string(), "--unstable-yaml".to_string(), "--unstable-sql".to_string(), badly_formatted_js.to_string(), badly_formatted_md.to_string(), badly_formatted_json.to_string(), badly_formatted_css.to_string(), badly_formatted_html.to_string(), badly_formatted_component.to_string(), badly_formatted_yaml.to_string(), badly_formatted_ipynb.to_string(), badly_formatted_sql.to_string(), ]) .run(); output.assert_exit_code(0); output.skip_output_check(); let expected_js = fixed_js.read_to_string(); let expected_md = fixed_md.read_to_string(); let expected_json = fixed_json.read_to_string(); let expected_css = fixed_css.read_to_string(); let expected_html = fixed_html.read_to_string(); let expected_component = fixed_component.read_to_string(); let expected_yaml = fixed_yaml.read_to_string(); let expected_ipynb = fixed_ipynb.read_to_string(); let expected_sql = fixed_sql.read_to_string(); let actual_js = badly_formatted_js.read_to_string(); let actual_md = badly_formatted_md.read_to_string(); let actual_json = badly_formatted_json.read_to_string(); let actual_css = badly_formatted_css.read_to_string(); let actual_html = badly_formatted_html.read_to_string(); let actual_component = badly_formatted_component.read_to_string(); let actual_yaml = badly_formatted_yaml.read_to_string(); let actual_ipynb = badly_formatted_ipynb.read_to_string(); let actual_sql = badly_formatted_sql.read_to_string(); assert_eq!(expected_js, actual_js); assert_eq!(expected_md, actual_md); assert_eq!(expected_json, actual_json); assert_eq!(expected_css, actual_css); assert_eq!(expected_html, actual_html); assert_eq!(expected_component, actual_component); assert_eq!(expected_yaml, actual_yaml); assert_eq!(expected_ipynb, actual_ipynb); assert_eq!(expected_sql, actual_sql); } #[test] fn fmt_stdin_syntax_error() { let output = util::deno_cmd() .current_dir(util::testdata_path()) .arg("fmt") .arg("-") .stdin_text("import { example }") .split_output() .run(); assert!(output.stdout().is_empty()); assert!(!output.stderr().is_empty()); output.assert_exit_code(1); } #[test] fn fmt_auto_ignore_git_and_node_modules() { fn create_bad_json(t: PathRef) { let bad_json_path = t.join("bad.json"); bad_json_path.write("bad json\n"); } let context = TestContext::default(); let temp_dir = context.temp_dir(); let t = temp_dir.path().join("target"); let nest_git = t.join("nest").join(".git"); let git_dir = t.join(".git"); let nest_node_modules = t.join("nest").join("node_modules"); let node_modules_dir = t.join("node_modules"); nest_git.create_dir_all(); git_dir.create_dir_all(); nest_node_modules.create_dir_all(); node_modules_dir.create_dir_all(); create_bad_json(nest_git); create_bad_json(git_dir); create_bad_json(nest_node_modules); create_bad_json(node_modules_dir); let output = context .new_command() .current_dir(t) .env("NO_COLOR", "1") .args("fmt .") .run(); output.assert_exit_code(1); assert_eq!(output.combined_output(), "error: No target files found.\n"); } itest!(fmt_quiet_check_fmt_dir { args: "fmt --check --quiet fmt/regular/", output_str: Some(""), exit_code: 0, }); itest!(fmt_check_formatted_files { args: "fmt --check fmt/regular/formatted1.js fmt/regular/formatted2.ts fmt/regular/formatted3.markdown fmt/regular/formatted4.jsonc", output: "fmt/expected_fmt_check_formatted_files.out", exit_code: 0, }); itest!(fmt_check_ignore { args: "fmt --check --ignore=fmt/regular/formatted1.js fmt/regular/", output: "fmt/expected_fmt_check_ignore.out", exit_code: 0, }); itest!(fmt_stdin { args: "fmt -", input: Some("const a = 1\n"), output_str: Some("const a = 1;\n"), }); itest!(fmt_stdin_markdown { args: "fmt --ext=md -", input: Some( "# Hello Markdown\n```ts\nconsole.log( \"text\")\n```\n\n```cts\nconsole.log( 5 )\n```" ), output_str: Some( "# Hello Markdown\n\n```ts\nconsole.log(\"text\");\n```\n\n```cts\nconsole.log(5);\n```\n" ), }); itest!(fmt_stdin_json { args: "fmt --ext=json -", input: Some("{ \"key\": \"value\"}"), output_str: Some("{ \"key\": \"value\" }\n"), }); itest!(fmt_stdin_ipynb { args: "fmt --ext=ipynb -", input: Some(include_str!("../testdata/fmt/badly_formatted.ipynb")), output_str: Some(include_str!("../testdata/fmt/badly_formatted_fixed.ipynb")), }); itest!(fmt_stdin_check_formatted { args: "fmt --check -", input: Some("const a = 1;\n"), output_str: Some(""), }); itest!(fmt_stdin_check_not_formatted { args: "fmt --check -", input: Some("const a = 1\n"), output_str: Some("Not formatted stdin\n"), }); itest!(fmt_with_config { args: "fmt --config fmt/with_config/deno.jsonc fmt/with_config/subdir", output: "fmt/fmt_with_config.out", }); itest!(fmt_with_config_default { args: "fmt fmt/with_config/subdir", output: "fmt/fmt_with_config.out", }); // Check if CLI flags take precedence itest!(fmt_with_config_and_flags { args: "fmt --config fmt/with_config/deno.jsonc --ignore=fmt/with_config/subdir/a.ts,fmt/with_config/subdir/b.ts", output: "fmt/fmt_with_config_and_flags.out", }); itest!(fmt_with_malformed_config { args: "fmt --config fmt/deno.malformed.jsonc", output: "fmt/fmt_with_malformed_config.out", exit_code: 1, }); itest!(fmt_with_malformed_config2 { args: "fmt --config fmt/deno.malformed2.jsonc", output: "fmt/fmt_with_malformed_config2.out", exit_code: 1, }); #[test] fn fmt_with_glob_config() { let context = TestContextBuilder::new().cwd("fmt").build(); let cmd_output = context .new_command() .args("fmt --check --config deno.glob.json") .run(); cmd_output.assert_exit_code(1); let output = cmd_output.combined_output(); if cfg!(windows) { assert_contains!(output, r"glob\nested\fizz\fizz.ts"); assert_contains!(output, r"glob\pages\[id].ts"); assert_contains!(output, r"glob\nested\fizz\bar.ts"); assert_contains!(output, r"glob\nested\foo\foo.ts"); assert_contains!(output, r"glob\data\test1.js"); assert_contains!(output, r"glob\nested\foo\bar.ts"); assert_contains!(output, r"glob\nested\foo\fizz.ts"); assert_contains!(output, r"glob\nested\fizz\foo.ts"); assert_contains!(output, r"glob\data\test1.ts"); } else { assert_contains!(output, "glob/nested/fizz/fizz.ts"); assert_contains!(output, "glob/pages/[id].ts"); assert_contains!(output, "glob/nested/fizz/bar.ts"); assert_contains!(output, "glob/nested/foo/foo.ts"); assert_contains!(output, "glob/data/test1.js"); assert_contains!(output, "glob/nested/foo/bar.ts"); assert_contains!(output, "glob/nested/foo/fizz.ts"); assert_contains!(output, "glob/nested/fizz/foo.ts"); assert_contains!(output, "glob/data/test1.ts"); } assert_contains!(output, "Found 9 not formatted files in 9 files"); } #[test] fn fmt_with_glob_config_and_flags() { let context = TestContextBuilder::new().cwd("fmt").build(); let cmd_output = context .new_command() .args("fmt --check --config deno.glob.json --ignore=glob/nested/**/bar.ts") .run(); cmd_output.assert_exit_code(1); let output = cmd_output.combined_output(); if cfg!(windows) { assert_contains!(output, r"glob\nested\fizz\fizz.ts"); assert_contains!(output, r"glob\pages\[id].ts"); assert_contains!(output, r"glob\nested\fizz\bazz.ts"); assert_contains!(output, r"glob\nested\foo\foo.ts"); assert_contains!(output, r"glob\data\test1.js"); assert_contains!(output, r"glob\nested\foo\bazz.ts"); assert_contains!(output, r"glob\nested\foo\fizz.ts"); assert_contains!(output, r"glob\nested\fizz\foo.ts"); assert_contains!(output, r"glob\data\test1.ts"); } else { assert_contains!(output, "glob/nested/fizz/fizz.ts"); assert_contains!(output, "glob/pages/[id].ts"); assert_contains!(output, "glob/nested/fizz/bazz.ts"); assert_contains!(output, "glob/nested/foo/foo.ts"); assert_contains!(output, "glob/data/test1.js"); assert_contains!(output, "glob/nested/foo/bazz.ts"); assert_contains!(output, "glob/nested/foo/fizz.ts"); assert_contains!(output, "glob/nested/fizz/foo.ts"); assert_contains!(output, "glob/data/test1.ts"); } assert_contains!(output, "Found 9 not formatted files in 9 files"); let cmd_output = context .new_command() .args("fmt --check --config deno.glob.json glob/data/test1.?s") .run(); cmd_output.assert_exit_code(1); let output = cmd_output.combined_output(); if cfg!(windows) { assert_contains!(output, r"glob\data\test1.js"); assert_contains!(output, r"glob\data\test1.ts"); } else { assert_contains!(output, "glob/data/test1.js"); assert_contains!(output, "glob/data/test1.ts"); } assert_contains!(output, "Found 2 not formatted files in 2 files"); } #[test] fn opt_out_top_level_exclude_via_fmt_unexclude() { let context = TestContextBuilder::new().use_temp_cwd().build(); let temp_dir = context.temp_dir().path(); temp_dir.join("deno.json").write_json(&json!({ "fmt": { "exclude": [ "!excluded.ts" ] }, "exclude": [ "excluded.ts", "actually_excluded.ts" ] })); temp_dir.join("main.ts").write("const a = 1;"); temp_dir.join("excluded.ts").write("const a = 2;"); temp_dir .join("actually_excluded.ts") .write("const a = 2;"); let output = context.new_command().arg("fmt").run(); output.assert_exit_code(0); let output = output.combined_output(); assert_contains!(output, "main.ts"); assert_contains!(output, "excluded.ts"); assert_not_contains!(output, "actually_excluded.ts"); } #[test(flaky)] fn test_tty_non_workspace_directory() { let context = TestContextBuilder::new().use_temp_cwd().build(); let temp_dir = context.temp_dir().path(); temp_dir.join("main.ts").write("const a = 1;\n"); context.new_command().arg("fmt").with_pty(|mut pty| { pty.expect("Are you sure you want to format the entire"); pty.write_raw("y\r\n"); pty.expect("Checked 1 file"); }); context.new_command().arg("fmt").with_pty(|mut pty| { pty.expect("Are you sure you want to format"); pty.write_raw("n\r\n"); pty.expect("Did not format non-workspace directory"); }); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/integration/init_tests.rs
tests/integration/init_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. use test_util as util; use test_util::test; use util::TestContextBuilder; use util::assert_contains; #[test] fn init_subcommand_without_dir() { let context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let cwd = context.temp_dir().path(); let output = context.new_command().args("init").split_output().run(); output.assert_exit_code(0); let stderr = output.stderr(); assert_contains!(stderr, "Project initialized"); assert!(!stderr.contains("cd")); assert_contains!(stderr, "deno run main.ts"); assert_contains!(stderr, "deno task dev"); assert_contains!(stderr, "deno test"); assert!(cwd.join("deno.json").exists()); let output = context .new_command() .env("NO_COLOR", "1") .args("run main.ts") .split_output() .run(); output.assert_exit_code(0); assert_eq!(output.stdout().as_bytes(), b"Add 2 + 3 = 5\n"); let output = context .new_command() .env("NO_COLOR", "1") .args("test") .split_output() .run(); output.assert_exit_code(0); assert_contains!(output.stdout(), "1 passed"); output.skip_output_check(); } #[test] fn init_subcommand_with_dir_arg() { let context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let cwd = context.temp_dir().path(); let output = context .new_command() .args("init my_dir") .split_output() .run(); output.assert_exit_code(0); let stderr = output.stderr(); assert_contains!(stderr, "Project initialized"); assert_contains!(stderr, "cd my_dir"); assert_contains!(stderr, "deno run main.ts"); assert_contains!(stderr, "deno task dev"); assert_contains!(stderr, "deno test"); assert!(cwd.join("my_dir/deno.json").exists()); let output = context .new_command() .env("NO_COLOR", "1") .args("run my_dir/main.ts") .split_output() .run(); output.assert_exit_code(0); assert_eq!(output.stdout().as_bytes(), b"Add 2 + 3 = 5\n"); output.skip_output_check(); let output = context .new_command() .env("NO_COLOR", "1") .current_dir("my_dir") .args("test main_test.ts") .split_output() .run(); output.assert_exit_code(0); assert_contains!(output.stdout(), "1 passed"); output.skip_output_check(); } #[test] fn init_subcommand_with_quiet_arg() { let context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let cwd = context.temp_dir().path(); let output = context .new_command() .args("init --quiet") .split_output() .run(); output.assert_exit_code(0); assert_eq!(output.stdout(), ""); assert!(cwd.join("deno.json").exists()); let output = context .new_command() .env("NO_COLOR", "1") .args("run main.ts") .split_output() .run(); output.assert_exit_code(0); assert_eq!(output.stdout().as_bytes(), b"Add 2 + 3 = 5\n"); output.skip_output_check(); let output = context .new_command() .env("NO_COLOR", "1") .args("test") .split_output() .run(); output.assert_exit_code(0); assert_contains!(output.stdout(), "1 passed"); output.skip_output_check(); } #[test] fn init_subcommand_with_existing_file() { let context = TestContextBuilder::new().use_temp_cwd().build(); let cwd = context.temp_dir().path(); cwd .join("main.ts") .write("console.log('Log from main.ts that already exists');"); let output = context.new_command().args("init").split_output().run(); output.assert_exit_code(0); output.assert_stderr_matches_text( "ℹ️ Skipped creating main.ts as it already exists βœ… Project initialized Run these commands to get started # Run the program deno run main.ts # Run the program and watch for file changes deno task dev # Run the tests deno test ", ); assert!(cwd.join("deno.json").exists()); let output = context .new_command() .env("NO_COLOR", "1") .args("run main.ts") .run(); output.assert_exit_code(0); output.assert_matches_text("Log from main.ts that already exists\n"); } #[test] fn init_subcommand_empty() { let context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let cwd = context.temp_dir().path(); let output = context .new_command() .args("init --empty") .split_output() .run(); output.assert_exit_code(0); let stderr = output.stderr(); assert_contains!(stderr, "Project initialized"); assert!(!stderr.contains("cd")); assert_contains!(stderr, "deno run main.ts"); assert_contains!(stderr, "deno task dev"); assert!(!stderr.contains("deno test")); let deno_json_path = cwd.join("deno.json"); assert!(deno_json_path.exists()); let deno_json_content = deno_json_path.read_to_string(); assert!(!deno_json_content.contains("@std/assert")); assert!(cwd.join("main.ts").exists()); assert!(!cwd.join("main_test.ts").exists()); let main_content = cwd.join("main.ts").read_to_string(); assert_eq!(main_content, "console.log('Hello world!');\n"); let output = context .new_command() .env("NO_COLOR", "1") .args("run main.ts") .split_output() .run(); output.assert_exit_code(0); assert_eq!(output.stdout().as_bytes(), b"Hello world!\n"); output.skip_output_check(); } #[tokio::test] #[cfg(not(all(target_os = "macos", target_arch = "x86_64")))] async fn init_subcommand_serve() { let context = TestContextBuilder::for_jsr().use_temp_cwd().build(); let cwd = context.temp_dir().path(); let output = context .new_command() .args("init --serve") .split_output() .run(); output.assert_exit_code(0); let stderr = output.stderr(); assert_contains!(stderr, "Project initialized"); assert_contains!(stderr, "deno serve -R main.ts"); assert_contains!(stderr, "deno task dev"); assert_contains!(stderr, "deno test -R"); assert!(cwd.join("deno.json").exists()); let mut child = context .new_command() .env("NO_COLOR", "1") .args("serve -R --port 9500 main.ts") .spawn_with_piped_output(); tokio::time::sleep(std::time::Duration::from_millis(1000)).await; let resp = match reqwest::get("http://127.0.0.1:9500").await { Ok(resp) => resp, Err(_) => { // retry once tokio::time::sleep(std::time::Duration::from_millis(1000)).await; reqwest::get("http://127.0.0.1:9500").await.unwrap() } }; let body = resp.text().await.unwrap(); assert_eq!(body, "Home page"); let _ = child.kill(); let output = context .new_command() .env("NO_COLOR", "1") .args("test -R") .split_output() .run(); output.assert_exit_code(0); assert_contains!(output.stdout(), "4 passed"); output.skip_output_check(); } #[test(flaky)] fn init_npm() { let context = TestContextBuilder::for_npm().use_temp_cwd().build(); let cwd = context.temp_dir().path(); context .new_command() .args("init --npm @denotest") .with_pty(|mut pty| { pty.expect("Do you want to continue?"); pty.write_raw("y\n"); pty.expect("Initialized!"); assert_eq!(cwd.join("3").read_to_string(), "test"); }); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/integration/install_tests.rs
tests/integration/install_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. use test_util as util; use util::TestContext; use util::TestContextBuilder; use util::assert_contains; use util::assert_not_contains; use util::test; #[test] fn install_basic() { let context = TestContextBuilder::new() .use_http_server() .use_temp_cwd() .build(); let temp_dir = context.temp_dir(); let temp_dir_str = temp_dir.path().to_string(); // ensure a lockfile doesn't get created or updated locally temp_dir.write("deno.json", "{}"); let output = context .new_command() .args("install --check --name echo_test -g http://localhost:4545/echo.ts") .envs([ ("HOME", temp_dir_str.as_str()), ("USERPROFILE", temp_dir_str.as_str()), ("DENO_INSTALL_ROOT", ""), ]) .run(); output.assert_exit_code(0); let output_text = output.combined_output(); assert_contains!(output_text, "βœ… Successfully installed echo_test"); // no lockfile should be created locally assert!(!temp_dir.path().join("deno.lock").exists()); let mut file_path = temp_dir.path().join(".deno/bin/echo_test"); assert!(file_path.exists()); if cfg!(windows) { file_path = file_path.with_extension("cmd"); } let content = file_path.read_to_string(); // ensure there's a trailing newline so the shell script can be // more versatile. assert_eq!(content.chars().last().unwrap(), '\n'); if cfg!(windows) { assert_contains!( content, r#""run" "--check" "--no-config" "http://localhost:4545/echo.ts""# ); } else { assert_contains!( content, r#"run --check --no-config 'http://localhost:4545/echo.ts'"# ); } // now uninstall context .new_command() .args("uninstall -g echo_test") .envs([ ("HOME", temp_dir_str.as_str()), ("USERPROFILE", temp_dir_str.as_str()), ("DENO_INSTALL_ROOT", ""), ]) .run() .skip_output_check() .assert_exit_code(0); // ensure local lockfile still doesn't exist assert!(!temp_dir.path().join("deno.lock").exists()); // ensure uninstall occurred assert!(!file_path.exists()); } #[test] fn install_basic_global() { let context = TestContextBuilder::new() .use_http_server() .use_temp_cwd() .build(); let temp_dir = context.temp_dir(); let temp_dir_str = temp_dir.path().to_string(); // ensure a lockfile doesn't get created or updated locally temp_dir.write("deno.json", "{}"); let output = context .new_command() .args( "install --global --check --name echo_test http://localhost:4545/echo.ts", ) .envs([ ("HOME", temp_dir_str.as_str()), ("USERPROFILE", temp_dir_str.as_str()), ("DENO_INSTALL_ROOT", ""), ]) .run(); output.assert_exit_code(0); let output_text = output.combined_output(); assert_not_contains!( output_text, "`deno install` behavior will change in Deno 2. To preserve the current behavior use the `-g` or `--global` flag." ); // no lockfile should be created locally assert!(!temp_dir.path().join("deno.lock").exists()); let mut file_path = temp_dir.path().join(".deno/bin/echo_test"); assert!(file_path.exists()); if cfg!(windows) { file_path = file_path.with_extension("cmd"); } let content = file_path.read_to_string(); // ensure there's a trailing newline so the shell script can be // more versatile. assert_eq!(content.chars().last().unwrap(), '\n'); if cfg!(windows) { assert_contains!( content, r#""run" "--check" "--no-config" "http://localhost:4545/echo.ts""# ); } else { assert_contains!( content, r#"run --check --no-config 'http://localhost:4545/echo.ts'"# ); } // now uninstall context .new_command() .args("uninstall -g echo_test") .envs([ ("HOME", temp_dir_str.as_str()), ("USERPROFILE", temp_dir_str.as_str()), ("DENO_INSTALL_ROOT", ""), ]) .run() .skip_output_check() .assert_exit_code(0); // ensure local lockfile still doesn't exist assert!(!temp_dir.path().join("deno.lock").exists()); // ensure uninstall occurred assert!(!file_path.exists()); } #[test] fn install_custom_dir_env_var() { let context = TestContext::with_http_server(); let temp_dir = context.temp_dir(); let temp_dir_str = temp_dir.path().to_string(); context .new_command() .current_dir(util::root_path()) // different cwd .args("install --check --name echo_test -g http://localhost:4545/echo.ts") .envs([ ("HOME", temp_dir_str.as_str()), ("USERPROFILE", temp_dir_str.as_str()), ("DENO_INSTALL_ROOT", temp_dir_str.as_str()), ]) .run() .skip_output_check() .assert_exit_code(0); let mut file_path = temp_dir.path().join("bin/echo_test"); assert!(file_path.exists()); if cfg!(windows) { file_path = file_path.with_extension("cmd"); } let content = file_path.read_to_string(); if cfg!(windows) { assert_contains!( content, r#""run" "--check" "--no-config" "http://localhost:4545/echo.ts""# ); } else { assert_contains!( content, r#"run --check --no-config 'http://localhost:4545/echo.ts'"# ); } } #[test] fn installer_test_custom_dir_with_bin() { let context = TestContext::with_http_server(); let temp_dir = context.temp_dir(); let temp_dir_str = temp_dir.path().to_string(); let temp_dir_with_bin = temp_dir.path().join("bin").to_string(); context .new_command() .current_dir(util::root_path()) // different cwd .args("install --check --name echo_test -g http://localhost:4545/echo.ts") .envs([ ("HOME", temp_dir_str.as_str()), ("USERPROFILE", temp_dir_str.as_str()), ("DENO_INSTALL_ROOT", temp_dir_with_bin.as_str()), ]) .run() .skip_output_check() .assert_exit_code(0); let mut file_path = temp_dir.path().join("bin/echo_test"); assert!(file_path.exists()); if cfg!(windows) { file_path = file_path.with_extension("cmd"); } let content = file_path.read_to_string(); if cfg!(windows) { assert_contains!( content, r#""run" "--check" "--no-config" "http://localhost:4545/echo.ts""# ); } else { assert_contains!( content, r#"run --check --no-config 'http://localhost:4545/echo.ts'"# ); } } #[test] fn installer_test_local_module_run() { let context = TestContext::with_http_server(); let temp_dir = context.temp_dir(); let temp_dir_str = temp_dir.path().to_string(); let echo_ts_str = util::testdata_path().join("echo.ts").to_string(); context .new_command() .current_dir(util::root_path()) .args_vec([ "install", "-g", "--name", "echo_test", "--root", temp_dir_str.as_str(), echo_ts_str.as_str(), "--", "hello", ]) .envs([ ("HOME", temp_dir_str.as_str()), ("USERPROFILE", temp_dir_str.as_str()), ("DENO_INSTALL_ROOT", ""), ]) .run() .skip_output_check() .assert_exit_code(0); let bin_dir = temp_dir.path().join("bin"); let mut file_path = bin_dir.join("echo_test"); if cfg!(windows) { file_path = file_path.with_extension("cmd"); } assert!(file_path.exists()); let output = context .new_command() .name(&file_path) .current_dir(temp_dir.path()) .args("foo") .env("PATH", util::target_dir()) .run(); output.assert_matches_text("hello, foo"); output.assert_exit_code(0); } #[test] fn installer_test_remote_module_run() { let context = TestContextBuilder::new() .use_http_server() .use_temp_cwd() .build(); let temp_dir = context.temp_dir(); let root_dir = temp_dir.path().join("root"); let bin_dir = root_dir.join("bin"); context .new_command() .args("install --name echo_test --root ./root -g http://localhost:4545/echo.ts -- hello") .run() .skip_output_check() .assert_exit_code(0); let mut bin_file_path = bin_dir.join("echo_test"); if cfg!(windows) { bin_file_path = bin_file_path.with_extension("cmd"); } assert!(bin_file_path.exists()); let output = context .new_command() .name(&bin_file_path) .current_dir(root_dir) .args("foo") .env("PATH", util::target_dir()) .run(); output.assert_matches_text("hello, foo"); output.assert_exit_code(0); // now uninstall with the relative path context .new_command() .args("uninstall -g --root ./root echo_test") .run() .skip_output_check() .assert_exit_code(0); assert!(!bin_file_path.exists()); } #[test] fn check_local_by_default() { let context = TestContextBuilder::new() .use_http_server() .use_temp_cwd() .build(); let temp_dir = context.temp_dir(); let temp_dir_str = temp_dir.path().to_string(); let script_path = util::testdata_path().join("./install/check_local_by_default.ts"); let script_path_str = script_path.to_string_lossy().into_owned(); context .new_command() .args_vec(["install", "-g", "--allow-import", script_path_str.as_str()]) .envs([ ("HOME", temp_dir_str.as_str()), ("USERPROFILE", temp_dir_str.as_str()), ("DENO_INSTALL_ROOT", ""), ]) .run() .skip_output_check() .assert_exit_code(0); } #[test] fn check_local_by_default2() { let context = TestContextBuilder::new() .use_http_server() .use_temp_cwd() .build(); let temp_dir = context.temp_dir(); let temp_dir_str = temp_dir.path().to_string(); let script_path = util::testdata_path().join("./install/check_local_by_default2.ts"); let script_path_str = script_path.to_string_lossy().into_owned(); context .new_command() .args_vec(["install", "-g", "--allow-import", script_path_str.as_str()]) .envs([ ("HOME", temp_dir_str.as_str()), ("NO_COLOR", "1"), ("USERPROFILE", temp_dir_str.as_str()), ("DENO_INSTALL_ROOT", ""), ]) .run() .skip_output_check() .assert_exit_code(0); } #[test] fn show_prefix_hint_on_global_install() { let context = TestContextBuilder::new() .add_npm_env_vars() .add_jsr_env_vars() .use_http_server() .use_temp_cwd() .build(); let temp_dir = context.temp_dir(); let temp_dir_str = temp_dir.path().to_string(); let env_vars = [ ("HOME", temp_dir_str.as_str()), ("USERPROFILE", temp_dir_str.as_str()), ("DENO_INSTALL_ROOT", ""), ]; for pkg_req in ["npm:@denotest/bin", "jsr:@denotest/add"] { let name = pkg_req.split_once('/').unwrap().1; let pkg = pkg_req.split_once(':').unwrap().1; // try with prefix and ensure that the installation succeeds context .new_command() .args_vec(["install", "-g", "--name", name, pkg_req]) .envs(env_vars) .run() .skip_output_check() .assert_exit_code(0); // try without the prefix and ensure that the installation fails with the appropriate error // message let output = context .new_command() .args_vec(["install", "-g", "--name", name, pkg]) .envs(env_vars) .run(); output.assert_exit_code(1); let output_text = output.combined_output(); let expected_text = format!( "error: {pkg} is missing a prefix. Did you mean `deno install -g {pkg_req}`?" ); assert_contains!(output_text, &expected_text); } // try a pckage not in npm and jsr to make sure the appropriate error message still appears let output = context .new_command() .args_vec(["install", "-g", "package-that-does-not-exist"]) .envs(env_vars) .run(); output.assert_exit_code(1); let output_text = output.combined_output(); assert_contains!(output_text, "error: Module not found"); } #[test] fn installer_multiple() { let context = TestContextBuilder::new() .use_http_server() .use_temp_cwd() .build(); let temp_dir = context.temp_dir(); let root_dir = temp_dir.path().join("root"); let bin_dir = root_dir.join("bin"); context .new_command() .args("install --root ./root -g http://localhost:4545/echo.ts http://localhost:4545/cat.ts") .run() .assert_matches_text("[WILDCARD]Successfully installed echo[WILDCARD]Successfully installed cat[WILDCARD]") .assert_exit_code(0); for name in ["echo", "cat"] { let mut bin_file_path = bin_dir.join(name); if cfg!(windows) { bin_file_path = bin_file_path.with_extension("cmd"); } assert!(bin_file_path.exists()); } } #[test] fn installer_second_module_looks_like_script_argument() { let context = TestContextBuilder::new() .use_http_server() .use_temp_cwd() .build(); // in Deno < 3.0, we didn't require `--` before script arguments, so we try to provide a helpful // error message for people migrating context .new_command() .args("install --root ./root -g http://localhost:4545/echo.ts non_existent") .run() .assert_matches_text(concat!( "[WILDCARD]Successfully installed echo[WILDCARD]error: non_existent is missing a prefix. ", "Deno 3.0 requires `--` before script arguments in `deno install -g`. ", "Did you mean `deno install -g http://localhost:4545/echo.ts -- non_existent`? ", "Or maybe provide a `jsr:` or `npm:` prefix?\n" )) .assert_exit_code(1); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/integration/bench_tests.rs
tests/integration/bench_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. use serde_json::json; use test_util as util; use util::TestContext; use util::TestContextBuilder; use util::assert_contains; use util::assert_not_contains; use util::test; #[test] fn recursive_permissions_pledge() { let context = TestContext::default(); let output = context .new_command() .args("bench bench/recursive_permissions_pledge.js") .run(); output.assert_exit_code(1); assert_contains!( output.combined_output(), "pledge test permissions called before restoring previous pledge" ); } #[test] fn conditionally_loads_type_graph() { let context = TestContext::default(); let output = context .new_command() .args("bench --reload -L debug run/type_directives_js_main.js") .run(); output.assert_matches_text("[WILDCARD] - FileFetcher::fetch_no_follow - specifier: file:///[WILDCARD]/subdir/type_reference.d.ts[WILDCARD]"); let output = context .new_command() .args("bench --reload -L debug --no-check run/type_directives_js_main.js") .run(); assert_not_contains!(output.combined_output(), "type_reference.d.ts"); } #[test] fn opt_out_top_level_exclude_via_bench_unexclude() { let context = TestContextBuilder::new().use_temp_cwd().build(); let temp_dir = context.temp_dir().path(); temp_dir.join("deno.json").write_json(&json!({ "bench": { "exclude": [ "!excluded.bench.ts" ] }, "exclude": [ "excluded.bench.ts", "actually_excluded.bench.ts" ] })); temp_dir .join("main.bench.ts") .write("Deno.bench('test1', () => {});"); temp_dir .join("excluded.bench.ts") .write("Deno.bench('test2', () => {});"); temp_dir .join("actually_excluded.bench.ts") .write("Deno.bench('test3', () => {});"); let output = context.new_command().arg("bench").run(); output.assert_exit_code(0); let output = output.combined_output(); assert_contains!(output, "main.bench.ts"); assert_contains!(output, "excluded.bench.ts"); assert_not_contains!(output, "actually_excluded.bench.ts"); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/integration/task_tests.rs
tests/integration/task_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. // Most of the tests for this are in deno_task_shell. // These tests are intended to only test integration. use test_util as util; use util::TestContextBuilder; use util::test; // use test_util::env_vars_for_npm_tests; // use test_util::TestContext; // TODO(2.0): this should first run `deno install` // itest!(task_package_json_npm_bin { // args: "task bin extra", // cwd: Some("task/package_json/"), // output: "task/package_json/bin.out", // copy_temp_dir: Some("task/package_json/"), // envs: env_vars_for_npm_tests(), // exit_code: 0, // http_server: true, // }); // TODO(2.0): not entirely clear what's wrong with this test but it hangs for more than 60s // itest!(task_npx_on_own { // args: "task on-own", // cwd: Some("task/npx/"), // output: "task/npx/on_own.out", // copy_temp_dir: Some("task/npx/"), // envs: env_vars_for_npm_tests(), // exit_code: 1, // http_server: true, // }); #[test(flaky)] fn deno_task_ansi_escape_codes() { let context = TestContextBuilder::default().use_temp_cwd().build(); let temp_dir = context.temp_dir(); temp_dir.write("deno.json", r#"{ "tasks": { "dev": "echo 'BOOO!!!'", "next": "\u001b[3F\u001b[0G- dev\u001b[1E\u001b[2K echo 'I am your friend.'" } } "#); context .new_command() .args_vec(["task"]) .with_pty(|mut console| { console.expect("Available tasks:"); console.expect("- dev"); console.expect(" echo 'BOOO!!!'"); console.expect("- next"); console.expect(" - dev echo 'I am your friend.'"); }); } #[test(flaky)] fn deno_task_control_chars() { let context = TestContextBuilder::default().use_temp_cwd().build(); let temp_dir = context.temp_dir(); temp_dir.write( "deno.json", r#"{ "tasks": { "dev": "echo 'BOOO!!!' && \r echo hi there is my command", "serve": { "description": "this is a\tm\rangled description", "command": "echo hello" } } } "#, ); context .new_command() .args_vec(["task"]) .with_pty(|mut console| { console.expect("Available tasks:"); console.expect("- dev"); console .expect(" echo 'BOOO!!!' && \\r echo hi there is my command"); console.expect("- serve"); console.expect(" // this is a\\tm\\rangled description"); console.expect(" echo hello"); }); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/unit_node/mod.rs
tests/unit_node/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::num::NonZeroUsize; use std::sync::Arc; use file_test_runner::RunOptions; use file_test_runner::TestResult; use file_test_runner::collection::CollectOptions; use file_test_runner::collection::CollectedTest; use file_test_runner::collection::collect_tests_or_exit; use file_test_runner::collection::strategies::TestPerFileCollectionStrategy; use test_util as util; use test_util::test_runner::FlakyTestTracker; use test_util::test_runner::Parallelism; use test_util::test_runner::flaky_test_ci; use test_util::tests_path; use util::deno_config_path; use util::env_vars_for_npm_tests; fn main() { let category = collect_tests_or_exit(CollectOptions { base: tests_path().join("unit_node").to_path_buf(), strategy: Box::new(TestPerFileCollectionStrategy { file_pattern: Some(".*_test\\.ts$".to_string()), }), filter_override: None, }); if category.is_empty() { return; } let parallelism = Parallelism::default(); let flaky_test_tracker = Arc::new(FlakyTestTracker::default()); let _g = util::http_server(); // Run the crypto category tests separately without concurrency because they run in Deno with --parallel let (crypto_category, category) = category.partition(|test| test.name.contains("::crypto::")); let reporter = test_util::test_runner::get_test_reporter( "unit_node", flaky_test_tracker.clone(), ); file_test_runner::run_tests( &category, RunOptions { parallelism: parallelism.max_parallelism(), reporter: reporter.clone(), }, { let flaky_test_tracker = flaky_test_tracker.clone(); move |test| { flaky_test_ci( &test.name, &flaky_test_tracker, Some(&parallelism), || run_test(test), ) } }, ); file_test_runner::run_tests( &crypto_category, RunOptions { parallelism: NonZeroUsize::new(1).unwrap(), reporter: reporter.clone(), }, move |test| { flaky_test_ci(&test.name, &flaky_test_tracker, None, || run_test(test)) }, ); } fn run_test(test: &CollectedTest) -> TestResult { let mut deno = util::deno_cmd() .disable_diagnostic_logging() .current_dir(util::root_path()) .arg("test") .arg("--config") .arg(deno_config_path()) .arg("--no-lock") .arg("--unstable-net") .arg("-A"); // Some tests require the root CA cert file to be loaded. if test.name.ends_with("::http2_test") || test.name.ends_with("::http_test") || test.name.ends_with("::https_test") { deno = deno.arg("--cert=./tests/testdata/tls/RootCA.pem"); } // Parallel tests for crypto if test.name.contains("::crypto::") { deno = deno.arg("--parallel"); } deno .arg(test.path.clone()) .envs(env_vars_for_npm_tests()) .piped_output() .spawn() .expect("failed to spawn script") .wait_to_test_result(&test.name) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/build.rs
tests/napi/build.rs
// Copyright 2018-2025 the Deno authors. MIT license. extern crate napi_build; fn main() { napi_build::setup(); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/promise.rs
tests/napi/src/promise.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use std::ptr::addr_of_mut; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; static mut CURRENT_DEFERRED: napi_deferred = ptr::null_mut(); extern "C" fn test_promise_new( env: napi_env, _info: napi_callback_info, ) -> napi_value { let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_promise( env, addr_of_mut!(CURRENT_DEFERRED), &mut value )); value } extern "C" fn test_promise_resolve( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); assert_napi_ok!(napi_resolve_deferred(env, CURRENT_DEFERRED, args[0])); unsafe { CURRENT_DEFERRED = ptr::null_mut() }; ptr::null_mut() } extern "C" fn test_promise_reject( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); assert_napi_ok!(napi_reject_deferred(env, CURRENT_DEFERRED, args[0])); unsafe { CURRENT_DEFERRED = ptr::null_mut() }; ptr::null_mut() } extern "C" fn test_promise_is( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut is_promise: bool = false; assert_napi_ok!(napi_is_promise(env, args[0], &mut is_promise)); let mut result: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_boolean(env, is_promise, &mut result)); result } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "test_promise_new", test_promise_new), napi_new_property!(env, "test_promise_resolve", test_promise_resolve), napi_new_property!(env, "test_promise_reject", test_promise_reject), napi_new_property!(env, "test_promise_is", test_promise_is), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/array.rs
tests/napi/src/array.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::ValueType::napi_number; use napi_sys::ValueType::napi_object; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn test_array_new( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_object); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_array(env, &mut value)); let mut length: u32 = 0; assert_napi_ok!(napi_get_array_length(env, args[0], &mut length)); for i in 0..length { let mut e: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_element(env, args[0], i, &mut e)); assert_napi_ok!(napi_set_element(env, value, i, e)); } value } extern "C" fn test_array_new_with_length( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_number); let mut len: u32 = 0; assert_napi_ok!(napi_get_value_uint32(env, args[0], &mut len)); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_array_with_length(env, len as usize, &mut value)); value } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "test_array_new", test_array_new), napi_new_property!( env, "test_array_new_with_length", test_array_new_with_length ), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/tsfn.rs
tests/napi/src/tsfn.rs
// Copyright 2018-2025 the Deno authors. MIT license. // This test performs initialization similar to napi-rs. // https://github.com/napi-rs/napi-rs/commit/a5a04a4e545f268769cc78e2bd6c45af4336aac3 use std::ffi::c_char; use std::ffi::c_void; use std::ptr; use napi_sys as sys; macro_rules! check_status_or_panic { ($code:expr, $msg:expr) => {{ let c = $code; match c { sys::Status::napi_ok => {} _ => panic!($msg), } }}; } fn create_custom_gc(env: sys::napi_env) { let mut custom_gc_fn = ptr::null_mut(); check_status_or_panic!( unsafe { sys::napi_create_function( env, "custom_gc".as_ptr() as *const c_char, 9, Some(empty), ptr::null_mut(), &mut custom_gc_fn, ) }, "Create Custom GC Function in napi_register_module_v1 failed" ); let mut async_resource_name = ptr::null_mut(); check_status_or_panic!( unsafe { sys::napi_create_string_utf8( env, "CustomGC".as_ptr() as *const c_char, 8, &mut async_resource_name, ) }, "Create async resource string in napi_register_module_v1 napi_register_module_v1" ); let mut custom_gc_tsfn = ptr::null_mut(); let context = Box::into_raw(Box::new(0)) as *mut c_void; check_status_or_panic!( unsafe { sys::napi_create_threadsafe_function( env, custom_gc_fn, ptr::null_mut(), async_resource_name, 0, 1, ptr::null_mut(), Some(custom_gc_finalize), context, Some(custom_gc), &mut custom_gc_tsfn, ) }, "Create Custom GC ThreadsafeFunction in napi_register_module_v1 failed" ); check_status_or_panic!( unsafe { sys::napi_unref_threadsafe_function(env, custom_gc_tsfn) }, "Unref Custom GC ThreadsafeFunction in napi_register_module_v1 failed" ); } unsafe extern "C" fn empty( _env: sys::napi_env, _info: sys::napi_callback_info, ) -> sys::napi_value { ptr::null_mut() } unsafe extern "C" fn custom_gc_finalize( _env: sys::napi_env, _finalize_data: *mut c_void, finalize_hint: *mut c_void, ) { unsafe { let _ = Box::from_raw(finalize_hint as *mut i32); } } extern "C" fn custom_gc( env: sys::napi_env, _js_callback: sys::napi_value, _context: *mut c_void, data: *mut c_void, ) { let mut ref_count = 0; check_status_or_panic!( unsafe { sys::napi_reference_unref(env, data as sys::napi_ref, &mut ref_count) }, "Failed to unref Buffer reference in Custom GC" ); check_status_or_panic!( unsafe { sys::napi_delete_reference(env, data as sys::napi_ref) }, "Failed to delete Buffer reference in Custom GC" ); } pub fn init(env: sys::napi_env, _exports: sys::napi_value) { create_custom_gc(env); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/object.rs
tests/napi/src/object.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn test_object_new( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 2); assert_eq!(argc, 2); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_object(env, &mut value)); assert_napi_ok!(napi_set_element(env, value, 0, args[0])); assert_napi_ok!(napi_set_element(env, value, 1, args[1])); value } extern "C" fn test_object_get( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let obj = args[0]; assert_napi_ok!(napi_set_element(env, obj, 0, args[0])); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_element(env, obj, 0, &mut value)); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_element(env, obj, 1, &mut value)); obj } extern "C" fn test_object_attr_property( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let obj = args[0]; let mut property = napi_new_property!(env, "self", test_object_new); property.attributes = PropertyAttributes::enumerable; property.method = None; property.value = obj; let mut method_property = napi_new_property!(env, "method", test_object_new); method_property.attributes = PropertyAttributes::enumerable; let properties = &[property, method_property]; assert_napi_ok!(napi_define_properties( env, obj, properties.len(), properties.as_ptr() )); obj } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "test_object_new", test_object_new), napi_new_property!(env, "test_object_get", test_object_get), napi_new_property!( env, "test_object_attr_property", test_object_attr_property ), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/finalizer.rs
tests/napi/src/finalizer.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::ValueType::napi_object; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; unsafe extern "C" fn finalize_cb( _env: napi_env, data: *mut ::std::os::raw::c_void, hint: *mut ::std::os::raw::c_void, ) { assert!(data.is_null()); assert!(hint.is_null()); } extern "C" fn test_bind_finalizer( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_object); let obj = args[0]; unsafe { napi_add_finalizer( env, obj, ptr::null_mut(), Some(finalize_cb), ptr::null_mut(), ptr::null_mut(), ) }; obj } struct Thing { _allocation: Vec<u8>, } unsafe extern "C" fn finalize_cb_drop( _env: napi_env, data: *mut ::std::os::raw::c_void, hint: *mut ::std::os::raw::c_void, ) { unsafe { let _ = Box::from_raw(data as *mut Thing); assert!(hint.is_null()); } } extern "C" fn test_external_finalizer( env: napi_env, _: napi_callback_info, ) -> napi_value { let data = Box::into_raw(Box::new(Thing { _allocation: vec![1, 2, 3], })); let mut result = ptr::null_mut(); assert_napi_ok!(napi_create_external( env, data as _, Some(finalize_cb_drop), ptr::null_mut(), &mut result )); result } unsafe extern "C" fn finalize_cb_vec( _env: napi_env, data: *mut ::std::os::raw::c_void, hint: *mut ::std::os::raw::c_void, ) { unsafe { let _ = Vec::from_raw_parts(data as *mut u8, 3, 3); assert!(hint.is_null()); } } extern "C" fn test_external_buffer( env: napi_env, _: napi_callback_info, ) -> napi_value { let mut result = ptr::null_mut(); let buf: Vec<u8> = vec![1, 2, 3]; assert_napi_ok!(napi_create_external_buffer( env, 3, buf.as_ptr() as _, Some(finalize_cb_vec), ptr::null_mut(), &mut result )); std::mem::forget(buf); result } extern "C" fn test_static_external_buffer( env: napi_env, _: napi_callback_info, ) -> napi_value { let mut result = ptr::null_mut(); static BUF: &[u8] = &[1, 2, 3]; assert_napi_ok!(napi_create_external_buffer( env, BUF.len(), BUF.as_ptr() as _, None, ptr::null_mut(), &mut result )); result } extern "C" fn test_external_arraybuffer( env: napi_env, _: napi_callback_info, ) -> napi_value { let mut result = ptr::null_mut(); let buf: Vec<u8> = vec![1, 2, 3]; assert_napi_ok!(napi_create_external_arraybuffer( env, buf.as_ptr() as _, 3, Some(finalize_cb_vec), ptr::null_mut(), &mut result )); std::mem::forget(buf); result } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "test_bind_finalizer", test_bind_finalizer), napi_new_property!(env, "test_external_finalizer", test_external_finalizer), napi_new_property!(env, "test_external_buffer", test_external_buffer), napi_new_property!( env, "test_external_arraybuffer", test_external_arraybuffer ), napi_new_property!( env, "test_static_external_buffer", test_static_external_buffer ), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/date.rs
tests/napi/src/date.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::ValueType::napi_number; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn create_date( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_number); let mut time = -1.0; assert_napi_ok!(napi_get_value_double(env, args[0], &mut time)); let mut date: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_date(env, time, &mut date)); date } extern "C" fn is_date(env: napi_env, info: napi_callback_info) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let date: napi_value = args[0]; let mut result: napi_value = std::ptr::null_mut(); let mut is_date = false; assert_napi_ok!(napi_is_date(env, date, &mut is_date)); assert_napi_ok!(napi_get_boolean(env, is_date, &mut result)); result } extern "C" fn get_date_value( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let date: napi_value = args[0]; let mut result: napi_value = std::ptr::null_mut(); let mut value = 0.0; assert_napi_ok!(napi_get_date_value(env, date, &mut value)); assert_napi_ok!(napi_create_double(env, value, &mut result)); result } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "createDate", create_date), napi_new_property!(env, "isDate", is_date), napi_new_property!(env, "getDateValue", get_date_value), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/lib.rs
tests/napi/src/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. #![allow(clippy::all)] #![allow(clippy::print_stdout)] #![allow(clippy::print_stderr)] #![allow(clippy::undocumented_unsafe_blocks)] use std::ffi::c_void; use napi_sys::*; pub mod array; pub mod arraybuffer; pub mod r#async; pub mod bigint; pub mod callback; pub mod coerce; pub mod date; pub mod env; pub mod error; pub mod finalizer; pub mod make_callback; pub mod mem; pub mod numbers; pub mod object; pub mod object_wrap; pub mod primitives; pub mod promise; pub mod properties; pub mod strings; pub mod symbol; pub mod tsfn; pub mod typedarray; pub mod uv; #[macro_export] macro_rules! cstr { ($s: literal) => {{ std::ffi::CString::new($s).unwrap().into_raw() }}; } #[macro_export] macro_rules! assert_napi_ok { ($call: expr) => {{ assert_eq!( { #[allow(unused_unsafe)] unsafe { $call } }, napi_sys::Status::napi_ok ); }}; } #[macro_export] macro_rules! napi_get_callback_info { ($env: expr, $callback_info: expr, $size: literal) => {{ let mut args = [std::ptr::null_mut(); $size]; let mut argc = $size; let mut this = std::ptr::null_mut(); crate::assert_napi_ok!(napi_get_cb_info( $env, $callback_info, &mut argc, args.as_mut_ptr(), &mut this, std::ptr::null_mut(), )); (args, argc, this) }}; } #[macro_export] macro_rules! napi_new_property { ($env: expr, $name: expr, $value: expr) => { napi_property_descriptor { utf8name: concat!($name, "\0").as_ptr() as *const std::os::raw::c_char, name: std::ptr::null_mut(), method: Some($value), getter: None, setter: None, data: std::ptr::null_mut(), attributes: 0, value: std::ptr::null_mut(), } }; } extern "C" fn cleanup(arg: *mut c_void) { println!("cleanup({})", arg as i64); } extern "C" fn remove_this_hook(arg: *mut c_void) { let env = arg as napi_env; unsafe { napi_remove_env_cleanup_hook(env, Some(remove_this_hook), arg) }; } static SECRET: i64 = 42; static WRONG_SECRET: i64 = 17; static THIRD_SECRET: i64 = 18; extern "C" fn install_cleanup_hook( env: napi_env, info: napi_callback_info, ) -> napi_value { let (_args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 0); unsafe { napi_add_env_cleanup_hook(env, Some(cleanup), WRONG_SECRET as *mut c_void); napi_add_env_cleanup_hook(env, Some(cleanup), SECRET as *mut c_void); napi_add_env_cleanup_hook(env, Some(cleanup), THIRD_SECRET as *mut c_void); napi_add_env_cleanup_hook(env, Some(remove_this_hook), env as *mut c_void); napi_remove_env_cleanup_hook( env, Some(cleanup), WRONG_SECRET as *mut c_void, ); } std::ptr::null_mut() } pub fn init_cleanup_hook(env: napi_env, exports: napi_value) { let properties = &[napi_new_property!( env, "installCleanupHook", install_cleanup_hook )]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); } #[unsafe(no_mangle)] unsafe extern "C" fn napi_register_module_v1( env: napi_env, _: napi_value, ) -> napi_value { #[cfg(windows)] { unsafe { napi_sys::setup(); libuv_sys_lite::setup(); } } // We create a fresh exports object and leave the passed // exports object empty. // // https://github.com/denoland/deno/issues/17349 let mut exports = std::ptr::null_mut(); assert_napi_ok!(napi_create_object(env, &mut exports)); strings::init(env, exports); numbers::init(env, exports); typedarray::init(env, exports); arraybuffer::init(env, exports); array::init(env, exports); env::init(env, exports); error::init(env, exports); finalizer::init(env, exports); primitives::init(env, exports); properties::init(env, exports); promise::init(env, exports); coerce::init(env, exports); object_wrap::init(env, exports); callback::init(env, exports); r#async::init(env, exports); date::init(env, exports); tsfn::init(env, exports); mem::init(env, exports); bigint::init(env, exports); symbol::init(env, exports); make_callback::init(env, exports); object::init(env, exports); uv::init(env, exports); init_cleanup_hook(env, exports); exports }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/properties.rs
tests/napi/src/properties.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::PropertyAttributes::*; use napi_sys::*; use crate::assert_napi_ok; use crate::cstr; static NICE: i64 = 69; fn init_constants(env: napi_env) -> napi_value { let mut constants: napi_value = ptr::null_mut(); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_object(env, &mut constants)); assert_napi_ok!(napi_create_int64(env, NICE, &mut value)); assert_napi_ok!(napi_set_named_property( env, constants, cstr!("nice"), value )); constants } pub fn init(env: napi_env, exports: napi_value) { let mut number: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_double(env, 1.0, &mut number)); // Key name as napi_value representing `v8::String` let mut name_value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, cstr!("key_v8_string"), usize::MAX, &mut name_value, )); // Key symbol let mut symbol_description: napi_value = ptr::null_mut(); let mut name_symbol: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, cstr!("key_v8_symbol"), usize::MAX, &mut symbol_description, )); assert_napi_ok!(napi_create_symbol( env, symbol_description, &mut name_symbol )); let properties = &[ napi_property_descriptor { utf8name: cstr!("test_simple_property"), name: ptr::null_mut(), method: None, getter: None, setter: None, data: ptr::null_mut(), attributes: enumerable | writable, value: init_constants(env), }, napi_property_descriptor { utf8name: cstr!("test_property_rw"), name: ptr::null_mut(), method: None, getter: None, setter: None, data: ptr::null_mut(), attributes: enumerable | writable, value: number, }, napi_property_descriptor { utf8name: cstr!("test_property_r"), name: ptr::null_mut(), method: None, getter: None, setter: None, data: ptr::null_mut(), attributes: enumerable, value: number, }, napi_property_descriptor { utf8name: ptr::null(), name: name_value, method: None, getter: None, setter: None, data: ptr::null_mut(), attributes: enumerable, value: number, }, napi_property_descriptor { utf8name: ptr::null(), name: name_symbol, method: None, getter: None, setter: None, data: ptr::null_mut(), attributes: enumerable, value: number, }, ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/arraybuffer.rs
tests/napi/src/arraybuffer.rs
// Copyright 2018-2025 the Deno authors. MIT license. use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn test_detached( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut value = false; assert_napi_ok!(napi_is_detached_arraybuffer(env, args[0], &mut value)); assert!(!value); assert_napi_ok!(napi_detach_arraybuffer(env, args[0])); assert_napi_ok!(napi_is_detached_arraybuffer(env, args[0], &mut value)); assert!(value); args[0] } extern "C" fn is_detached( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut value = false; assert_napi_ok!(napi_is_detached_arraybuffer(env, args[0], &mut value)); let mut result = std::ptr::null_mut(); assert_napi_ok!(napi_get_boolean(env, value, &mut result)); result } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "test_detached", test_detached), napi_new_property!(env, "is_detached", is_detached), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/bigint.rs
tests/napi/src/bigint.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::Status::napi_pending_exception; use napi_sys::ValueType::napi_bigint; use napi_sys::*; use crate::assert_napi_ok; use crate::cstr; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn is_lossless( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 2); assert_eq!(argc, 2); let mut is_signed = false; assert_napi_ok!(napi_get_value_bool(env, args[1], &mut is_signed)); let mut lossless = false; if is_signed { let mut input: i64 = 0; assert_napi_ok!(napi_get_value_bigint_int64( env, args[0], &mut input, &mut lossless )); } else { let mut input: u64 = 0; assert_napi_ok!(napi_get_value_bigint_uint64( env, args[0], &mut input, &mut lossless )); } let mut output: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_boolean(env, lossless, &mut output)); output } extern "C" fn test_int64( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, _argc, _) = napi_get_callback_info!(env, info, 2); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_bigint); let mut input: i64 = 0; let mut lossless = false; assert_napi_ok!(napi_get_value_bigint_int64( env, args[0], &mut input, &mut lossless )); let mut output: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_bigint_int64(env, input, &mut output)); output } extern "C" fn test_uint64( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, _argc, _) = napi_get_callback_info!(env, info, 2); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_bigint); let mut input: u64 = 0; let mut lossless = false; assert_napi_ok!(napi_get_value_bigint_uint64( env, args[0], &mut input, &mut lossless )); let mut output: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_bigint_uint64(env, input, &mut output)); output } extern "C" fn test_words( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, _argc, _) = napi_get_callback_info!(env, info, 1); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_bigint); let mut expected_work_count = 0; assert_napi_ok!(napi_get_value_bigint_words( env, args[0], ptr::null_mut(), &mut expected_work_count, ptr::null_mut() )); let mut sign_bit = 0; let mut word_count: usize = 10; let mut words: Vec<u64> = Vec::with_capacity(10); assert_napi_ok!(napi_get_value_bigint_words( env, args[0], &mut sign_bit, &mut word_count, words.as_mut_ptr(), )); assert_eq!(word_count, expected_work_count); let mut output: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_bigint_words( env, sign_bit, word_count, words.as_ptr(), &mut output, )); output } extern "C" fn create_too_big_big_int( env: napi_env, _info: napi_callback_info, ) -> napi_value { let sign_bit = 0; let word_count = usize::MAX; let words: Vec<u64> = Vec::with_capacity(10); let mut output: napi_value = ptr::null_mut(); let result = unsafe { napi_create_bigint_words( env, sign_bit, word_count, words.as_ptr(), &mut output, ) }; assert_eq!(result, 1); output } extern "C" fn make_big_int_words_throw( env: napi_env, _info: napi_callback_info, ) -> napi_value { let words: Vec<u64> = Vec::with_capacity(10); let mut output = ptr::null_mut(); let status = unsafe { napi_create_bigint_words(env, 0, usize::MAX, words.as_ptr(), &mut output) }; if status != napi_pending_exception { unsafe { napi_throw_error( env, ptr::null_mut(), cstr!("Expected status 'napi_pending_exception'"), ) }; } ptr::null_mut() } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "isLossless", is_lossless), napi_new_property!(env, "testInt64", test_int64), napi_new_property!(env, "testUint64", test_uint64), napi_new_property!(env, "testWords", test_words), napi_new_property!(env, "createTooBigBigInt", create_too_big_big_int), napi_new_property!(env, "makeBigIntWordsThrow", make_big_int_words_throw), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/callback.rs
tests/napi/src/callback.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use Status::napi_pending_exception; use napi_sys::ValueType::napi_function; use napi_sys::ValueType::napi_object; use napi_sys::ValueType::napi_undefined; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; /// `test_callback_run((a, b) => a + b, [1, 2])` => 3 extern "C" fn test_callback_run( env: napi_env, info: napi_callback_info, ) -> napi_value { // We want to have argv with size 4, even though the callback will have // only two arguments. We'll assert that the remaining two args are undefined. let (args, argc, _) = napi_get_callback_info!(env, info, 4); assert_eq!(argc, 2); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_function); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[1], &mut ty)); assert_eq!(ty, napi_object); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[2], &mut ty)); assert_eq!(ty, napi_undefined); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[3], &mut ty)); assert_eq!(ty, napi_undefined); let mut len = 0; assert_napi_ok!(napi_get_array_length(env, args[1], &mut len)); let mut argv = Vec::with_capacity(len as usize); for index in 0..len { let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_element(env, args[1], index, &mut value)); argv.push(value); } let mut global: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_global(env, &mut global)); let mut result: napi_value = ptr::null_mut(); assert_napi_ok!(napi_call_function( env, global, args[0], argv.len(), argv.as_mut_ptr(), &mut result, )); result } extern "C" fn test_callback_run_with_recv( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 3); assert_eq!(argc, 3); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_function); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[1], &mut ty)); assert_eq!(ty, napi_object); let mut len = 0; assert_napi_ok!(napi_get_array_length(env, args[1], &mut len)); let mut argv = Vec::with_capacity(len as usize); for index in 0..len { let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_element(env, args[1], index, &mut value)); argv.push(value); } let mut result: napi_value = ptr::null_mut(); assert_napi_ok!(napi_call_function( env, args[2], // recv args[0], // cb argv.len(), argv.as_mut_ptr(), &mut result, )); result } extern "C" fn test_callback_throws( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, ..) = napi_get_callback_info!(env, info, 1); let mut global: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_global(env, &mut global)); let mut argv = vec![]; let mut result: napi_value = ptr::null_mut(); assert_eq!( unsafe { napi_call_function( env, global, // recv args[0], // cb argv.len(), argv.as_mut_ptr(), &mut result, ) }, napi_pending_exception ); result } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "test_callback_run", test_callback_run), napi_new_property!( env, "test_callback_run_with_recv", test_callback_run_with_recv ), napi_new_property!(env, "test_callback_throws", test_callback_throws), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/make_callback.rs
tests/napi/src/make_callback.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::ValueType::napi_function; use napi_sys::*; use crate::assert_napi_ok; use crate::cstr; extern "C" fn make_callback( env: napi_env, info: napi_callback_info, ) -> napi_value { const MAX_ARGUMENTS: usize = 10; const RESERVED_ARGUMENTS: usize = 3; let mut args = [std::ptr::null_mut(); MAX_ARGUMENTS]; let mut argc = MAX_ARGUMENTS; assert_napi_ok!(napi_get_cb_info( env, info, &mut argc, args.as_mut_ptr(), ptr::null_mut(), ptr::null_mut(), )); assert!(argc > 0); let resource = args[0]; let recv = args[1]; let func = args[2]; let mut argv: Vec<napi_value> = Vec::new(); argv.resize(MAX_ARGUMENTS - RESERVED_ARGUMENTS, ptr::null_mut()); for i in RESERVED_ARGUMENTS..argc { argv[i - RESERVED_ARGUMENTS] = args[i]; } let mut func_type: napi_valuetype = -1; assert_napi_ok!(napi_typeof(env, func, &mut func_type)); let mut resource_name = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, cstr!("test"), usize::MAX, &mut resource_name )); let mut context: napi_async_context = ptr::null_mut(); assert_napi_ok!(napi_async_init(env, resource, resource_name, &mut context)); let mut result = ptr::null_mut(); assert_eq!(func_type, napi_function); assert_napi_ok!(napi_make_callback( env, context, recv, func, argc - RESERVED_ARGUMENTS, argv.as_mut_ptr(), &mut result )); assert_napi_ok!(napi_async_destroy(env, context)); result } pub fn init(env: napi_env, exports: napi_value) { let mut fn_: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_function( env, ptr::null_mut(), usize::MAX, Some(make_callback), ptr::null_mut(), &mut fn_, )); assert_napi_ok!(napi_set_named_property( env, exports, cstr!("makeCallback"), fn_ )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/typedarray.rs
tests/napi/src/typedarray.rs
// Copyright 2018-2025 the Deno authors. MIT license. use core::ffi::c_void; use std::os::raw::c_char; use std::ptr; use napi_sys::Status::napi_ok; use napi_sys::TypedarrayType; use napi_sys::ValueType::napi_number; use napi_sys::ValueType::napi_object; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn test_multiply( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 2); assert_eq!(argc, 2); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_object); let input_array = args[0]; let mut is_typed_array = false; assert!( unsafe { napi_is_typedarray(env, input_array, &mut is_typed_array) } == napi_ok ); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[1], &mut ty)); assert_eq!(ty, napi_number); let mut multiplier: f64 = 0.0; assert_napi_ok!(napi_get_value_double(env, args[1], &mut multiplier)); let mut ty = -1; let mut input_buffer = ptr::null_mut(); let mut byte_offset = 0; let mut length = 0; assert_napi_ok!(napi_get_typedarray_info( env, input_array, &mut ty, &mut length, ptr::null_mut(), &mut input_buffer, &mut byte_offset, )); let mut data = ptr::null_mut(); let mut byte_length = 0; assert_napi_ok!(napi_get_arraybuffer_info( env, input_buffer, &mut data, &mut byte_length )); let mut output_buffer = ptr::null_mut(); let mut output_ptr = ptr::null_mut(); assert_napi_ok!(napi_create_arraybuffer( env, byte_length, &mut output_ptr, &mut output_buffer, )); let mut output_array: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_typedarray( env, ty, length, output_buffer, byte_offset, &mut output_array, )); if ty == TypedarrayType::uint8_array { let input_bytes = unsafe { (data as *mut u8).offset(byte_offset as isize) }; let output_bytes = output_ptr as *mut u8; for i in 0..length { unsafe { *output_bytes.offset(i as isize) = (*input_bytes.offset(i as isize) as f64 * multiplier) as u8; } } } else if ty == TypedarrayType::float64_array { let input_doubles = unsafe { (data as *mut f64).offset(byte_offset as isize) }; let output_doubles = output_ptr as *mut f64; for i in 0..length { unsafe { *output_doubles.offset(i as isize) = *input_doubles.offset(i as isize) * multiplier; } } } else { assert_napi_ok!(napi_throw_error( env, ptr::null(), "Typed array was of a type not expected by test.".as_ptr() as *const c_char, )); return ptr::null_mut(); } output_array } extern "C" fn test_external( env: napi_env, _info: napi_callback_info, ) -> napi_value { let mut arraybuffer: napi_value = ptr::null_mut(); let mut external: Box<[u8; 4]> = Box::new([0, 1, 2, 3]); assert_napi_ok!(napi_create_external_arraybuffer( env, external.as_mut_ptr() as *mut c_void, external.len(), None, ptr::null_mut(), &mut arraybuffer, )); let mut typedarray: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_typedarray( env, TypedarrayType::uint8_array, external.len(), arraybuffer, 0, &mut typedarray, )); std::mem::forget(external); // Leak into JS land typedarray } extern "C" fn test_is_buffer( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut is_buffer: bool = false; assert_napi_ok!(napi_is_buffer(env, args[0], &mut is_buffer)); let mut result: napi_value = std::ptr::null_mut(); assert_napi_ok!(napi_get_boolean(env, is_buffer, &mut result)); result } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "test_external", test_external), napi_new_property!(env, "test_multiply", test_multiply), napi_new_property!(env, "test_is_buffer", test_is_buffer), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/coerce.rs
tests/napi/src/coerce.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn test_coerce_bool( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_coerce_to_bool(env, args[0], &mut value)); value } extern "C" fn test_coerce_number( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_coerce_to_number(env, args[0], &mut value)); value } extern "C" fn test_coerce_object( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_coerce_to_object(env, args[0], &mut value)); value } extern "C" fn test_coerce_string( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_coerce_to_string(env, args[0], &mut value)); value } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "test_coerce_bool", test_coerce_bool), napi_new_property!(env, "test_coerce_number", test_coerce_number), napi_new_property!(env, "test_coerce_object", test_coerce_object), napi_new_property!(env, "test_coerce_string", test_coerce_string), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/env.rs
tests/napi/src/env.rs
// Copyright 2018-2025 the Deno authors. MIT license. use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn get_node_global( env: napi_env, info: napi_callback_info, ) -> napi_value { let (_, argc, _) = napi_get_callback_info!(env, info, 0); assert_eq!(argc, 0); let mut result: napi_value = std::ptr::null_mut(); assert_napi_ok!(napi_get_global(env, &mut result)); result } pub fn init(env: napi_env, exports: napi_value) { let properties = &[napi_new_property!(env, "testNodeGlobal", get_node_global)]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/primitives.rs
tests/napi/src/primitives.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_new_property; extern "C" fn test_get_undefined( env: napi_env, _: napi_callback_info, ) -> napi_value { let mut result = ptr::null_mut(); assert_napi_ok!(napi_get_undefined(env, &mut result)); result } pub fn init(env: napi_env, exports: napi_value) { let properties = &[napi_new_property!( env, "test_get_undefined", test_get_undefined )]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/error.rs
tests/napi/src/error.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::*; use crate::assert_napi_ok; use crate::cstr; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn check_error( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut r = false; assert_napi_ok!(napi_is_error(env, args[0], &mut r)); let mut result: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_boolean(env, r, &mut result)); result } extern "C" fn create_error( env: napi_env, _info: napi_callback_info, ) -> napi_value { let mut result: napi_value = ptr::null_mut(); let mut message: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, cstr!("error"), usize::MAX, &mut message )); assert_napi_ok!(napi_create_error( env, ptr::null_mut(), message, &mut result )); result } extern "C" fn create_range_error( env: napi_env, _info: napi_callback_info, ) -> napi_value { let mut result: napi_value = ptr::null_mut(); let mut message: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, cstr!("range error"), usize::MAX, &mut message )); assert_napi_ok!(napi_create_range_error( env, ptr::null_mut(), message, &mut result )); result } extern "C" fn create_type_error( env: napi_env, _info: napi_callback_info, ) -> napi_value { let mut result: napi_value = ptr::null_mut(); let mut message: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, cstr!("type error"), usize::MAX, &mut message )); assert_napi_ok!(napi_create_type_error( env, ptr::null_mut(), message, &mut result )); result } extern "C" fn create_error_code( env: napi_env, _info: napi_callback_info, ) -> napi_value { let mut result: napi_value = ptr::null_mut(); let mut message: napi_value = ptr::null_mut(); let mut code: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, cstr!("Error [error]"), usize::MAX, &mut message )); assert_napi_ok!(napi_create_string_utf8( env, cstr!("ERR_TEST_CODE"), usize::MAX, &mut code )); assert_napi_ok!(napi_create_error(env, code, message, &mut result)); result } extern "C" fn create_range_error_code( env: napi_env, _info: napi_callback_info, ) -> napi_value { let mut result: napi_value = ptr::null_mut(); let mut message: napi_value = ptr::null_mut(); let mut code: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, cstr!("RangeError [range error]"), usize::MAX, &mut message )); assert_napi_ok!(napi_create_string_utf8( env, cstr!("ERR_TEST_CODE"), usize::MAX, &mut code )); assert_napi_ok!(napi_create_range_error(env, code, message, &mut result)); result } extern "C" fn create_type_error_code( env: napi_env, _info: napi_callback_info, ) -> napi_value { let mut result: napi_value = ptr::null_mut(); let mut message: napi_value = ptr::null_mut(); let mut code: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, cstr!("TypeError [type error]"), usize::MAX, &mut message )); assert_napi_ok!(napi_create_string_utf8( env, cstr!("ERR_TEST_CODE"), usize::MAX, &mut code )); assert_napi_ok!(napi_create_type_error(env, code, message, &mut result)); result } extern "C" fn throw_existing_error( env: napi_env, _info: napi_callback_info, ) -> napi_value { let mut message: napi_value = ptr::null_mut(); let mut error: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, cstr!("existing error"), usize::MAX, &mut message )); assert_napi_ok!(napi_create_error( env, std::ptr::null_mut(), message, &mut error )); assert_napi_ok!(napi_throw(env, error)); std::ptr::null_mut() } extern "C" fn throw_error( env: napi_env, _info: napi_callback_info, ) -> napi_value { assert_napi_ok!(napi_throw_error(env, std::ptr::null_mut(), cstr!("error"),)); std::ptr::null_mut() } extern "C" fn throw_range_error( env: napi_env, _info: napi_callback_info, ) -> napi_value { assert_napi_ok!(napi_throw_range_error( env, std::ptr::null_mut(), cstr!("range error"), )); std::ptr::null_mut() } extern "C" fn throw_type_error( env: napi_env, _info: napi_callback_info, ) -> napi_value { assert_napi_ok!(napi_throw_type_error( env, std::ptr::null_mut(), cstr!("type error"), )); std::ptr::null_mut() } extern "C" fn throw_arbitrary( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); assert_napi_ok!(napi_throw(env, args[0])); std::ptr::null_mut() } extern "C" fn throw_error_code( env: napi_env, _info: napi_callback_info, ) -> napi_value { assert_napi_ok!(napi_throw_error( env, cstr!("ERR_TEST_CODE"), cstr!("Error [error]"), )); std::ptr::null_mut() } extern "C" fn throw_range_error_code( env: napi_env, _info: napi_callback_info, ) -> napi_value { assert_napi_ok!(napi_throw_range_error( env, cstr!("ERR_TEST_CODE"), cstr!("RangeError [range error]"), )); std::ptr::null_mut() } extern "C" fn throw_type_error_code( env: napi_env, _info: napi_callback_info, ) -> napi_value { assert_napi_ok!(napi_throw_type_error( env, cstr!("ERR_TEST_CODE"), cstr!("TypeError [type error]"), )); std::ptr::null_mut() } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "checkError", check_error), napi_new_property!(env, "throwExistingError", throw_existing_error), napi_new_property!(env, "throwError", throw_error), napi_new_property!(env, "throwRangeError", throw_range_error), napi_new_property!(env, "throwTypeError", throw_type_error), // NOTE(bartlomieju): currently experimental api // napi_new_property!(env, "throwSyntaxError", throw_syntax_error), napi_new_property!(env, "throwErrorCode", throw_error_code), napi_new_property!(env, "throwRangeErrorCode", throw_range_error_code), napi_new_property!(env, "throwTypeErrorCode", throw_type_error_code), // NOTE(bartlomieju): currently experimental api // napi_new_property!(env, "throwSyntaxErrorCode", throw_syntax_error_code), napi_new_property!(env, "throwArbitrary", throw_arbitrary), napi_new_property!(env, "createError", create_error), napi_new_property!(env, "createRangeError", create_range_error), napi_new_property!(env, "createTypeError", create_type_error), // NOTE(bartlomieju): currently experimental api // napi_new_property!(env, "createSyntaxError", create_syntax_error), napi_new_property!(env, "createErrorCode", create_error_code), napi_new_property!(env, "createRangeErrorCode", create_range_error_code), napi_new_property!(env, "createTypeErrorCode", create_type_error_code), // NOTE(bartlomieju): currently experimental api // napi_new_property!(env, "createSyntaxErrorCode", create_syntax_error_code), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/numbers.rs
tests/napi/src/numbers.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::ValueType::napi_number; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn test_int32( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_number); let mut int32 = -1; assert_napi_ok!(napi_get_value_int32(env, args[0], &mut int32)); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_int32(env, int32, &mut value)); value } extern "C" fn test_int64( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_number); let mut int64 = -1; assert_napi_ok!(napi_get_value_int64(env, args[0], &mut int64)); let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_int64(env, int64, &mut value)); value } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ napi_new_property!(env, "test_int32", test_int32), napi_new_property!(env, "test_int64", test_int64), ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/mem.rs
tests/napi/src/mem.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ptr; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_new_property; extern "C" fn adjust_external_memory( env: napi_env, _: napi_callback_info, ) -> napi_value { let mut adjusted_value = 0; assert_napi_ok!(napi_adjust_external_memory(env, 1024, &mut adjusted_value)); let mut result = ptr::null_mut(); assert_napi_ok!(napi_create_int64(env, adjusted_value, &mut result)); result } pub fn init(env: napi_env, exports: napi_value) { let properties = &[napi_new_property!( env, "adjust_external_memory", adjust_external_memory )]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/strings.rs
tests/napi/src/strings.rs
// Copyright 2018-2025 the Deno authors. MIT license. use napi_sys::ValueType::napi_string; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn test_utf8(env: napi_env, info: napi_callback_info) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_string); args[0] } extern "C" fn test_utf16( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_string); args[0] } pub fn init(env: napi_env, exports: napi_value) { let properties = &[ // utf8 napi_new_property!(env, "test_utf8", test_utf8), // utf16 napi_new_property!(env, "test_utf16", test_utf16), // latin1 ]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/object_wrap.rs
tests/napi/src/object_wrap.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::collections::HashMap; use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use napi_sys::ValueType::napi_number; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; pub struct NapiObject { counter: i32, } thread_local! { // map from native object ptr to napi reference (this is similar to what napi-rs does) static REFS: RefCell<HashMap<*mut c_void, napi_ref>> = RefCell::new(HashMap::new()); } pub extern "C" fn finalize_napi_object( env: napi_env, finalize_data: *mut c_void, _finalize_hint: *mut c_void, ) { let obj = unsafe { Box::from_raw(finalize_data as *mut NapiObject) }; drop(obj); if let Some(reference) = REFS.with_borrow_mut(|map| map.remove(&finalize_data)) { unsafe { napi_delete_reference(env, reference) }; } } impl NapiObject { fn new_inner( env: napi_env, info: napi_callback_info, finalizer: napi_finalize, out_ptr: Option<*mut napi_ref>, ) -> napi_value { assert!(matches!( (finalizer, out_ptr), (None, None) | (Some(_), Some(_)) )); let mut new_target: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_new_target(env, info, &mut new_target)); let is_constructor = !new_target.is_null(); let (args, argc, this) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); if is_constructor { let mut value = 0; let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_number); assert_napi_ok!(napi_get_value_int32(env, args[0], &mut value)); let obj = Box::new(Self { counter: value }); let obj_raw = Box::into_raw(obj) as *mut c_void; assert_napi_ok!(napi_wrap( env, this, obj_raw, finalizer, ptr::null_mut(), out_ptr.unwrap_or(ptr::null_mut()) )); if let Some(p) = out_ptr { if finalizer.is_some() { REFS.with_borrow_mut(|map| map.insert(obj_raw, unsafe { p.read() })); } } return this; } unreachable!(); } #[allow(clippy::new_ret_no_self)] pub extern "C" fn new(env: napi_env, info: napi_callback_info) -> napi_value { Self::new_inner(env, info, None, None) } #[allow(clippy::new_ret_no_self)] pub extern "C" fn new_with_finalizer( env: napi_env, info: napi_callback_info, ) -> napi_value { let mut out = ptr::null_mut(); Self::new_inner(env, info, Some(finalize_napi_object), Some(&mut out)) } pub extern "C" fn set_value( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, this) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut obj: *mut Self = ptr::null_mut(); assert_napi_ok!(napi_unwrap( env, this, &mut obj as *mut _ as *mut *mut c_void )); assert_napi_ok!(napi_get_value_int32(env, args[0], &mut (*obj).counter)); ptr::null_mut() } pub extern "C" fn get_value( env: napi_env, info: napi_callback_info, ) -> napi_value { let (_args, argc, this) = napi_get_callback_info!(env, info, 0); assert_eq!(argc, 0); let mut obj: *mut Self = ptr::null_mut(); assert_napi_ok!(napi_unwrap( env, this, &mut obj as *mut _ as *mut *mut c_void )); let mut num: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_int32(env, (*obj).counter, &mut num)); num } pub extern "C" fn increment( env: napi_env, info: napi_callback_info, ) -> napi_value { let (_args, argc, this) = napi_get_callback_info!(env, info, 0); assert_eq!(argc, 0); let mut obj: *mut Self = ptr::null_mut(); assert_napi_ok!(napi_unwrap( env, this, &mut obj as *mut _ as *mut *mut c_void )); unsafe { (*obj).counter += 1; } ptr::null_mut() } pub extern "C" fn factory( env: napi_env, info: napi_callback_info, ) -> napi_value { let (_args, argc, _this) = napi_get_callback_info!(env, info, 0); assert_eq!(argc, 0); let int64 = 64; let mut value: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_int64(env, int64, &mut value)); value } } pub fn init(env: napi_env, exports: napi_value) { let mut static_prop = napi_new_property!(env, "factory", NapiObject::factory); static_prop.attributes = PropertyAttributes::static_; let properties = &[ napi_new_property!(env, "set_value", NapiObject::set_value), napi_new_property!(env, "get_value", NapiObject::get_value), napi_new_property!(env, "increment", NapiObject::increment), static_prop, ]; let mut cons: napi_value = ptr::null_mut(); assert_napi_ok!(napi_define_class( env, "NapiObject\0".as_ptr() as *mut c_char, usize::MAX, Some(NapiObject::new), ptr::null_mut(), properties.len(), properties.as_ptr(), &mut cons, )); assert_napi_ok!(napi_set_named_property( env, exports, "NapiObject\0".as_ptr() as *const c_char, cons, )); let mut cons: napi_value = ptr::null_mut(); assert_napi_ok!(napi_define_class( env, c"NapiObjectOwned".as_ptr(), usize::MAX, Some(NapiObject::new_with_finalizer), ptr::null_mut(), properties.len(), properties.as_ptr(), &mut cons, )); assert_napi_ok!(napi_set_named_property( env, exports, "NapiObjectOwned\0".as_ptr() as *const c_char, cons, )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/async.rs
tests/napi/src/async.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::os::raw::c_char; use std::os::raw::c_void; use std::ptr; use napi_sys::Status::napi_ok; use napi_sys::ValueType::napi_function; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; pub struct Baton { called: bool, func: napi_ref, task: napi_async_work, } unsafe extern "C" fn execute(_env: napi_env, data: *mut c_void) { unsafe { let baton: &mut Baton = &mut *(data as *mut Baton); assert!(!baton.called); assert!(!baton.func.is_null()); baton.called = true; } } unsafe extern "C" fn complete( env: napi_env, status: napi_status, data: *mut c_void, ) { unsafe { assert!(status == napi_ok); let baton: Box<Baton> = Box::from_raw(data as *mut Baton); assert!(baton.called); assert!(!baton.func.is_null()); let mut global: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_global(env, &mut global)); let mut callback: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_reference_value(env, baton.func, &mut callback)); let mut _result: napi_value = ptr::null_mut(); assert_napi_ok!(napi_call_function( env, global, callback, 0, ptr::null(), &mut _result )); assert_napi_ok!(napi_delete_reference(env, baton.func)); assert_napi_ok!(napi_delete_async_work(env, baton.task)); } } extern "C" fn test_async_work( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_function); let mut resource_name: napi_value = ptr::null_mut(); assert_napi_ok!(napi_create_string_utf8( env, "test_async_resource".as_ptr() as *const c_char, usize::MAX, &mut resource_name, )); let async_work: napi_async_work = ptr::null_mut(); let mut func: napi_ref = ptr::null_mut(); assert_napi_ok!(napi_create_reference(env, args[0], 1, &mut func)); let baton = Box::new(Baton { called: false, func, task: async_work, }); let mut async_work = baton.task; let baton_ptr = Box::into_raw(baton) as *mut c_void; assert_napi_ok!(napi_create_async_work( env, ptr::null_mut(), resource_name, Some(execute), Some(complete), baton_ptr, &mut async_work, )); let mut baton = unsafe { Box::from_raw(baton_ptr as *mut Baton) }; baton.task = async_work; let _ = Box::into_raw(baton); assert_napi_ok!(napi_queue_async_work(env, async_work)); ptr::null_mut() } pub fn init(env: napi_env, exports: napi_value) { let properties = &[napi_new_property!(env, "test_async_work", test_async_work)]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/uv.rs
tests/napi/src/uv.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::mem::MaybeUninit; use std::ptr; use std::ptr::addr_of_mut; use std::ptr::null_mut; use std::time::Duration; use libuv_sys_lite::uv_async_init; use libuv_sys_lite::uv_async_t; use libuv_sys_lite::uv_close; use libuv_sys_lite::uv_handle_t; use libuv_sys_lite::uv_mutex_destroy; use libuv_sys_lite::uv_mutex_lock; use libuv_sys_lite::uv_mutex_t; use libuv_sys_lite::uv_mutex_unlock; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; struct KeepAlive { tsfn: napi_threadsafe_function, } impl KeepAlive { fn new(env: napi_env) -> Self { let mut name = null_mut(); assert_napi_ok!(napi_create_string_utf8( env, c"test_uv_async".as_ptr(), 13, &mut name )); unsafe extern "C" fn dummy( _env: napi_env, _cb: napi_callback_info, ) -> napi_value { ptr::null_mut() } let mut func = null_mut(); assert_napi_ok!(napi_create_function( env, c"dummy".as_ptr(), usize::MAX, Some(dummy), null_mut(), &mut func, )); let mut tsfn = null_mut(); assert_napi_ok!(napi_create_threadsafe_function( env, func, null_mut(), name, 0, 1, null_mut(), None, null_mut(), None, &mut tsfn, )); assert_napi_ok!(napi_ref_threadsafe_function(env, tsfn)); Self { tsfn } } } impl Drop for KeepAlive { fn drop(&mut self) { assert_napi_ok!(napi_release_threadsafe_function( self.tsfn, ThreadsafeFunctionReleaseMode::release, )); } } struct Async { mutex: *mut uv_mutex_t, env: napi_env, value: u32, callback: napi_ref, _keep_alive: KeepAlive, } #[derive(Clone, Copy)] struct UvAsyncPtr(*mut uv_async_t); unsafe impl Send for UvAsyncPtr {} fn new_raw<T>(t: T) -> *mut T { Box::into_raw(Box::new(t)) } unsafe extern "C" fn close_cb(handle: *mut uv_handle_t) { unsafe { let handle = handle.cast::<uv_async_t>(); let async_ = (*handle).data as *mut Async; let env = (*async_).env; assert_napi_ok!(napi_delete_reference(env, (*async_).callback)); uv_mutex_destroy((*async_).mutex); let _ = Box::from_raw((*async_).mutex); let _ = Box::from_raw(async_); let _ = Box::from_raw(handle); } } unsafe extern "C" fn callback(handle: *mut uv_async_t) { unsafe { eprintln!("callback"); let async_ = (*handle).data as *mut Async; uv_mutex_lock((*async_).mutex); let env = (*async_).env; let mut js_cb = null_mut(); assert_napi_ok!(napi_get_reference_value( env, (*async_).callback, &mut js_cb )); let mut global: napi_value = ptr::null_mut(); assert_napi_ok!(napi_get_global(env, &mut global)); let mut result: napi_value = ptr::null_mut(); let value = (*async_).value; eprintln!("value is {value}"); let mut value_js = ptr::null_mut(); assert_napi_ok!(napi_create_uint32(env, value, &mut value_js)); let args = &[value_js]; assert_napi_ok!(napi_call_function( env, global, js_cb, 1, args.as_ptr(), &mut result, )); uv_mutex_unlock((*async_).mutex); if value == 5 { uv_close(handle.cast(), Some(close_cb)); } } } unsafe fn uv_async_send(ptr: UvAsyncPtr) { assert_napi_ok!(libuv_sys_lite::uv_async_send(ptr.0)); } fn make_uv_mutex() -> *mut uv_mutex_t { let mutex = new_raw(MaybeUninit::<uv_mutex_t>::uninit()); assert_napi_ok!(libuv_sys_lite::uv_mutex_init(mutex.cast())); mutex.cast() } #[allow(unused_unsafe)] extern "C" fn test_uv_async( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); assert_eq!(argc, 1); let mut loop_ = null_mut(); assert_napi_ok!(napi_get_uv_event_loop(env, &mut loop_)); let uv_async = new_raw(MaybeUninit::<uv_async_t>::uninit()); let uv_async = uv_async.cast::<uv_async_t>(); let mut js_cb = null_mut(); assert_napi_ok!(napi_create_reference(env, args[0], 1, &mut js_cb)); // let mut tsfn = null_mut(); let data = new_raw(Async { env, callback: js_cb, mutex: make_uv_mutex(), value: 0, _keep_alive: KeepAlive::new(env), }); unsafe { addr_of_mut!((*uv_async).data).write(data.cast()); assert_napi_ok!(uv_async_init(loop_.cast(), uv_async, Some(callback))); let uv_async = UvAsyncPtr(uv_async); std::thread::spawn({ move || { let data = (*uv_async.0).data as *mut Async; for _ in 0..5 { uv_mutex_lock((*data).mutex); (*data).value += 1; uv_mutex_unlock((*data).mutex); std::thread::sleep(Duration::from_millis(10)); uv_async_send(uv_async); } } }); } ptr::null_mut() } pub fn init(env: napi_env, exports: napi_value) { let properties = &[napi_new_property!(env, "test_uv_async", test_uv_async)]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/src/symbol.rs
tests/napi/src/symbol.rs
// Copyright 2018-2025 the Deno authors. MIT license. use napi_sys::ValueType::napi_string; use napi_sys::*; use crate::assert_napi_ok; use crate::napi_get_callback_info; use crate::napi_new_property; extern "C" fn symbol_new( env: napi_env, info: napi_callback_info, ) -> napi_value { let (args, argc, _) = napi_get_callback_info!(env, info, 1); let mut description: napi_value = std::ptr::null_mut(); if argc >= 1 { let mut ty = -1; assert_napi_ok!(napi_typeof(env, args[0], &mut ty)); assert_eq!(ty, napi_string); description = args[0]; } let mut symbol: napi_value = std::ptr::null_mut(); assert_napi_ok!(napi_create_symbol(env, description, &mut symbol)); symbol } pub fn init(env: napi_env, exports: napi_value) { let properties = &[napi_new_property!(env, "symbolNew", symbol_new)]; assert_napi_ok!(napi_define_properties( env, exports, properties.len(), properties.as_ptr() )); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/napi/tests/napi_tests.rs
tests/napi/tests/napi_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. #![allow(clippy::print_stdout)] #![allow(clippy::print_stderr)] use std::process::Command; use test_util::deno_cmd; use test_util::deno_config_path; use test_util::env_vars_for_npm_tests; use test_util::http_server; use test_util::napi_tests_path; #[cfg(debug_assertions)] const BUILD_VARIANT: &str = "debug"; #[cfg(not(debug_assertions))] const BUILD_VARIANT: &str = "release"; fn build() { let mut build_plugin_base = Command::new("cargo"); let mut build_plugin = build_plugin_base.arg("build").arg("-p").arg("test_napi"); if BUILD_VARIANT == "release" { build_plugin = build_plugin.arg("--release"); } let build_plugin_output = build_plugin.output().unwrap(); assert!(build_plugin_output.status.success()); // cc module.c -undefined dynamic_lookup -shared -Wl,-no_fixup_chains -dynamic -o module.dylib #[cfg(not(target_os = "windows"))] { let out = if cfg!(target_os = "macos") { "module.dylib" } else { "module.so" }; let mut cc = Command::new("cc"); #[cfg(not(target_os = "macos"))] let c_module = cc.arg("module.c").arg("-shared").arg("-o").arg(out); #[cfg(target_os = "macos")] let c_module = { cc.arg("module.c") .arg("-undefined") .arg("dynamic_lookup") .arg("-shared") .arg("-Wl,-no_fixup_chains") .arg("-dynamic") .arg("-o") .arg(out) }; let c_module_output = c_module.output().unwrap(); assert!(c_module_output.status.success()); } } #[test] fn napi_tests() { build(); let _http_guard = http_server(); let output = deno_cmd() .current_dir(napi_tests_path()) .env("RUST_BACKTRACE", "1") .arg("test") .arg("--allow-read") .arg("--allow-env") .arg("--allow-ffi") .arg("--allow-run") .arg("--v8-flags=--expose-gc") .arg("--config") .arg(deno_config_path()) .arg("--no-lock") .arg(".") .envs(env_vars_for_npm_tests()) .spawn() .unwrap() .wait_with_output() .unwrap(); let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { eprintln!("exit code {:?}", output.status.code()); println!("stdout {}", stdout); println!("stderr {}", stderr); } assert!(output.status.success()); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/sqlite_extension_test/tests/integration_tests.rs
tests/sqlite_extension_test/tests/integration_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. #![allow(clippy::print_stdout)] #![allow(clippy::print_stderr)] use std::path::Path; use std::process::Command; use test_util::deno_cmd; use test_util::deno_config_path; #[cfg(debug_assertions)] const BUILD_VARIANT: &str = "debug"; #[cfg(not(debug_assertions))] const BUILD_VARIANT: &str = "release"; fn build_extension() { // The extension is in a separate standalone package (excluded from workspace) // because it requires rusqlite's "loadable_extension" feature which is // incompatible with the "session" feature used by the rest of the workspace. let tests_dir = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap(); let extension_manifest = tests_dir.join("sqlite_extension").join("Cargo.toml"); // Output to the repo's target directory so the Deno tests can find it let target_dir = tests_dir.parent().unwrap().join("target"); let mut build_plugin_base = Command::new("cargo"); let mut build_plugin = build_plugin_base .arg("build") .arg("--manifest-path") .arg(&extension_manifest) .arg("--target-dir") .arg(&target_dir) // Don't inherit RUSTFLAGS from the test environment - the sysroot // configuration used for main Deno builds doesn't have libsqlite3 .env_remove("RUSTFLAGS") .env_remove("RUSTDOCFLAGS"); if BUILD_VARIANT == "release" { build_plugin = build_plugin.arg("--release"); } let build_plugin_output = build_plugin.output().unwrap(); println!( "cargo build output: {}", String::from_utf8_lossy(&build_plugin_output.stdout) ); println!( "cargo build error: {}", String::from_utf8_lossy(&build_plugin_output.stderr) ); assert!( build_plugin_output.status.success(), "Extension build failed. Check that rusqlite features are compatible." ); } #[test] fn sqlite_extension_test() { build_extension(); let extension_dir = Path::new(env!("CARGO_MANIFEST_DIR")); let extension_test_file = extension_dir.join("sqlite_extension_test.ts"); let output = deno_cmd() .arg("test") .arg("--allow-read") .arg("--allow-write") .arg("--allow-ffi") .arg("--config") .arg(deno_config_path()) .arg("--no-check") .arg(extension_test_file) .env("NO_COLOR", "1") .output() .unwrap(); let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { println!("stdout: {}", stdout); println!("stderr: {}", stderr); panic!("Test failed"); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/ffi/src/lib.rs
tests/ffi/src/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. #![allow(clippy::print_stdout)] #![allow(clippy::print_stderr)] #![allow(clippy::undocumented_unsafe_blocks)] #![allow(non_upper_case_globals)] use std::os::raw::c_void; use std::sync::Mutex; use std::thread::sleep; use std::time::Duration; static BUFFER: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8]; #[unsafe(no_mangle)] pub extern "C" fn print_something() { println!("something"); } /// # Safety /// /// The pointer to the buffer must be valid and initialized, and the length must /// not be longer than the buffer's allocation. #[unsafe(no_mangle)] pub unsafe extern "C" fn print_buffer(ptr: *const u8, len: usize) { unsafe { let buf = std::slice::from_raw_parts(ptr, len); println!("{buf:?}"); } } /// # Safety /// /// The pointer to the buffer must be valid and initialized, and the length must /// not be longer than the buffer's allocation. #[unsafe(no_mangle)] pub unsafe extern "C" fn print_buffer2( ptr1: *const u8, len1: usize, ptr2: *const u8, len2: usize, ) { unsafe { let buf1 = std::slice::from_raw_parts(ptr1, len1); let buf2 = std::slice::from_raw_parts(ptr2, len2); println!("{buf1:?} {buf2:?}"); } } #[unsafe(no_mangle)] pub extern "C" fn return_buffer() -> *const u8 { BUFFER.as_ptr() } #[unsafe(no_mangle)] pub extern "C" fn is_null_ptr(ptr: *const u8) -> bool { ptr.is_null() } #[unsafe(no_mangle)] pub extern "C" fn add_u32(a: u32, b: u32) -> u32 { a + b } #[unsafe(no_mangle)] pub extern "C" fn add_i32(a: i32, b: i32) -> i32 { a + b } #[unsafe(no_mangle)] pub extern "C" fn add_u64(a: u64, b: u64) -> u64 { a + b } #[unsafe(no_mangle)] pub extern "C" fn add_i64(a: i64, b: i64) -> i64 { a + b } #[unsafe(no_mangle)] pub extern "C" fn add_usize(a: usize, b: usize) -> usize { a + b } #[unsafe(no_mangle)] pub extern "C" fn add_usize_fast(a: usize, b: usize) -> u32 { (a + b) as u32 } #[unsafe(no_mangle)] pub extern "C" fn add_isize(a: isize, b: isize) -> isize { a + b } #[unsafe(no_mangle)] pub extern "C" fn add_f32(a: f32, b: f32) -> f32 { a + b } #[unsafe(no_mangle)] pub extern "C" fn add_f64(a: f64, b: f64) -> f64 { a + b } #[unsafe(no_mangle)] pub extern "C" fn and(a: bool, b: bool) -> bool { a && b } #[unsafe(no_mangle)] unsafe extern "C" fn hash(ptr: *const u8, length: u32) -> u32 { unsafe { let buf = std::slice::from_raw_parts(ptr, length as usize); let mut hash: u32 = 0; for byte in buf { hash = hash.wrapping_mul(0x10001000).wrapping_add(*byte as u32); } hash } } #[unsafe(no_mangle)] pub extern "C" fn sleep_blocking(ms: u64) { let duration = Duration::from_millis(ms); sleep(duration); } /// # Safety /// /// The pointer to the buffer must be valid and initialized, and the length must /// not be longer than the buffer's allocation. #[unsafe(no_mangle)] pub unsafe extern "C" fn fill_buffer(value: u8, buf: *mut u8, len: usize) { unsafe { let buf = std::slice::from_raw_parts_mut(buf, len); for itm in buf.iter_mut() { *itm = value; } } } /// # Safety /// /// The pointer to the buffer must be valid and initialized, and the length must /// not be longer than the buffer's allocation. #[unsafe(no_mangle)] pub unsafe extern "C" fn nonblocking_buffer(ptr: *const u8, len: usize) { unsafe { let buf = std::slice::from_raw_parts(ptr, len); assert_eq!(buf, vec![1, 2, 3, 4, 5, 6, 7, 8]); } } #[unsafe(no_mangle)] pub extern "C" fn get_add_u32_ptr() -> *const c_void { add_u32 as *const c_void } #[unsafe(no_mangle)] pub extern "C" fn get_sleep_blocking_ptr() -> *const c_void { sleep_blocking as *const c_void } #[unsafe(no_mangle)] pub extern "C" fn call_fn_ptr(func: Option<extern "C" fn()>) { if func.is_none() { return; } let func = func.unwrap(); func(); } #[unsafe(no_mangle)] pub extern "C" fn call_fn_ptr_many_parameters( func: Option< extern "C" fn(u8, i8, u16, i16, u32, i32, u64, i64, f32, f64, *const u8), >, ) { if func.is_none() { return; } let func = func.unwrap(); func(1, -1, 2, -2, 3, -3, 4, -4, 0.5, -0.5, BUFFER.as_ptr()); } #[unsafe(no_mangle)] pub extern "C" fn call_fn_ptr_return_u8(func: Option<extern "C" fn() -> u8>) { if func.is_none() { return; } let func = func.unwrap(); println!("u8: {}", func()); } #[allow(clippy::not_unsafe_ptr_arg_deref)] #[unsafe(no_mangle)] pub extern "C" fn call_fn_ptr_return_buffer( func: Option<extern "C" fn() -> *const u8>, ) { if func.is_none() { return; } let func = func.unwrap(); let ptr = func(); let buf = unsafe { std::slice::from_raw_parts(ptr, 8) }; println!("buf: {buf:?}"); } static STORED_FUNCTION: Mutex<Option<extern "C" fn()>> = Mutex::new(None); static STORED_FUNCTION_2: Mutex<Option<extern "C" fn(u8) -> u8>> = Mutex::new(None); #[unsafe(no_mangle)] pub extern "C" fn store_function(func: Option<extern "C" fn()>) { *STORED_FUNCTION.lock().unwrap() = func; if func.is_none() { println!("STORED_FUNCTION cleared"); } } #[unsafe(no_mangle)] pub extern "C" fn store_function_2(func: Option<extern "C" fn(u8) -> u8>) { *STORED_FUNCTION_2.lock().unwrap() = func; if func.is_none() { println!("STORED_FUNCTION_2 cleared"); } } #[unsafe(no_mangle)] pub extern "C" fn call_stored_function() { let f = *STORED_FUNCTION.lock().unwrap(); if let Some(f) = f { f(); } } #[unsafe(no_mangle)] pub extern "C" fn call_stored_function_2(arg: u8) { let f = *STORED_FUNCTION_2.lock().unwrap(); if let Some(f) = f { println!("{}", f(arg)); } } #[unsafe(no_mangle)] pub extern "C" fn call_stored_function_thread_safe() { std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_millis(1500)); let f = *STORED_FUNCTION.lock().unwrap(); if let Some(f) = f { f(); } }); } #[unsafe(no_mangle)] pub extern "C" fn call_stored_function_thread_safe_and_log() { std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_millis(1500)); let f = *STORED_FUNCTION.lock().unwrap(); if let Some(f) = f { f(); println!("STORED_FUNCTION called"); } }); } #[unsafe(no_mangle)] pub extern "C" fn call_stored_function_2_thread_safe(arg: u8) { std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_millis(1500)); let f = *STORED_FUNCTION_2.lock().unwrap(); if let Some(f) = f { println!("Calling"); f(arg); } }); } #[unsafe(no_mangle)] pub extern "C" fn log_many_parameters( a: u8, b: u16, c: u32, d: u64, e: f64, f: f32, g: i64, h: i32, i: i16, j: i8, k: isize, l: usize, m: f64, n: f32, o: f64, p: f32, q: f64, r: f32, s: f64, ) { println!( "{a} {b} {c} {d} {e} {f} {g} {h} {i} {j} {k} {l} {m} {n} {o} {p} {q} {r} {s}" ); } #[unsafe(no_mangle)] pub extern "C" fn cast_u8_u32(x: u8) -> u32 { x as u32 } #[unsafe(no_mangle)] pub extern "C" fn cast_u32_u8(x: u32) -> u8 { x as u8 } #[unsafe(no_mangle)] pub extern "C" fn add_many_u16( a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16, i: u16, j: u16, k: u16, l: u16, m: u16, ) -> u16 { a + b + c + d + e + f + g + h + i + j + k + l + m } // FFI performance helper functions #[unsafe(no_mangle)] pub extern "C" fn nop() {} #[unsafe(no_mangle)] pub extern "C" fn nop_bool(_a: bool) {} #[unsafe(no_mangle)] pub extern "C" fn nop_u8(_a: u8) {} #[unsafe(no_mangle)] pub extern "C" fn nop_i8(_a: i8) {} #[unsafe(no_mangle)] pub extern "C" fn nop_u16(_a: u16) {} #[unsafe(no_mangle)] pub extern "C" fn nop_i16(_a: i16) {} #[unsafe(no_mangle)] pub extern "C" fn nop_u32(_a: u32) {} #[unsafe(no_mangle)] pub extern "C" fn nop_i32(_a: i32) {} #[unsafe(no_mangle)] pub extern "C" fn nop_u64(_a: u64) {} #[unsafe(no_mangle)] pub extern "C" fn nop_i64(_a: i64) {} #[unsafe(no_mangle)] pub extern "C" fn nop_usize(_a: usize) {} #[unsafe(no_mangle)] pub extern "C" fn nop_isize(_a: isize) {} #[unsafe(no_mangle)] pub extern "C" fn nop_f32(_a: f32) {} #[unsafe(no_mangle)] pub extern "C" fn nop_f64(_a: f64) {} #[unsafe(no_mangle)] pub extern "C" fn nop_buffer(_buffer: *mut [u8; 8]) {} #[unsafe(no_mangle)] pub extern "C" fn return_bool() -> bool { true } #[unsafe(no_mangle)] pub extern "C" fn return_u8() -> u8 { 255 } #[unsafe(no_mangle)] pub extern "C" fn return_i8() -> i8 { -128 } #[unsafe(no_mangle)] pub extern "C" fn return_u16() -> u16 { 65535 } #[unsafe(no_mangle)] pub extern "C" fn return_i16() -> i16 { -32768 } #[unsafe(no_mangle)] pub extern "C" fn return_u32() -> u32 { 4294967295 } #[unsafe(no_mangle)] pub extern "C" fn return_i32() -> i32 { -2147483648 } #[unsafe(no_mangle)] pub extern "C" fn return_u64() -> u64 { 18446744073709551615 } #[unsafe(no_mangle)] pub extern "C" fn return_i64() -> i64 { -9223372036854775808 } #[unsafe(no_mangle)] pub extern "C" fn return_usize() -> usize { 18446744073709551615 } #[unsafe(no_mangle)] pub extern "C" fn return_isize() -> isize { -9223372036854775808 } #[unsafe(no_mangle)] pub extern "C" fn return_f32() -> f32 { #[allow(clippy::excessive_precision)] 0.20298023223876953125 } #[unsafe(no_mangle)] pub extern "C" fn return_f64() -> f64 { 1e-10 } // Parameters iteration #[unsafe(no_mangle)] pub extern "C" fn nop_many_parameters( _: u8, _: i8, _: u16, _: i16, _: u32, _: i32, _: u64, _: i64, _: usize, _: isize, _: f32, _: f64, _: *mut [u8; 8], _: u8, _: i8, _: u16, _: i16, _: u32, _: i32, _: u64, _: i64, _: usize, _: isize, _: f32, _: f64, _: *mut [u8; 8], ) { } // Statics #[unsafe(no_mangle)] pub static static_u32: u32 = 42; #[unsafe(no_mangle)] pub static static_i64: i64 = -1242464576485; #[repr(C)] pub struct Structure { _data: u32, } #[unsafe(no_mangle)] pub static mut static_ptr: Structure = Structure { _data: 42 }; static STRING: &str = "Hello, world!\0"; #[unsafe(no_mangle)] extern "C" fn ffi_string() -> *const u8 { STRING.as_ptr() } /// Invalid UTF-8 characters, array of length 14 #[unsafe(no_mangle)] pub static static_char: [u8; 14] = [ 0xC0, 0xC1, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, 0x00, ]; #[derive(Debug)] #[repr(C)] pub struct Rect { x: f64, y: f64, w: f64, h: f64, } #[unsafe(no_mangle)] pub extern "C" fn make_rect(x: f64, y: f64, w: f64, h: f64) -> Rect { Rect { x, y, w, h } } #[unsafe(no_mangle)] pub extern "C" fn print_rect(rect: Rect) { println!("{rect:?}"); } #[derive(Debug)] #[repr(C)] pub struct Mixed { u8: u8, f32: f32, rect: Rect, usize: usize, array: [u32; 2], } /// # Safety /// /// The array pointer to the buffer must be valid and initialized, and the length must /// be 2. #[unsafe(no_mangle)] pub unsafe extern "C" fn create_mixed( u8: u8, f32: f32, rect: Rect, usize: usize, array: *const [u32; 2], ) -> Mixed { unsafe { let array = *array .as_ref() .expect("Array parameter should contain value"); Mixed { u8, f32, rect, usize, array, } } } #[unsafe(no_mangle)] pub extern "C" fn print_mixed(mixed: Mixed) { println!("{mixed:?}"); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/ffi/tests/integration_tests.rs
tests/ffi/tests/integration_tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. #![allow(clippy::print_stdout)] #![allow(clippy::print_stderr)] use std::process::Command; use pretty_assertions::assert_eq; use test_util::deno_cmd; use test_util::deno_config_path; use test_util::ffi_tests_path; #[cfg(debug_assertions)] const BUILD_VARIANT: &str = "debug"; #[cfg(not(debug_assertions))] const BUILD_VARIANT: &str = "release"; fn build() { let mut build_plugin_base = Command::new("cargo"); let mut build_plugin = build_plugin_base.arg("build").arg("-p").arg("test_ffi"); if BUILD_VARIANT == "release" { build_plugin = build_plugin.arg("--release"); } let build_plugin_output = build_plugin.output().unwrap(); assert!(build_plugin_output.status.success()); } #[test] fn basic() { build(); let output = deno_cmd() .current_dir(ffi_tests_path()) .arg("run") .arg("--config") .arg(deno_config_path()) .arg("--no-lock") .arg("--allow-ffi") .arg("--allow-read") .arg("--unstable-ffi") .arg("--quiet") .arg(r#"--v8-flags=--allow-natives-syntax"#) .arg("tests/test.js") .env("NO_COLOR", "1") .env("DENO_UNSTABLE_FFI_TRACE_TURBO", "1") .output() .unwrap(); let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { println!("stdout {stdout}"); println!("stderr {stderr}"); } println!("{:?}", output.status); assert!(output.status.success()); let expected = "\ something\n\ [1, 2, 3, 4, 5, 6, 7, 8]\n\ [4, 5, 6]\n\ [1, 2, 3, 4, 5, 6, 7, 8] [9, 10]\n\ [1, 2, 3, 4, 5, 6, 7, 8]\n\ [ 1, 2, 3, 4, 5, 6 ]\n\ [ 4, 5, 6 ]\n\ [ 4, 5, 6 ]\n\ Hello from pointer!\n\ pointer!\n\ false false\n\ true true\n\ false false\n\ true true\n\ false false\n\ 579\n\ true\n\ 579\n\ 579\n\ 5\n\ 5\n\ 579\n\ 8589934590n\n\ -8589934590n\n\ 8589934590n\n\ -8589934590n\n\ 9007199254740992n\n\ 9007199254740992n\n\ -9007199254740992n\n\ 9007199254740992n\n\ 9007199254740992n\n\ -9007199254740992n\n\ 579.9119873046875\n\ 579.912\n\ true\n\ false\n\ 579.9119873046875\n\ 579.9119873046875\n\ 579.912\n\ 579.912\n\ 579\n\ 8589934590n\n\ -8589934590n\n\ 8589934590n\n\ -8589934590n\n\ 9007199254740992n\n\ 9007199254740992n\n\ -9007199254740992n\n\ 9007199254740992n\n\ 9007199254740992n\n\ -9007199254740992n\n\ 579.9119873046875\n\ 579.912\n\ Before\n\ After\n\ logCallback\n\ 1 -1 2 -2 3 -3 4n -4n 0.5 -0.5 1 2 3 4 5 6 7 8\n\ u8: 8\n\ buf: [1, 2, 3, 4, 5, 6, 7, 8]\n\ logCallback\n\ 30\n\ 255 65535 4294967295 4294967296 123.456 789.876 -1 -2 -3 -4 -1000 1000 12345.67891 12345.679 12345.67891 12345.679 12345.67891 12345.679 12345.67891\n\ 255 65535 4294967295 4294967296 123.456 789.876 -1 -2 -3 -4 -1000 1000 12345.67891 12345.679 12345.67891 12345.679 12345.67891 12345.679 12345.67891\n\ 0\n\ 0\n\ 0\n\ 0\n\ 78\n\ 78\n\ STORED_FUNCTION cleared\n\ STORED_FUNCTION_2 cleared\n\ logCallback\n\ u8: 8\n\ Rect { x: 10.0, y: 20.0, w: 100.0, h: 200.0 }\n\ Rect { x: 10.0, y: 20.0, w: 100.0, h: 200.0 }\n\ Rect { x: 20.0, y: 20.0, w: 100.0, h: 200.0 }\n\ Mixed { u8: 3, f32: 12.515, rect: Rect { x: 10.0, y: 20.0, w: 100.0, h: 200.0 }, usize: 12456789, array: [8, 32] }\n\ 2264956937\n\ 2264956937\n\ Correct number of resources\n"; assert_eq!(stdout, expected); assert_eq!(stderr, ""); } #[test] fn symbol_types() { build(); let output = deno_cmd() .current_dir(ffi_tests_path()) .arg("check") .arg("--config") .arg(deno_config_path()) .arg("--no-lock") .arg("--unstable-ffi") .arg("--quiet") .arg("tests/ffi_types.ts") .env("NO_COLOR", "1") .output() .unwrap(); let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { println!("stdout {stdout}"); println!("stderr {stderr}"); } println!("{:?}", output.status); assert!(output.status.success()); assert_eq!(stderr, ""); } #[test] fn thread_safe_callback() { build(); let output = deno_cmd() .current_dir(ffi_tests_path()) .arg("run") .arg("--config") .arg(deno_config_path()) .arg("--no-lock") .arg("--allow-ffi") .arg("--allow-read") .arg("--unstable-ffi") .arg("--quiet") .arg("tests/thread_safe_test.js") .env("NO_COLOR", "1") .output() .unwrap(); let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { println!("stdout {stdout}"); println!("stderr {stderr}"); } println!("{:?}", output.status); assert!(output.status.success()); let expected = "\ Callback on main thread\n\ Callback on worker thread\n\ STORED_FUNCTION cleared\n\ Calling callback, isolate should stay asleep until callback is called\n\ Callback being called\n\ STORED_FUNCTION cleared\n\ Isolate should now exit\n"; assert_eq!(stdout, expected); assert_eq!(stderr, ""); } #[test] fn event_loop_integration() { build(); let output = deno_cmd() .current_dir(ffi_tests_path()) .arg("run") .arg("--config") .arg(deno_config_path()) .arg("--no-lock") .arg("--allow-ffi") .arg("--allow-read") .arg("--unstable-ffi") .arg("--quiet") .arg("tests/event_loop_integration.ts") .env("NO_COLOR", "1") .output() .unwrap(); let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { println!("stdout {stdout}"); println!("stderr {stderr}"); } println!("{:?}", output.status); assert!(output.status.success()); // TODO(aapoalas): The order of logging in thread safe callbacks is // unexpected: The callback logs synchronously and creates an asynchronous // logging task, which then gets called synchronously before the callback // actually yields to the calling thread. This is in contrast to what the // logging would look like if the call was coming from within Deno itself, // and may lead users to unknowingly run heavy asynchronous tasks from thread // safe callbacks synchronously. // The fix would be to make sure microtasks are only run after the event loop // middleware that polls them has completed its work. This just does not seem // to work properly with Linux release builds. let expected = "\ SYNCHRONOUS\n\ Sync\n\ STORED_FUNCTION called\n\ Async\n\ Timeout\n\ THREAD SAFE\n\ Sync\n\ Async\n\ STORED_FUNCTION called\n\ Timeout\n\ RETRY THREAD SAFE\n\ Sync\n\ Async\n\ STORED_FUNCTION called\n\ Timeout\n"; assert_eq!(stdout, expected); assert_eq!(stderr, ""); } #[test] fn ffi_callback_errors_test() { build(); let output = deno_cmd() .current_dir(ffi_tests_path()) .arg("run") .arg("--config") .arg(deno_config_path()) .arg("--no-lock") .arg("--allow-ffi") .arg("--allow-read") .arg("--unstable-ffi") .arg("--quiet") .arg("tests/ffi_callback_errors.ts") .env("NO_COLOR", "1") .output() .unwrap(); let stdout = std::str::from_utf8(&output.stdout).unwrap(); let stderr = std::str::from_utf8(&output.stderr).unwrap(); if !output.status.success() { println!("stdout {stdout}"); println!("stderr {stderr}"); } println!("{:?}", output.status); assert!(output.status.success()); let expected = "\ CallCase: SyncSelf\n\ Throwing errors from an UnsafeCallback called from a synchronous UnsafeFnPointer works. Terribly excellent.\n\ CallCase: SyncFfi\n\ 0\n\ Throwing errors from an UnsafeCallback called from a synchronous FFI symbol works. Terribly excellent.\n\ CallCase: AsyncSelf\n\ CallCase: AsyncSyncFfi\n\ 0\n\ Calling\n\ CallCase: AsyncFfi\n"; assert_eq!(stdout, expected); assert_eq!( stderr, "Illegal unhandled exception in nonblocking callback\n".repeat(3) ); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/unit/mod.rs
tests/unit/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::sync::Arc; use file_test_runner::RunOptions; use file_test_runner::TestResult; use file_test_runner::collection::CollectOptions; use file_test_runner::collection::CollectedTest; use file_test_runner::collection::collect_tests_or_exit; use file_test_runner::collection::strategies::TestPerFileCollectionStrategy; use test_util as util; use test_util::TestContextBuilder; use test_util::test_runner::FlakyTestTracker; use test_util::test_runner::Parallelism; use test_util::test_runner::flaky_test_ci; use test_util::tests_path; fn main() { let category = collect_tests_or_exit(CollectOptions { base: tests_path().join("unit").to_path_buf(), strategy: Box::new(TestPerFileCollectionStrategy { file_pattern: Some(".*_test\\.ts$".to_string()), }), filter_override: None, }); if category.is_empty() { return; // no tests to run for the filter } let parallelism = Parallelism::default(); let flaky_test_tracker = Arc::new(FlakyTestTracker::default()); let _g = util::http_server(); file_test_runner::run_tests( &category, RunOptions { parallelism: parallelism.max_parallelism(), reporter: test_util::test_runner::get_test_reporter( "unit", flaky_test_tracker.clone(), ), }, move |test| { flaky_test_ci(&test.name, &flaky_test_tracker, Some(&parallelism), || { run_test(test) }) }, ) } fn run_test(test: &CollectedTest) -> TestResult { let mut deno = if test.name.ends_with("::bundle_test") { TestContextBuilder::new() .add_npm_env_vars() .use_http_server() .build() .new_command() } else { util::deno_cmd() }; deno = deno .disable_diagnostic_logging() .current_dir(util::root_path()) .arg("test") .arg("--config") .arg(util::deno_config_path()) .arg("--no-lock") // TODO(bartlomieju): would be better if we could apply this unstable // flag to particular files, but there's many of them that rely on unstable // net APIs (`reusePort` in `listen` and `listenTls`; `listenDatagram`) .arg("--unstable-net") .arg("--unstable-vsock") .arg("--location=http://127.0.0.1:4545/") .arg("--no-prompt"); if test.name.ends_with("::bundle_test") { deno = deno.arg("--unstable-bundle"); } if test.name.ends_with("::cron_test") { deno = deno.arg("--unstable-cron"); } if test.name.contains("::kv_") { deno = deno.arg("--unstable-kv"); } if test.name.ends_with("::worker_permissions_test") || test.name.ends_with("::worker_test") { deno = deno.arg("--unstable-worker-options"); } // Some tests require the root CA cert file to be loaded. if test.name.ends_with("::websocket_test") { deno = deno.arg(format!( "--cert={}", util::testdata_path() .join("tls") .join("RootCA.pem") .to_string_lossy() )); }; if test.name.ends_with("::tls_sni_test") { // TODO(lucacasonato): fix the SNI in the certs so that this is not needed deno = deno.arg("--unsafely-ignore-certificate-errors"); } let mut deno = deno.arg("-A").arg(test.path.clone()); // update the snapshots if when `UPDATE=1` if std::env::var_os("UPDATE") == Some("1".into()) { deno = deno.arg("--").arg("--update"); } deno .piped_output() .spawn() .expect("failed to spawn script") .wait_to_test_result(&test.name) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/sqlite_extension/src/lib.rs
tests/sqlite_extension/src/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. //! A simple SQLite loadable extension for testing. //! //! This extension provides a `test_func(x)` function that returns its argument unchanged. use std::os::raw::c_char; use std::os::raw::c_int; use rusqlite::Connection; use rusqlite::Result; use rusqlite::ffi; use rusqlite::functions::FunctionFlags; use rusqlite::types::ToSqlOutput; use rusqlite::types::Value; /// Entry point for SQLite to load the extension. #[expect(clippy::not_unsafe_ptr_arg_deref)] #[unsafe(no_mangle)] pub unsafe extern "C" fn sqlite3_extension_init( db: *mut ffi::sqlite3, pz_err_msg: *mut *mut c_char, p_api: *mut ffi::sqlite3_api_routines, ) -> c_int { // SAFETY: This function is called by SQLite with valid pointers. // extension_init2 handles the API initialization. unsafe { Connection::extension_init2(db, pz_err_msg, p_api, extension_init) } } fn extension_init(db: Connection) -> Result<bool> { db.create_scalar_function( "test_func", 1, FunctionFlags::SQLITE_DETERMINISTIC, |ctx| { // Return the argument value unchanged let value: Value = ctx.get(0)?; Ok(ToSqlOutput::Owned(value)) }, )?; Ok(false) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/specs/mod.rs
tests/specs/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; use std::panic::AssertUnwindSafe; use std::path::Path; use std::rc::Rc; use std::sync::Arc; use anyhow::Context; use file_test_runner::NO_CAPTURE; use file_test_runner::TestResult; use file_test_runner::collection::CollectOptions; use file_test_runner::collection::CollectTestsError; use file_test_runner::collection::CollectedCategoryOrTest; use file_test_runner::collection::CollectedTest; use file_test_runner::collection::CollectedTestCategory; use file_test_runner::collection::collect_tests_or_exit; use file_test_runner::collection::strategies::FileTestMapperStrategy; use file_test_runner::collection::strategies::TestPerDirectoryCollectionStrategy; use serde::Deserialize; use test_util::IS_CI; use test_util::PathRef; use test_util::TestContextBuilder; use test_util::test_runner::FlakyTestTracker; use test_util::test_runner::Parallelism; use test_util::test_runner::run_maybe_flaky_test; use test_util::tests_path; const MANIFEST_FILE_NAME: &str = "__test__.jsonc"; #[derive(Clone, Deserialize)] #[serde(untagged)] enum VecOrString { Vec(Vec<String>), String(String), } type JsonMap = serde_json::Map<String, serde_json::Value>; #[derive(Clone, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct MultiTestMetaData { /// Whether to copy all the non-assertion files in the current /// test directory to a temporary directory before running the /// steps. #[serde(default)] pub temp_dir: bool, /// The base environment to use for the test. #[serde(default)] pub base: Option<String>, #[serde(default)] pub envs: HashMap<String, String>, #[serde(default)] pub cwd: Option<String>, #[serde(default)] pub tests: BTreeMap<String, JsonMap>, #[serde(default)] pub ignore: bool, #[serde(default)] pub variants: BTreeMap<String, JsonMap>, } impl MultiTestMetaData { pub fn into_collected_tests( mut self, parent_test: &CollectedTest, ) -> Vec<CollectedCategoryOrTest<serde_json::Value>> { fn merge_json_value( multi_test_meta_data: &MultiTestMetaData, value: &mut JsonMap, ) { if let Some(base) = &multi_test_meta_data.base && !value.contains_key("base") { value.insert("base".to_string(), base.clone().into()); } if multi_test_meta_data.temp_dir && !value.contains_key("tempDir") { value.insert("tempDir".to_string(), true.into()); } if multi_test_meta_data.cwd.is_some() && !value.contains_key("cwd") { value .insert("cwd".to_string(), multi_test_meta_data.cwd.clone().into()); } if !multi_test_meta_data.envs.is_empty() { if !value.contains_key("envs") { value.insert("envs".to_string(), JsonMap::default().into()); } let envs_obj = value.get_mut("envs").unwrap().as_object_mut().unwrap(); for (key, value) in &multi_test_meta_data.envs { if !envs_obj.contains_key(key) { envs_obj.insert(key.into(), value.clone().into()); } } } if multi_test_meta_data.ignore && !value.contains_key("ignore") { value.insert("ignore".to_string(), true.into()); } if !multi_test_meta_data.variants.is_empty() { if !value.contains_key("variants") { value.insert("variants".to_string(), JsonMap::default().into()); } let variants_obj = value.get_mut("variants").unwrap().as_object_mut().unwrap(); for (key, value) in &multi_test_meta_data.variants { if !variants_obj.contains_key(key) { variants_obj.insert(key.into(), value.clone().into()); } } } } let mut collected_tests = Vec::with_capacity(self.tests.len()); for (name, mut json_data) in std::mem::take(&mut self.tests) { merge_json_value(&self, &mut json_data); collected_tests.push(CollectedTest { name: format!("{}::{}", parent_test.name, name), path: parent_test.path.clone(), line_and_column: None, data: serde_json::Value::Object(json_data), }); } let mut all_tests = Vec::with_capacity(collected_tests.len()); for test in collected_tests { if let Some(variants) = test .data .as_object() .and_then(|o| o.get("variants")) .and_then(|v| v.as_object()) && !variants.is_empty() { all_tests.push( map_variants(&test.data, &test.path, &test.name, variants.iter()) .unwrap(), ); } else { all_tests.push(CollectedCategoryOrTest::Test(test)); } } all_tests } } #[derive(Clone, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct MultiStepMetaData { /// Whether to copy all the non-assertion files in the current /// test directory to a temporary directory before running the /// steps. #[serde(default)] pub temp_dir: bool, /// Whether to run this test. #[serde(rename = "if")] pub if_cond: Option<String>, /// Whether the temporary directory should be canonicalized. /// /// This should be used sparingly, but is sometimes necessary /// on the CI. #[serde(default)] pub canonicalized_temp_dir: bool, /// Whether the temporary directory should be symlinked to another path. #[serde(default)] pub symlinked_temp_dir: bool, #[serde(default)] pub flaky: bool, /// The base environment to use for the test. #[serde(default)] pub base: Option<String>, #[serde(default)] pub cwd: Option<String>, #[serde(default)] pub envs: HashMap<String, String>, #[serde(default)] pub repeat: Option<usize>, #[serde(default)] pub steps: Vec<StepMetaData>, #[serde(default)] pub ignore: bool, #[serde(default)] pub variants: BTreeMap<String, JsonMap>, } #[derive(Clone, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct SingleTestMetaData { #[serde(default)] pub base: Option<String>, #[serde(default)] pub temp_dir: bool, #[serde(default)] pub canonicalized_temp_dir: bool, #[serde(default)] pub symlinked_temp_dir: bool, #[serde(default)] pub repeat: Option<usize>, #[serde(flatten)] pub step: StepMetaData, #[serde(default)] pub ignore: bool, #[allow(dead_code)] #[serde(default)] pub variants: BTreeMap<String, JsonMap>, } impl SingleTestMetaData { pub fn into_multi(self) -> MultiStepMetaData { MultiStepMetaData { base: self.base, cwd: None, if_cond: self.step.if_cond.clone(), flaky: self.step.flaky, temp_dir: self.temp_dir, canonicalized_temp_dir: self.canonicalized_temp_dir, symlinked_temp_dir: self.symlinked_temp_dir, repeat: self.repeat, envs: Default::default(), steps: vec![self.step], ignore: self.ignore, variants: self.variants, } } } #[derive(Clone, Deserialize)] #[serde(deny_unknown_fields, rename_all = "camelCase")] struct StepMetaData { /// If the test should be retried multiple times on failure. #[serde(default)] pub flaky: bool, pub args: VecOrString, pub cwd: Option<String>, #[serde(rename = "if")] pub if_cond: Option<String>, pub command_name: Option<String>, #[serde(default)] pub envs: HashMap<String, String>, pub input: Option<String>, pub output: String, #[serde(default)] pub exit_code: i32, #[serde(default)] pub variants: BTreeMap<String, JsonMap>, } pub fn main() { let root_category = collect_tests_or_exit::<serde_json::Value>(CollectOptions { base: tests_path().join("specs").to_path_buf(), strategy: Box::new(FileTestMapperStrategy { base_strategy: TestPerDirectoryCollectionStrategy { file_name: MANIFEST_FILE_NAME.to_string(), }, map: map_test_within_file, }), filter_override: None, }) .into_flat_category(); if root_category.is_empty() { return; // all tests filtered out } let _http_guard = test_util::http_server(); let parallelism = Parallelism::default(); let flaky_test_tracker = Arc::new(FlakyTestTracker::default()); file_test_runner::run_tests( &root_category, file_test_runner::RunOptions { parallelism: parallelism.max_parallelism(), reporter: test_util::test_runner::get_test_reporter( "specs", flaky_test_tracker.clone(), ), }, move |test| run_test(test, &flaky_test_tracker, &parallelism), ); } fn run_test( test: &CollectedTest<serde_json::Value>, flaky_test_tracker: &FlakyTestTracker, parallelism: &Parallelism, ) -> TestResult { let cwd = PathRef::new(&test.path).parent(); let metadata_value = test.data.clone(); let diagnostic_logger = Rc::new(RefCell::new(Vec::<u8>::new())); let result = TestResult::from_maybe_panic_or_result(AssertUnwindSafe(|| { let metadata = deserialize_value(metadata_value); let substs = variant_substitutions(&BTreeMap::new(), &metadata.variants); let if_cond = metadata .if_cond .as_deref() .map(|s| apply_substs(s, &substs)); if metadata.ignore || !should_run(if_cond.as_deref()) { TestResult::Ignored } else if let Some(repeat) = metadata.repeat { for _ in 0..repeat { let result = run_test_inner( test, &metadata, &cwd, diagnostic_logger.clone(), flaky_test_tracker, parallelism, ); if result.is_failed() { return result; } } TestResult::Passed { duration: None } } else { run_test_inner( test, &metadata, &cwd, diagnostic_logger.clone(), flaky_test_tracker, parallelism, ) } })); match result { TestResult::Failed { duration, output: panic_output, } => { let mut output = diagnostic_logger.borrow().clone(); output.push(b'\n'); output.extend(panic_output); TestResult::Failed { duration, output } } TestResult::Passed { .. } | TestResult::Ignored | TestResult::SubTests { .. } => result, } } fn run_test_inner( test: &CollectedTest<serde_json::Value>, metadata: &MultiStepMetaData, cwd: &PathRef, diagnostic_logger: Rc<RefCell<Vec<u8>>>, flaky_test_tracker: &FlakyTestTracker, parallelism: &Parallelism, ) -> TestResult { let run_fn = || { let context = test_context_from_metadata(metadata, cwd, diagnostic_logger.clone()); for step in metadata .steps .iter() .filter(|s| should_run(s.if_cond.as_deref())) { let run_func = || { TestResult::from_maybe_panic_or_result(AssertUnwindSafe(|| { run_step(step, metadata, cwd, &context); TestResult::Passed { duration: None } })) }; let result = run_maybe_flaky_test( &test.name, step.flaky, flaky_test_tracker, None, run_func, ); if result.is_failed() { return result; } } TestResult::Passed { duration: None } }; run_maybe_flaky_test( &test.name, metadata.flaky || *IS_CI, flaky_test_tracker, Some(parallelism), run_fn, ) } fn deserialize_value(metadata_value: serde_json::Value) -> MultiStepMetaData { let metadata_string = metadata_value.to_string(); // checking for "steps" leads to a more targeted error message // instead of when deserializing an untagged enum if metadata_value .as_object() .map(|o| o.contains_key("steps")) .unwrap_or(false) { serde_json::from_value::<MultiStepMetaData>(metadata_value) } else { serde_json::from_value::<SingleTestMetaData>(metadata_value) .map(|s| s.into_multi()) } .with_context(|| format!("Failed to parse test spec: {}", metadata_string)) .unwrap() } fn test_context_from_metadata( metadata: &MultiStepMetaData, cwd: &PathRef, diagnostic_logger: Rc<RefCell<Vec<u8>>>, ) -> test_util::TestContext { let mut builder = TestContextBuilder::new(); builder = builder.logging_capture(diagnostic_logger); if metadata.temp_dir { builder = builder.use_temp_cwd(); } else { builder = builder.cwd(cwd.to_string_lossy()); } if metadata.canonicalized_temp_dir { // not actually deprecated, we just want to discourage its use #[allow(deprecated)] { builder = builder.use_canonicalized_temp_dir(); } } if metadata.symlinked_temp_dir { // not actually deprecated, we just want to discourage its use // because it's mostly used for testing purposes locally #[allow(deprecated)] { builder = builder.use_symlinked_temp_dir(); } if cfg!(not(debug_assertions)) { // panic to prevent using this on the CI as CI already uses // a symlinked temp directory for every test panic!("Cannot use symlinkedTempDir in release mode"); } } match &metadata.base { // todo(dsherret): add bases in the future as needed Some(base) => panic!("Unknown test base: {}", base), None => { // by default add all these builder = builder .add_jsr_env_vars() .add_npm_env_vars() .add_compile_env_vars(); } } let context = builder.build(); if metadata.temp_dir { // copy all the files in the cwd to a temp directory // excluding the metadata and assertion files let temp_dir = context.temp_dir().path(); let assertion_paths = resolve_test_and_assertion_files(cwd, metadata); cwd.copy_to_recursive_with_exclusions(temp_dir, &assertion_paths); } context } fn should_run(if_cond: Option<&str>) -> bool { if let Some(cond) = if_cond { match cond { "windows" => cfg!(windows), "unix" => cfg!(unix), "mac" => cfg!(target_os = "macos"), "linux" => cfg!(target_os = "linux"), "notCI" => std::env::var_os("CI").is_none(), "notMacIntel" => { cfg!(unix) && !(cfg!(target_os = "macos") && cfg!(target_arch = "x86_64")) } value => panic!("Unknown if condition: {}", value), } } else { true } } fn run_step( step: &StepMetaData, metadata: &MultiStepMetaData, cwd: &PathRef, context: &test_util::TestContext, ) { let substs = variant_substitutions(&step.variants, &metadata.variants); let command = if substs.is_empty() { let envs = metadata.envs.iter().chain(step.envs.iter()); context.new_command().envs(envs) } else { let mut envs = metadata .envs .iter() .chain(step.envs.iter()) .map(|(key, value)| (key.clone(), value.clone())) .collect::<HashMap<_, _>>(); substitute_variants_into_envs(&substs, &mut envs); context.new_command().envs(envs) }; let command = match &step.args { VecOrString::Vec(args) => { if substs.is_empty() { command.args_vec(args) } else { let mut args_replaced = args.clone(); for arg in args { for (from, to) in &substs { let arg_replaced = arg.replace(from, to); if arg_replaced.is_empty() && &arg_replaced != arg { continue; } args_replaced.push(arg_replaced); } } command.args_vec(args) } } VecOrString::String(text) => { if substs.is_empty() { command.args(text) } else { let text = apply_substs(text, &substs); command.args(text.as_ref()) } } }; let command = match step.cwd.as_ref().or(metadata.cwd.as_ref()) { Some(cwd) => command.current_dir(cwd), None => command, }; let command = match &step.command_name { Some(command_name) => { if substs.is_empty() { command.name(command_name) } else { let command_name = apply_substs(command_name, &substs); command.name(command_name.as_ref()) } } None => command, }; let command = match *NO_CAPTURE { // deprecated is only to prevent use, so this is fine here #[allow(deprecated)] true => command.show_output(), false => command, }; let command = match &step.input { Some(input) => { if input.ends_with(".in") { let test_input_path = cwd.join(input); command.stdin_text(std::fs::read_to_string(test_input_path).unwrap()) } else { command.stdin_text(input) } } None => command, }; let output = command.run(); let step_output = { if substs.is_empty() { step.output.clone() } else { let mut output = step.output.clone(); for (from, to) in substs { output = output.replace(&from, &to); } output } }; if step_output.ends_with(".out") { let test_output_path = cwd.join(&step_output); output.assert_matches_file(test_output_path); } else { assert!( step_output.len() <= 160, "The \"output\" property in your __test__.jsonc file is too long. Please extract this to an `.out` file to improve readability." ); output.assert_matches_text(&step_output); } output.assert_exit_code(step.exit_code); } fn resolve_test_and_assertion_files( dir: &PathRef, metadata: &MultiStepMetaData, ) -> HashSet<PathRef> { let mut result = HashSet::with_capacity(metadata.steps.len() + 1); result.insert(dir.join(MANIFEST_FILE_NAME)); result.extend(metadata.steps.iter().map(|step| dir.join(&step.output))); result } fn map_variants<'a, I>( test_data: &serde_json::Value, test_path: &Path, test_name: &str, variants: I, ) -> Result<CollectedCategoryOrTest<serde_json::Value>, CollectTestsError> where I: IntoIterator<Item = (&'a String, &'a serde_json::Value)>, { let mut children = Vec::with_capacity(2); for (variant_name, variant_data) in variants { let mut child_data = test_data.clone(); let child_obj = child_data .as_object_mut() .unwrap() .get_mut("variants") .unwrap() .as_object_mut() .unwrap(); child_obj.clear(); child_obj.insert(variant_name.clone(), variant_data.clone()); children.push(CollectedCategoryOrTest::Test(CollectedTest { name: format!("{}::{}", test_name, variant_name), path: test_path.to_path_buf(), line_and_column: None, data: child_data, })); } Ok(CollectedCategoryOrTest::Category(CollectedTestCategory { children, name: test_name.to_string(), path: test_path.to_path_buf(), })) } /// Maps a __test__.jsonc file to a category of tests if it contains a "test" object. fn map_test_within_file( test: CollectedTest, ) -> Result<CollectedCategoryOrTest<serde_json::Value>, CollectTestsError> { let test_path = PathRef::new(&test.path); let metadata_value = test_path.read_jsonc_value(); if metadata_value .as_object() .map(|o| o.contains_key("tests")) .unwrap_or(false) { let data: MultiTestMetaData = serde_json::from_value(metadata_value) .with_context(|| format!("Failed deserializing {}", test_path)) .map_err(CollectTestsError::Other)?; Ok(CollectedCategoryOrTest::Category(CollectedTestCategory { children: data.into_collected_tests(&test), name: test.name, path: test.path, })) } else if let Some(variants) = metadata_value .as_object() .and_then(|o| o.get("variants")) .and_then(|v| v.as_object()) && !variants.is_empty() { map_variants(&metadata_value, &test.path, &test.name, variants.iter()) } else { Ok(CollectedCategoryOrTest::Test(CollectedTest { name: test.name, path: test.path, line_and_column: None, data: metadata_value, })) } } // in the future we could consider using https://docs.rs/aho_corasick to do multiple replacements at once // in practice, though, i suspect the numbers here will be small enough that the naive approach is fast enough fn variant_substitutions( variants: &BTreeMap<String, JsonMap>, multi_step_variants: &BTreeMap<String, JsonMap>, ) -> Vec<(String, String)> { if variants.is_empty() && multi_step_variants.is_empty() { return Vec::new(); } let mut variant = variants.values().next().cloned().unwrap_or_default(); let multi_step_variant = multi_step_variants .values() .next() .cloned() .unwrap_or_default(); for (name, value) in multi_step_variant { if !variant.contains_key(&name) { variant.insert(name, value.clone()); } } let mut pairs = variant .into_iter() .filter_map(|(name, value)| { value .as_str() .map(|value| (format!("${{{}}}", name), value.to_string())) }) .collect::<Vec<_>>(); pairs.sort_by(|a, b| a.0.cmp(&b.0).reverse()); pairs } fn substitute_variants_into_envs( pairs: &Vec<(String, String)>, envs: &mut HashMap<String, String>, ) { let mut to_remove = Vec::new(); for (key, value) in pairs { for (k, v) in envs.iter_mut() { let replaced = v.replace(key.as_str(), value); if replaced.is_empty() && &replaced != v { to_remove.push(k.clone()); continue; } *v = replaced; } } for key in to_remove { envs.remove(&key); } } fn apply_substs<'a>( text: &'a str, substs: &'_ [(String, String)], ) -> Cow<'a, str> { if substs.is_empty() { Cow::Borrowed(text) } else { let mut text = Cow::Borrowed(text); for (from, to) in substs { text = text.replace(from, to).into(); } text } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/tests/specs/node/child_process_extra_pipes/test-pipe/src/main.rs
tests/specs/node/child_process_extra_pipes/test-pipe/src/main.rs
use std::fs::File; use std::io::prelude::*; use std::os::fd::FromRawFd; fn main() { #[cfg(unix)] { let mut pipe = unsafe { File::from_raw_fd(4) }; let mut read = 0; let mut buf = [0u8; 1024]; loop { if read > 4 { assert_eq!(&buf[..5], b"start"); break; } match pipe.read(&mut buf) { Ok(n) => { read += n; } Ok(0) => { return; } Err(e) => { eprintln!("GOT ERROR: {e:?}"); } } } pipe.write_all(b"hello world").unwrap(); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/coverage.rs
runtime/coverage.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::fs; use std::fs::File; use std::io::BufWriter; use std::io::Write; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicI32; use deno_core::InspectorSessionKind; use deno_core::JsRuntime; use deno_core::JsRuntimeInspector; use deno_core::LocalInspectorSession; use deno_core::error::CoreError; use deno_core::parking_lot::Mutex; use deno_core::serde_json; use deno_core::url::Url; use uuid::Uuid; static NEXT_MSG_ID: AtomicI32 = AtomicI32::new(0); fn next_msg_id() -> i32 { NEXT_MSG_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } #[derive(Debug)] pub struct CoverageCollectorInner { dir: PathBuf, coverage_msg_id: Option<i32>, } #[derive(Clone, Debug)] pub struct CoverageCollectorState(Arc<Mutex<CoverageCollectorInner>>); impl CoverageCollectorState { pub fn new(dir: PathBuf) -> Self { Self(Arc::new(Mutex::new(CoverageCollectorInner { dir, coverage_msg_id: None, }))) } pub fn callback(&self, msg: deno_core::InspectorMsg) { let deno_core::InspectorMsgKind::Message(msg_id) = msg.kind else { return; }; let maybe_coverage_msg_id = self.0.lock().coverage_msg_id.as_ref().cloned(); if let Some(coverage_msg_id) = maybe_coverage_msg_id && coverage_msg_id == msg_id { let message: serde_json::Value = serde_json::from_str(&msg.content).unwrap(); let coverages: cdp::TakePreciseCoverageResponse = serde_json::from_value(message["result"].clone()).unwrap(); self.write_coverages(coverages.result); } } fn write_coverages(&self, script_coverages: Vec<cdp::ScriptCoverage>) { for script_coverage in script_coverages { // Filter out internal and http/https JS files, eval'd scripts, // and scripts with invalid urls from being included in coverage reports if script_coverage.url.is_empty() || script_coverage.url.starts_with("ext:") || script_coverage.url.starts_with("[ext:") || script_coverage.url.starts_with("http:") || script_coverage.url.starts_with("https:") || script_coverage.url.starts_with("node:") || Url::parse(&script_coverage.url).is_err() { continue; } let filename = format!("{}.json", Uuid::new_v4()); let filepath = self.0.lock().dir.join(filename); let file = match File::create(&filepath) { Ok(f) => f, Err(err) => { log::error!( "Failed to create coverage file at {:?}, reason: {:?}", filepath, err ); continue; } }; let mut out = BufWriter::new(file); let coverage = serde_json::to_string_pretty(&script_coverage).unwrap(); if let Err(err) = out.write_all(coverage.as_bytes()) { log::error!( "Failed to write coverage file at {:?}, reason: {:?}", filepath, err ); continue; } if let Err(err) = out.flush() { log::error!( "Failed to flush coverage file at {:?}, reason: {:?}", filepath, err ); continue; } } } } pub struct CoverageCollector { pub state: CoverageCollectorState, session: LocalInspectorSession, } impl CoverageCollector { pub fn new(js_runtime: &mut JsRuntime, coverage_dir: PathBuf) -> Self { let state = CoverageCollectorState::new(coverage_dir); js_runtime.maybe_init_inspector(); let insp = js_runtime.inspector(); let s = state.clone(); let callback = Box::new(move |message| s.clone().callback(message)); let session = JsRuntimeInspector::create_local_session( insp, callback, InspectorSessionKind::Blocking, ); Self { state, session } } pub fn start_collecting(&mut self) { self .session .post_message::<()>(next_msg_id(), "Profiler.enable", None); self.session.post_message( next_msg_id(), "Profiler.startPreciseCoverage", Some(cdp::StartPreciseCoverageArgs { call_count: true, detailed: true, allow_triggered_updates: false, }), ); } #[allow(clippy::disallowed_methods)] pub fn stop_collecting(&mut self) -> Result<(), CoreError> { fs::create_dir_all(&self.state.0.lock().dir)?; let msg_id = next_msg_id(); self.state.0.lock().coverage_msg_id.replace(msg_id); self.session.post_message::<()>( msg_id, "Profiler.takePreciseCoverage", None, ); Ok(()) } } mod cdp { use serde::Deserialize; use serde::Serialize; /// <https://chromedevtools.github.io/devtools-protocol/tot/Profiler/#method-takePreciseCoverage> #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TakePreciseCoverageResponse { pub result: Vec<ScriptCoverage>, pub timestamp: f64, } /// <https://chromedevtools.github.io/devtools-protocol/tot/Profiler/#type-CoverageRange> #[derive(Debug, Eq, PartialEq, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct CoverageRange { /// Start character index. #[serde(rename = "startOffset")] pub start_char_offset: usize, /// End character index. #[serde(rename = "endOffset")] pub end_char_offset: usize, pub count: i64, } /// <https://chromedevtools.github.io/devtools-protocol/tot/Profiler/#type-FunctionCoverage> #[derive(Debug, Eq, PartialEq, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct FunctionCoverage { pub function_name: String, pub ranges: Vec<CoverageRange>, pub is_block_coverage: bool, } /// <https://chromedevtools.github.io/devtools-protocol/tot/Profiler/#type-ScriptCoverage> #[derive(Debug, Eq, PartialEq, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct ScriptCoverage { pub script_id: String, pub url: String, pub functions: Vec<FunctionCoverage>, } /// <https://chromedevtools.github.io/devtools-protocol/tot/Profiler/#method-startPreciseCoverage> #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct StartPreciseCoverageArgs { pub call_count: bool, pub detailed: bool, pub allow_triggered_updates: bool, } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/lib.rs
runtime/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. pub use deno_cache; pub use deno_canvas; pub use deno_core; pub use deno_cron; pub use deno_crypto; pub use deno_fetch; pub use deno_ffi; pub use deno_fs; pub use deno_http; pub use deno_io; pub use deno_kv; pub use deno_napi; pub use deno_net; pub use deno_node; pub use deno_os; pub use deno_permissions; pub use deno_process; pub use deno_telemetry; pub use deno_terminal::colors; pub use deno_tls; pub use deno_web; pub use deno_webgpu; pub use deno_webidl; pub use deno_websocket; pub use deno_webstorage; pub mod code_cache; pub mod coverage; pub mod fmt_errors; pub mod inspector_server; pub mod js; pub mod ops; pub mod permissions; #[cfg(feature = "snapshot")] pub mod snapshot; pub mod snapshot_info; pub mod tokio_util; #[cfg(feature = "transpile")] pub mod transpile; pub mod web_worker; pub mod worker; mod worker_bootstrap; pub use worker::UnconfiguredRuntime; pub use worker::UnconfiguredRuntimeOptions; pub use worker_bootstrap::BootstrapOptions; pub use worker_bootstrap::WorkerExecutionMode; pub use worker_bootstrap::WorkerLogLevel; pub mod shared; pub use deno_features::FeatureChecker; pub use deno_features::UNSTABLE_ENV_VAR_NAMES; pub use deno_features::UNSTABLE_FEATURES; pub use deno_features::UnstableFeatureKind; pub use deno_os::exit; pub use shared::runtime;
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/permissions.rs
runtime/permissions.rs
// Copyright 2018-2025 the Deno authors. MIT license. pub use deno_permissions::RuntimePermissionDescriptorParser;
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/fmt_errors.rs
runtime/fmt_errors.rs
// Copyright 2018-2025 the Deno authors. MIT license. //! This mod provides DenoError to unify errors across Deno. use std::borrow::Cow; use std::fmt::Write as _; use std::sync::LazyLock; use color_print::cformat; use color_print::cstr; use deno_core::error::JsError; use deno_core::error::format_frame; use deno_core::url::Url; use deno_terminal::colors; #[derive(Debug, Clone)] struct ErrorReference<'a> { from: &'a JsError, to: &'a JsError, } #[derive(Debug, Clone)] struct IndexedErrorReference<'a> { reference: ErrorReference<'a>, index: usize, } #[derive(Debug)] enum FixSuggestionKind { Info, Hint, Docs, } #[derive(Debug)] enum FixSuggestionMessage<'a> { Single(&'a str), Multiline(&'a [&'a str]), } #[derive(Debug)] pub struct FixSuggestion<'a> { kind: FixSuggestionKind, message: FixSuggestionMessage<'a>, } impl<'a> FixSuggestion<'a> { pub fn info(message: &'a str) -> Self { Self { kind: FixSuggestionKind::Info, message: FixSuggestionMessage::Single(message), } } pub fn info_multiline(messages: &'a [&'a str]) -> Self { Self { kind: FixSuggestionKind::Info, message: FixSuggestionMessage::Multiline(messages), } } pub fn hint(message: &'a str) -> Self { Self { kind: FixSuggestionKind::Hint, message: FixSuggestionMessage::Single(message), } } pub fn hint_multiline(messages: &'a [&'a str]) -> Self { Self { kind: FixSuggestionKind::Hint, message: FixSuggestionMessage::Multiline(messages), } } pub fn docs(url: &'a str) -> Self { Self { kind: FixSuggestionKind::Docs, message: FixSuggestionMessage::Single(url), } } } struct AnsiColors; impl deno_core::error::ErrorFormat for AnsiColors { fn fmt_element( element: deno_core::error::ErrorElement, in_extension_code: bool, s: &str, ) -> std::borrow::Cow<'_, str> { if in_extension_code { return colors::dimmed_gray(s).to_string().into(); } use deno_core::error::ErrorElement::*; match element { Anonymous | NativeFrame | FileName | EvalOrigin => { colors::cyan(s).to_string().into() } LineNumber | ColumnNumber => colors::yellow(s).to_string().into(), FunctionName | PromiseAll => colors::italic_bold(s).to_string().into(), WorkingDirPath => colors::dimmed_gray(s).to_string().into(), PlainText => s.into(), } } } /// Take an optional source line and associated information to format it into /// a pretty printed version of that line. fn format_maybe_source_line( source_line: Option<&str>, column_number: Option<i64>, is_error: bool, level: usize, ) -> String { if source_line.is_none() || column_number.is_none() { return "".to_string(); } let source_line = source_line.unwrap(); // sometimes source_line gets set with an empty string, which then outputs // an empty source line when displayed, so need just short circuit here. if source_line.is_empty() { return "".to_string(); } if source_line.contains("Couldn't format source line: ") { return format!("\n{source_line}"); } let mut s = String::new(); let column_number = column_number.unwrap(); if column_number as usize > source_line.len() { return format!( "\n{} Couldn't format source line: Column {} is out of bounds (source may have changed at runtime)", colors::yellow("Warning"), column_number, ); } for _i in 0..(column_number - 1) { if source_line.chars().nth(_i as usize).unwrap() == '\t' { s.push('\t'); } else { s.push(' '); } } s.push('^'); let color_underline = if is_error { colors::red(&s).to_string() } else { colors::cyan(&s).to_string() }; let indent = format!("{:indent$}", "", indent = level); format!("\n{indent}{source_line}\n{indent}{color_underline}") } fn find_recursive_cause(js_error: &JsError) -> Option<ErrorReference<'_>> { let mut history = Vec::<&JsError>::new(); let mut current_error: &JsError = js_error; while let Some(cause) = &current_error.cause { history.push(current_error); if let Some(seen) = history.iter().find(|&el| cause.is_same_error(el)) { return Some(ErrorReference { from: current_error, to: seen, }); } else { current_error = cause; } } None } fn format_aggregated_error( aggregated_errors: &Vec<JsError>, circular_reference_index: usize, initial_cwd: Option<&Url>, filter_frames: bool, ) -> String { let mut s = String::new(); let mut nested_circular_reference_index = circular_reference_index; for js_error in aggregated_errors { let aggregated_circular = find_recursive_cause(js_error); if aggregated_circular.is_some() { nested_circular_reference_index += 1; } let error_string = format_js_error_inner( js_error, aggregated_circular.map(|reference| IndexedErrorReference { reference, index: nested_circular_reference_index, }), false, filter_frames, vec![], initial_cwd, ); for line in error_string.trim_start_matches("Uncaught ").lines() { write!(s, "\n {line}").unwrap(); } } s } fn stack_frame_is_ext(frame: &deno_core::error::JsStackFrame) -> bool { frame .file_name .as_ref() .map(|file_name| { file_name.starts_with("ext:") || file_name.starts_with("node:") }) .unwrap_or(false) } fn format_js_error_inner( js_error: &JsError, circular: Option<IndexedErrorReference>, include_source_code: bool, filter_frames: bool, suggestions: Vec<FixSuggestion>, initial_cwd: Option<&Url>, ) -> String { let mut s = String::new(); s.push_str(&js_error.exception_message); if let Some(circular) = &circular && js_error.is_same_error(circular.reference.to) { write!(s, " {}", colors::cyan(format!("<ref *{}>", circular.index))) .unwrap(); } if let Some(aggregated) = &js_error.aggregated { let aggregated_message = format_aggregated_error( aggregated, circular .as_ref() .map(|circular| circular.index) .unwrap_or(0), initial_cwd, filter_frames, ); s.push_str(&aggregated_message); } let column_number = js_error .source_line_frame_index .and_then(|i| js_error.frames.get(i).unwrap().column_number); s.push_str(&format_maybe_source_line( if include_source_code { js_error.source_line.as_deref() } else { None }, column_number, true, 0, )); let at_dimmed = Cow::Owned(colors::dimmed_gray("at ").to_string()); let at_normal = Cow::Borrowed("at "); for frame in &js_error.frames { let is_ext = stack_frame_is_ext(frame); if filter_frames && is_ext && let Some(fn_name) = &frame.function_name && (fn_name.starts_with("__node_internal_") || fn_name == "eventLoopTick" || fn_name == "denoErrorToNodeError") { continue; } write!( s, "\n {}{}", if is_ext { &at_dimmed } else { &at_normal }, format_frame::<AnsiColors>(frame, initial_cwd) ) .unwrap(); } if let Some(cause) = &js_error.cause { let is_caused_by_circular = circular .as_ref() .map(|circular| js_error.is_same_error(circular.reference.from)) .unwrap_or(false); let error_string = if is_caused_by_circular { colors::cyan(format!("[Circular *{}]", circular.unwrap().index)) .to_string() } else { format_js_error_inner(cause, circular, false, false, vec![], initial_cwd) }; write!( s, "\nCaused by: {}", error_string.trim_start_matches("Uncaught ") ) .unwrap(); } if !suggestions.is_empty() { write!(s, "\n\n").unwrap(); for (index, suggestion) in suggestions.iter().enumerate() { write!(s, " ").unwrap(); match suggestion.kind { FixSuggestionKind::Hint => { write!(s, "{} ", colors::cyan("hint:")).unwrap() } FixSuggestionKind::Info => { write!(s, "{} ", colors::yellow("info:")).unwrap() } FixSuggestionKind::Docs => { write!(s, "{} ", colors::green("docs:")).unwrap() } }; match suggestion.message { FixSuggestionMessage::Single(msg) => { if matches!(suggestion.kind, FixSuggestionKind::Docs) { write!(s, "{}", cformat!("<u>{}</>", msg)).unwrap(); } else { write!(s, "{}", msg).unwrap(); } } FixSuggestionMessage::Multiline(messages) => { for (idx, message) in messages.iter().enumerate() { if idx != 0 { writeln!(s).unwrap(); write!(s, " ").unwrap(); } write!(s, "{}", message).unwrap(); } } } if index != (suggestions.len() - 1) { writeln!(s).unwrap(); } } } s } fn get_suggestions_for_terminal_errors(e: &JsError) -> Vec<FixSuggestion<'_>> { if let Some(msg) = &e.message { if msg.contains("module is not defined") || msg.contains("exports is not defined") || msg.contains("require is not defined") { if let Some(file_name) = e.frames.first().and_then(|f| f.file_name.as_ref()) && (file_name.ends_with(".mjs") || file_name.ends_with(".mts")) { return vec![]; } return vec![ FixSuggestion::info_multiline(&[ cstr!( "Deno supports CommonJS modules in <u>.cjs</> files, or when the closest" ), cstr!( "<u>package.json</> has a <i>\"type\": \"commonjs\"</> option." ), ]), FixSuggestion::hint_multiline(&[ "Rewrite this module to ESM,", cstr!("or change the file extension to <u>.cjs</u>,"), cstr!( "or add <u>package.json</> next to the file with <i>\"type\": \"commonjs\"</> option," ), cstr!( "or pass <i>--unstable-detect-cjs</> flag to detect CommonJS when loading." ), ]), FixSuggestion::docs("https://docs.deno.com/go/commonjs"), ]; } else if msg.contains("__filename is not defined") { return vec![ FixSuggestion::info(cstr!( "<u>__filename</> global is not available in ES modules." )), FixSuggestion::hint(cstr!("Use <u>import.meta.filename</> instead.")), ]; } else if msg.contains("__dirname is not defined") { return vec![ FixSuggestion::info(cstr!( "<u>__dirname</> global is not available in ES modules." )), FixSuggestion::hint(cstr!("Use <u>import.meta.dirname</> instead.")), ]; } else if msg.contains("openKv is not a function") { return vec![ FixSuggestion::info("Deno.openKv() is an unstable API."), FixSuggestion::hint( "Run again with `--unstable-kv` flag to enable this API.", ), ]; } else if msg.contains("bundle is not a function") { return vec![ FixSuggestion::info("Deno.bundle() is an unstable API."), FixSuggestion::hint( "Run again with `--unstable-bundle` flag to enable this API.", ), ]; } else if msg.contains("cron is not a function") { return vec![ FixSuggestion::info("Deno.cron() is an unstable API."), FixSuggestion::hint( "Run again with `--unstable-cron` flag to enable this API.", ), ]; } else if msg.contains("WebSocketStream is not defined") { return vec![ FixSuggestion::info("new WebSocketStream() is an unstable API."), FixSuggestion::hint( "Run again with `--unstable-net` flag to enable this API.", ), ]; } else if msg.contains("Temporal is not defined") { return vec![ FixSuggestion::info("Temporal is an unstable API."), FixSuggestion::hint( "Run again with `--unstable-temporal` flag to enable this API.", ), ]; } else if msg.contains("window is not defined") { return vec![ FixSuggestion::info("window global is not available in Deno 2."), FixSuggestion::hint("Replace `window` with `globalThis`."), ]; } else if msg.contains("UnsafeWindowSurface is not a constructor") { return vec![ FixSuggestion::info("Deno.UnsafeWindowSurface is an unstable API."), FixSuggestion::hint( "Run again with `--unstable-webgpu` flag to enable this API.", ), ]; } else if msg.contains("QuicEndpoint is not a constructor") { return vec![ FixSuggestion::info("listenQuic is an unstable API."), FixSuggestion::hint( "Run again with `--unstable-net` flag to enable this API.", ), ]; } else if msg.contains("connectQuic is not a function") { return vec![ FixSuggestion::info("connectQuic is an unstable API."), FixSuggestion::hint( "Run again with `--unstable-net` flag to enable this API.", ), ]; } else if msg.contains("client error (Connect): invalid peer certificate") { return vec![FixSuggestion::hint( "Run again with the `--unsafely-ignore-certificate-errors` flag to bypass certificate errors.", )]; // Try to capture errors like: // ``` // Uncaught Error: Cannot find module '../build/Release/canvas.node' // Require stack: // - /.../deno/npm/registry.npmjs.org/canvas/2.11.2/lib/bindings.js // - /.../.cache/deno/npm/registry.npmjs.org/canvas/2.11.2/lib/canvas.js // ``` } else if msg.contains("Cannot find module") && msg.contains("Require stack") && msg.contains(".node'") { return vec![ FixSuggestion::info_multiline(&[ "Trying to execute an npm package using Node-API addons,", "these packages require local `node_modules` directory to be present.", ]), FixSuggestion::hint_multiline(&[ "Add `\"nodeModulesDir\": \"auto\" option to `deno.json`, and then run", "`deno install --allow-scripts=npm:<package> --entrypoint <script>` to setup `node_modules` directory.", ]), ]; } else if msg.contains("document is not defined") { return vec![ FixSuggestion::info(cstr!( "<u>document</> global is not available in Deno." )), FixSuggestion::hint_multiline(&[ cstr!( "Use a library like <u>happy-dom</>, <u>deno_dom</>, <u>linkedom</> or <u>JSDom</>" ), cstr!( "and setup the <u>document</> global according to the library documentation." ), ]), ]; } } vec![] } static SHOULD_FILTER_FRAMES: LazyLock<bool> = LazyLock::new(|| std::env::var("DENO_NO_FILTER_FRAMES").is_err()); /// Format a [`JsError`] for terminal output. pub fn format_js_error( js_error: &JsError, initial_cwd: Option<&Url>, ) -> String { let circular = find_recursive_cause(js_error).map(|reference| IndexedErrorReference { reference, index: 1, }); let suggestions = get_suggestions_for_terminal_errors(js_error); format_js_error_inner( js_error, circular, true, *SHOULD_FILTER_FRAMES, suggestions, initial_cwd, ) } #[cfg(test)] mod tests { use test_util::strip_ansi_codes; use super::*; #[test] fn test_format_none_source_line() { let actual = format_maybe_source_line(None, None, false, 0); assert_eq!(actual, ""); } #[test] fn test_format_some_source_line() { let actual = format_maybe_source_line(Some("console.log('foo');"), Some(9), true, 0); assert_eq!( strip_ansi_codes(&actual), "\nconsole.log(\'foo\');\n ^" ); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/code_cache.rs
runtime/code_cache.rs
// Copyright 2018-2025 the Deno authors. MIT license. use deno_core::ModuleSpecifier; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum CodeCacheType { EsModule, Script, } pub trait CodeCache: Send + Sync { fn get_sync( &self, specifier: &ModuleSpecifier, code_cache_type: CodeCacheType, source_hash: u64, ) -> Option<Vec<u8>>; fn set_sync( &self, specifier: ModuleSpecifier, code_cache_type: CodeCacheType, source_hash: u64, data: &[u8], ); }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/transpile.rs
runtime/transpile.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::path::Path; use deno_ast::MediaType; use deno_ast::ParseParams; use deno_ast::SourceMapOption; use deno_core::ModuleCodeString; use deno_core::ModuleName; use deno_core::SourceMapData; use deno_error::JsErrorBox; deno_error::js_error_wrapper!( deno_ast::ParseDiagnostic, JsParseDiagnostic, "Error" ); deno_error::js_error_wrapper!( deno_ast::TranspileError, JsTranspileError, "Error" ); pub fn maybe_transpile_source( name: ModuleName, source: ModuleCodeString, ) -> Result<(ModuleCodeString, Option<SourceMapData>), JsErrorBox> { // Always transpile `node:` built-in modules, since they might be TypeScript. let media_type = if name.starts_with("node:") { MediaType::TypeScript } else { MediaType::from_path(Path::new(&name)) }; match media_type { MediaType::TypeScript => {} MediaType::JavaScript => return Ok((source, None)), MediaType::Mjs => return Ok((source, None)), _ => panic!( "Unsupported media type for snapshotting {media_type:?} for file {}", name ), } let parsed = deno_ast::parse_module(ParseParams { specifier: deno_core::url::Url::parse(&name).unwrap(), text: source.into(), media_type, capture_tokens: false, scope_analysis: false, maybe_syntax: None, }) .map_err(|e| JsErrorBox::from_err(JsParseDiagnostic(e)))?; let transpiled_source = parsed .transpile( &deno_ast::TranspileOptions { imports_not_used_as_values: deno_ast::ImportsNotUsedAsValues::Remove, ..Default::default() }, &deno_ast::TranspileModuleOptions::default(), &deno_ast::EmitOptions { source_map: if cfg!(debug_assertions) { SourceMapOption::Separate } else { SourceMapOption::None }, ..Default::default() }, ) .map_err(|e| JsErrorBox::from_err(JsTranspileError(e)))? .into_source(); let maybe_source_map: Option<SourceMapData> = transpiled_source .source_map .map(|sm| sm.into_bytes().into()); let source_text = transpiled_source.text; Ok((source_text.into(), maybe_source_map)) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/worker.rs
runtime/worker.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; #[cfg(target_os = "linux")] use std::sync::LazyLock; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::time::Duration; use std::time::Instant; use deno_cache::CacheImpl; use deno_cache::CreateCache; use deno_cache::SqliteBackedCache; use deno_core::CompiledWasmModuleStore; use deno_core::Extension; use deno_core::InspectorSessionKind; use deno_core::JsRuntime; use deno_core::JsRuntimeInspector; use deno_core::LocalInspectorSession; use deno_core::ModuleCodeString; use deno_core::ModuleId; use deno_core::ModuleLoadOptions; use deno_core::ModuleLoadReferrer; use deno_core::ModuleLoader; use deno_core::ModuleSpecifier; use deno_core::OpMetricsFactoryFn; use deno_core::OpMetricsSummaryTracker; use deno_core::PollEventLoopOptions; use deno_core::RuntimeOptions; use deno_core::SharedArrayBufferStore; use deno_core::SourceCodeCacheInfo; use deno_core::error::CoreError; use deno_core::error::JsError; use deno_core::merge_op_metrics; use deno_core::v8; use deno_cron::local::LocalCronHandler; use deno_fs::FileSystem; use deno_io::Stdio; use deno_kv::dynamic::MultiBackendDbHandler; use deno_napi::DenoRtNativeAddonLoaderRc; use deno_node::ExtNodeSys; use deno_node::NodeExtInitServices; use deno_os::ExitCode; use deno_permissions::PermissionsContainer; use deno_process::NpmProcessStateProviderRc; use deno_tls::RootCertStoreProvider; use deno_tls::TlsKeys; use deno_web::BlobStore; use deno_web::InMemoryBroadcastChannel; use log::debug; use node_resolver::InNpmPackageChecker; use node_resolver::NpmPackageFolderResolver; use crate::BootstrapOptions; use crate::FeatureChecker; use crate::code_cache::CodeCache; use crate::code_cache::CodeCacheType; use crate::inspector_server::InspectorServer; use crate::ops; use crate::shared::runtime; pub type FormatJsErrorFn = dyn Fn(&JsError) -> String + Sync + Send; #[cfg(target_os = "linux")] pub(crate) static MEMORY_TRIM_HANDLER_ENABLED: LazyLock<bool> = LazyLock::new(|| std::env::var_os("DENO_USR2_MEMORY_TRIM").is_some()); #[cfg(target_os = "linux")] pub(crate) static SIGUSR2_RX: LazyLock<tokio::sync::watch::Receiver<()>> = LazyLock::new(|| { let (tx, rx) = tokio::sync::watch::channel(()); tokio::spawn(async move { let mut sigusr2 = deno_signals::signal_stream(libc::SIGUSR2).unwrap(); loop { sigusr2.recv().await; // SAFETY: calling into libc, nothing relevant on the Rust side. unsafe { libc::malloc_trim(0); } if tx.send(()).is_err() { break; } } }); rx }); // TODO(bartlomieju): temporary measurement until we start supporting more // module types pub fn create_validate_import_attributes_callback( enable_raw_imports: Arc<AtomicBool>, ) -> deno_core::ValidateImportAttributesCb { Box::new( move |scope: &mut v8::PinScope<'_, '_>, attributes: &HashMap<String, String>| { let valid_attribute = |kind: &str| { enable_raw_imports.load(Ordering::Relaxed) && matches!(kind, "bytes" | "text") || matches!(kind, "json") }; for (key, value) in attributes { let msg = if key != "type" { Some(format!("\"{key}\" attribute is not supported.")) } else if !valid_attribute(value.as_str()) { Some(format!("\"{value}\" is not a valid module type.")) } else { None }; let Some(msg) = msg else { continue; }; let message = v8::String::new(scope, &msg).unwrap(); let exception = v8::Exception::type_error(scope, message); scope.throw_exception(exception); return; } }, ) } pub fn make_wait_for_inspector_disconnect_callback() -> Box<dyn Fn()> { let has_notified_of_inspector_disconnect = AtomicBool::new(false); Box::new(move || { if !has_notified_of_inspector_disconnect .swap(true, std::sync::atomic::Ordering::SeqCst) { log::info!( "Program finished. Waiting for inspector to disconnect to exit the process..." ); } }) } /// This worker is created and used by almost all /// subcommands in Deno executable. /// /// It provides ops available in the `Deno` namespace. /// /// All `WebWorker`s created during program execution /// are descendants of this worker. pub struct MainWorker { pub js_runtime: JsRuntime, should_break_on_first_statement: bool, should_wait_for_inspector_session: bool, exit_code: ExitCode, bootstrap_fn_global: Option<v8::Global<v8::Function>>, dispatch_load_event_fn_global: v8::Global<v8::Function>, dispatch_beforeunload_event_fn_global: v8::Global<v8::Function>, dispatch_unload_event_fn_global: v8::Global<v8::Function>, dispatch_process_beforeexit_event_fn_global: v8::Global<v8::Function>, dispatch_process_exit_event_fn_global: v8::Global<v8::Function>, memory_trim_handle: Option<tokio::task::JoinHandle<()>>, } impl Drop for MainWorker { fn drop(&mut self) { if let Some(memory_trim_handle) = self.memory_trim_handle.take() { memory_trim_handle.abort(); } } } pub struct WorkerServiceOptions< TInNpmPackageChecker: InNpmPackageChecker, TNpmPackageFolderResolver: NpmPackageFolderResolver, TExtNodeSys: ExtNodeSys, > { pub blob_store: Arc<BlobStore>, pub broadcast_channel: InMemoryBroadcastChannel, pub deno_rt_native_addon_loader: Option<DenoRtNativeAddonLoaderRc>, pub feature_checker: Arc<FeatureChecker>, pub fs: Arc<dyn FileSystem>, /// Implementation of `ModuleLoader` which will be /// called when V8 requests to load ES modules. /// /// If not provided runtime will error if code being /// executed tries to load modules. pub module_loader: Rc<dyn ModuleLoader>, pub node_services: Option< NodeExtInitServices< TInNpmPackageChecker, TNpmPackageFolderResolver, TExtNodeSys, >, >, pub npm_process_state_provider: Option<NpmProcessStateProviderRc>, pub permissions: PermissionsContainer, pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>, pub fetch_dns_resolver: deno_fetch::dns::Resolver, /// The store to use for transferring SharedArrayBuffers between isolates. /// If multiple isolates should have the possibility of sharing /// SharedArrayBuffers, they should use the same [SharedArrayBufferStore]. If /// no [SharedArrayBufferStore] is specified, SharedArrayBuffer can not be /// serialized. pub shared_array_buffer_store: Option<SharedArrayBufferStore>, /// The store to use for transferring `WebAssembly.Module` objects between /// isolates. /// If multiple isolates should have the possibility of sharing /// `WebAssembly.Module` objects, they should use the same /// [CompiledWasmModuleStore]. If no [CompiledWasmModuleStore] is specified, /// `WebAssembly.Module` objects cannot be serialized. pub compiled_wasm_module_store: Option<CompiledWasmModuleStore>, /// V8 code cache for module and script source code. pub v8_code_cache: Option<Arc<dyn CodeCache>>, pub bundle_provider: Option<Arc<dyn deno_bundle_runtime::BundleProvider>>, } pub struct WorkerOptions { pub bootstrap: BootstrapOptions, /// JsRuntime extensions, not to be confused with ES modules. /// /// Extensions register "ops" and JavaScript sources provided in `js` or `esm` /// configuration. If you are using a snapshot, then extensions shouldn't /// provide JavaScript sources that were already snapshotted. pub extensions: Vec<Extension>, /// V8 snapshot that should be loaded on startup. pub startup_snapshot: Option<&'static [u8]>, /// Should op registration be skipped? pub skip_op_registration: bool, /// Optional isolate creation parameters, such as heap limits. pub create_params: Option<v8::CreateParams>, pub unsafely_ignore_certificate_errors: Option<Vec<String>>, pub seed: Option<u64>, // Callbacks invoked when creating new instance of WebWorker pub create_web_worker_cb: Arc<ops::worker_host::CreateWebWorkerCb>, pub format_js_error_fn: Option<Arc<FormatJsErrorFn>>, pub maybe_inspector_server: Option<Arc<InspectorServer>>, // If true, the worker will wait for inspector session and break on first // statement of user code. Takes higher precedence than // `should_wait_for_inspector_session`. pub should_break_on_first_statement: bool, // If true, the worker will wait for inspector session before executing // user code. pub should_wait_for_inspector_session: bool, /// If Some, print a low-level trace output for ops matching the given patterns. pub trace_ops: Option<Vec<String>>, pub cache_storage_dir: Option<std::path::PathBuf>, pub origin_storage_dir: Option<std::path::PathBuf>, pub stdio: Stdio, pub enable_raw_imports: bool, pub enable_stack_trace_arg_in_ops: bool, pub unconfigured_runtime: Option<UnconfiguredRuntime>, } impl Default for WorkerOptions { fn default() -> Self { Self { create_web_worker_cb: Arc::new(|_| { unimplemented!("web workers are not supported") }), skip_op_registration: false, seed: None, unsafely_ignore_certificate_errors: Default::default(), should_break_on_first_statement: Default::default(), should_wait_for_inspector_session: Default::default(), trace_ops: Default::default(), maybe_inspector_server: Default::default(), format_js_error_fn: Default::default(), origin_storage_dir: Default::default(), cache_storage_dir: Default::default(), extensions: Default::default(), startup_snapshot: Default::default(), create_params: Default::default(), bootstrap: Default::default(), stdio: Default::default(), enable_raw_imports: false, enable_stack_trace_arg_in_ops: false, unconfigured_runtime: None, } } } pub fn create_op_metrics( enable_op_summary_metrics: bool, trace_ops: Option<Vec<String>>, ) -> ( Option<Rc<OpMetricsSummaryTracker>>, Option<OpMetricsFactoryFn>, ) { let mut op_summary_metrics = None; let mut op_metrics_factory_fn: Option<OpMetricsFactoryFn> = None; let now = Instant::now(); let max_len: Rc<std::cell::Cell<usize>> = Default::default(); if let Some(patterns) = trace_ops { /// Match an op name against a list of patterns fn matches_pattern(patterns: &[String], name: &str) -> bool { let mut found_match = false; let mut found_nomatch = false; for pattern in patterns.iter() { if let Some(pattern) = pattern.strip_prefix('-') { if name.contains(pattern) { return false; } } else if name.contains(pattern.as_str()) { found_match = true; } else { found_nomatch = true; } } found_match || !found_nomatch } op_metrics_factory_fn = Some(Box::new(move |_, _, decl| { // If we don't match a requested pattern, or we match a negative pattern, bail if !matches_pattern(&patterns, decl.name) { return None; } max_len.set(max_len.get().max(decl.name.len())); let max_len = max_len.clone(); Some(Rc::new( #[allow(clippy::print_stderr)] move |op: &deno_core::_ops::OpCtx, event, source| { eprintln!( "[{: >10.3}] {name:max_len$}: {event:?} {source:?}", now.elapsed().as_secs_f64(), name = op.decl().name, max_len = max_len.get() ); }, )) })); } if enable_op_summary_metrics { let summary = Rc::new(OpMetricsSummaryTracker::default()); let summary_metrics = summary.clone().op_metrics_factory_fn(|_| true); op_metrics_factory_fn = Some(match op_metrics_factory_fn { Some(f) => merge_op_metrics(f, summary_metrics), None => summary_metrics, }); op_summary_metrics = Some(summary); } (op_summary_metrics, op_metrics_factory_fn) } impl MainWorker { pub fn bootstrap_from_options< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TExtNodeSys: ExtNodeSys + 'static, >( main_module: &ModuleSpecifier, services: WorkerServiceOptions< TInNpmPackageChecker, TNpmPackageFolderResolver, TExtNodeSys, >, options: WorkerOptions, ) -> Self { let (mut worker, bootstrap_options) = Self::from_options(main_module, services, options); worker.bootstrap(bootstrap_options); worker } fn from_options< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TExtNodeSys: ExtNodeSys + 'static, >( main_module: &ModuleSpecifier, services: WorkerServiceOptions< TInNpmPackageChecker, TNpmPackageFolderResolver, TExtNodeSys, >, mut options: WorkerOptions, ) -> (Self, BootstrapOptions) { fn create_cache_inner(options: &WorkerOptions) -> Option<CreateCache> { if let Ok(var) = std::env::var("DENO_CACHE_LSC_ENDPOINT") { let elems: Vec<_> = var.split(",").collect(); if elems.len() == 2 { let endpoint = elems[0]; let token = elems[1]; use deno_cache::CacheShard; let shard = Rc::new(CacheShard::new(endpoint.to_string(), token.to_string())); let create_cache_fn = move || { let x = deno_cache::LscBackend::default(); x.set_shard(shard.clone()); Ok(CacheImpl::Lsc(x)) }; #[allow(clippy::arc_with_non_send_sync)] return Some(CreateCache(Arc::new(create_cache_fn))); } } if let Some(storage_dir) = &options.cache_storage_dir { let storage_dir = storage_dir.clone(); let create_cache_fn = move || { let s = SqliteBackedCache::new(storage_dir.clone())?; Ok(CacheImpl::Sqlite(s)) }; return Some(CreateCache(Arc::new(create_cache_fn))); } None } let create_cache = create_cache_inner(&options); // Get our op metrics let (op_summary_metrics, op_metrics_factory_fn) = create_op_metrics( options.bootstrap.enable_op_summary_metrics, options.trace_ops, ); // Permissions: many ops depend on this let enable_testing_features = options.bootstrap.enable_testing_features; let exit_code = ExitCode::default(); // check options that require configuring a new jsruntime if options.unconfigured_runtime.is_some() && (options.enable_stack_trace_arg_in_ops || op_metrics_factory_fn.is_some()) { options.unconfigured_runtime = None; } #[cfg(feature = "hmr")] const { assert!( cfg!(not(feature = "only_snapshotted_js_sources")), "'hmr' is incompatible with 'only_snapshotted_js_sources'." ); } #[cfg(feature = "only_snapshotted_js_sources")] options.startup_snapshot.as_ref().expect("A user snapshot was not provided, even though 'only_snapshotted_js_sources' is used."); let mut js_runtime = if let Some(u) = options.unconfigured_runtime { u.hydrate(services.module_loader) } else { let mut extensions = common_extensions::< TInNpmPackageChecker, TNpmPackageFolderResolver, TExtNodeSys, >(options.startup_snapshot.is_some(), false); extensions.extend(std::mem::take(&mut options.extensions)); common_runtime(CommonRuntimeOptions { module_loader: services.module_loader.clone(), startup_snapshot: options.startup_snapshot, create_params: options.create_params, skip_op_registration: options.skip_op_registration, shared_array_buffer_store: services.shared_array_buffer_store, compiled_wasm_module_store: services.compiled_wasm_module_store, extensions, op_metrics_factory_fn, enable_stack_trace_arg_in_ops: options.enable_stack_trace_arg_in_ops, }) }; js_runtime .set_eval_context_code_cache_cbs(services.v8_code_cache.map(|cache| { let cache_clone = cache.clone(); ( Box::new(move |specifier: &ModuleSpecifier, code: &v8::String| { let source_hash = { use std::hash::Hash; use std::hash::Hasher; let mut hasher = twox_hash::XxHash64::default(); code.hash(&mut hasher); hasher.finish() }; let data = cache .get_sync(specifier, CodeCacheType::Script, source_hash) .inspect(|_| { // This log line is also used by tests. log::debug!( "V8 code cache hit for script: {specifier}, [{source_hash}]" ); }) .map(Cow::Owned); Ok(SourceCodeCacheInfo { data, hash: source_hash, }) }) as Box<dyn Fn(&_, &_) -> _>, Box::new( move |specifier: ModuleSpecifier, source_hash: u64, data: &[u8]| { // This log line is also used by tests. log::debug!( "Updating V8 code cache for script: {specifier}, [{source_hash}]" ); cache_clone.set_sync( specifier, CodeCacheType::Script, source_hash, data, ); }, ) as Box<dyn Fn(_, _, &_)>, ) })); js_runtime .op_state() .borrow_mut() .borrow::<EnableRawImports>() .0 .store(options.enable_raw_imports, Ordering::Relaxed); js_runtime .lazy_init_extensions(vec![ deno_web::deno_web::args( services.blob_store.clone(), options.bootstrap.location.clone(), services.broadcast_channel.clone(), ), deno_fetch::deno_fetch::args(deno_fetch::Options { user_agent: options.bootstrap.user_agent.clone(), root_cert_store_provider: services.root_cert_store_provider.clone(), unsafely_ignore_certificate_errors: options .unsafely_ignore_certificate_errors .clone(), file_fetch_handler: Rc::new(deno_fetch::FsFetchHandler), resolver: services.fetch_dns_resolver, ..Default::default() }), deno_cache::deno_cache::args(create_cache), deno_websocket::deno_websocket::args(), deno_webstorage::deno_webstorage::args( options.origin_storage_dir.clone(), ), deno_crypto::deno_crypto::args(options.seed), deno_ffi::deno_ffi::args(services.deno_rt_native_addon_loader.clone()), deno_net::deno_net::args( services.root_cert_store_provider.clone(), options.unsafely_ignore_certificate_errors.clone(), ), deno_kv::deno_kv::args( MultiBackendDbHandler::remote_or_sqlite( options.origin_storage_dir.clone(), options.seed, deno_kv::remote::HttpOptions { user_agent: options.bootstrap.user_agent.clone(), root_cert_store_provider: services .root_cert_store_provider .clone(), unsafely_ignore_certificate_errors: options .unsafely_ignore_certificate_errors .clone(), client_cert_chain_and_key: TlsKeys::Null, proxy: None, }, ), deno_kv::KvConfig::builder().build(), ), deno_napi::deno_napi::args( services.deno_rt_native_addon_loader.clone(), ), deno_http::deno_http::args(deno_http::Options { no_legacy_abort: options.bootstrap.no_legacy_abort, ..Default::default() }), deno_io::deno_io::args(Some(options.stdio)), deno_fs::deno_fs::args(services.fs.clone()), deno_os::deno_os::args(Some(exit_code.clone())), deno_process::deno_process::args(services.npm_process_state_provider), deno_node::deno_node::args::< TInNpmPackageChecker, TNpmPackageFolderResolver, TExtNodeSys, >(services.node_services, services.fs.clone()), ops::runtime::deno_runtime::args(main_module.clone()), ops::worker_host::deno_worker_host::args( options.create_web_worker_cb.clone(), options.format_js_error_fn.clone(), ), deno_bundle_runtime::deno_bundle_runtime::args( services.bundle_provider.clone(), ), ]) .unwrap(); if let Some(op_summary_metrics) = op_summary_metrics { js_runtime.op_state().borrow_mut().put(op_summary_metrics); } { let state = js_runtime.op_state(); let mut state = state.borrow_mut(); // Put inspector handle into the op state so we can put a breakpoint when // executing a CJS entrypoint. state.put(js_runtime.inspector()); state.put::<PermissionsContainer>(services.permissions); state.put(ops::TestingFeaturesEnabled(enable_testing_features)); state.put(services.feature_checker); } if let Some(server) = options.maybe_inspector_server.clone() { let inspector_url = server.register_inspector( main_module.to_string(), js_runtime.inspector(), options.should_break_on_first_statement || options.should_wait_for_inspector_session, ); js_runtime.op_state().borrow_mut().put(inspector_url); } let ( bootstrap_fn_global, dispatch_load_event_fn_global, dispatch_beforeunload_event_fn_global, dispatch_unload_event_fn_global, dispatch_process_beforeexit_event_fn_global, dispatch_process_exit_event_fn_global, ) = { let context = js_runtime.main_context(); deno_core::scope!(scope, &mut js_runtime); let context_local = v8::Local::new(scope, context); let global_obj = context_local.global(scope); let bootstrap_str = v8::String::new_external_onebyte_static(scope, b"bootstrap").unwrap(); let bootstrap_ns: v8::Local<v8::Object> = global_obj .get(scope, bootstrap_str.into()) .unwrap() .try_into() .unwrap(); let main_runtime_str = v8::String::new_external_onebyte_static(scope, b"mainRuntime").unwrap(); let bootstrap_fn = bootstrap_ns.get(scope, main_runtime_str.into()).unwrap(); let bootstrap_fn = v8::Local::<v8::Function>::try_from(bootstrap_fn).unwrap(); let dispatch_load_event_fn_str = v8::String::new_external_onebyte_static(scope, b"dispatchLoadEvent") .unwrap(); let dispatch_load_event_fn = bootstrap_ns .get(scope, dispatch_load_event_fn_str.into()) .unwrap(); let dispatch_load_event_fn = v8::Local::<v8::Function>::try_from(dispatch_load_event_fn).unwrap(); let dispatch_beforeunload_event_fn_str = v8::String::new_external_onebyte_static( scope, b"dispatchBeforeUnloadEvent", ) .unwrap(); let dispatch_beforeunload_event_fn = bootstrap_ns .get(scope, dispatch_beforeunload_event_fn_str.into()) .unwrap(); let dispatch_beforeunload_event_fn = v8::Local::<v8::Function>::try_from(dispatch_beforeunload_event_fn) .unwrap(); let dispatch_unload_event_fn_str = v8::String::new_external_onebyte_static(scope, b"dispatchUnloadEvent") .unwrap(); let dispatch_unload_event_fn = bootstrap_ns .get(scope, dispatch_unload_event_fn_str.into()) .unwrap(); let dispatch_unload_event_fn = v8::Local::<v8::Function>::try_from(dispatch_unload_event_fn).unwrap(); let dispatch_process_beforeexit_event = v8::String::new_external_onebyte_static( scope, b"dispatchProcessBeforeExitEvent", ) .unwrap(); let dispatch_process_beforeexit_event_fn = bootstrap_ns .get(scope, dispatch_process_beforeexit_event.into()) .unwrap(); let dispatch_process_beforeexit_event_fn = v8::Local::<v8::Function>::try_from( dispatch_process_beforeexit_event_fn, ) .unwrap(); let dispatch_process_exit_event = v8::String::new_external_onebyte_static( scope, b"dispatchProcessExitEvent", ) .unwrap(); let dispatch_process_exit_event_fn = bootstrap_ns .get(scope, dispatch_process_exit_event.into()) .unwrap(); let dispatch_process_exit_event_fn = v8::Local::<v8::Function>::try_from(dispatch_process_exit_event_fn) .unwrap(); ( v8::Global::new(scope, bootstrap_fn), v8::Global::new(scope, dispatch_load_event_fn), v8::Global::new(scope, dispatch_beforeunload_event_fn), v8::Global::new(scope, dispatch_unload_event_fn), v8::Global::new(scope, dispatch_process_beforeexit_event_fn), v8::Global::new(scope, dispatch_process_exit_event_fn), ) }; let worker = Self { js_runtime, should_break_on_first_statement: options.should_break_on_first_statement, should_wait_for_inspector_session: options .should_wait_for_inspector_session, exit_code, bootstrap_fn_global: Some(bootstrap_fn_global), dispatch_load_event_fn_global, dispatch_beforeunload_event_fn_global, dispatch_unload_event_fn_global, dispatch_process_beforeexit_event_fn_global, dispatch_process_exit_event_fn_global, memory_trim_handle: None, }; (worker, options.bootstrap) } pub fn bootstrap(&mut self, options: BootstrapOptions) { // Setup bootstrap options for ops. { let op_state = self.js_runtime.op_state(); let mut state = op_state.borrow_mut(); state.put(options.clone()); if let Some((fd, serialization)) = options.node_ipc_init { state.put(deno_node::ChildPipeFd(fd, serialization)); } } deno_core::scope!(scope, &mut self.js_runtime); v8::tc_scope!(scope, scope); let args = options.as_v8(scope); let bootstrap_fn = self.bootstrap_fn_global.take().unwrap(); let bootstrap_fn = v8::Local::new(scope, bootstrap_fn); let undefined = v8::undefined(scope); bootstrap_fn.call(scope, undefined.into(), &[args]); if let Some(exception) = scope.exception() { let error = JsError::from_v8_exception(scope, exception); panic!("Bootstrap exception: {error}"); } } #[cfg(not(target_os = "linux"))] pub fn setup_memory_trim_handler(&mut self) { // Noop } /// Sets up a handler that responds to SIGUSR2 signals by trimming unused /// memory and notifying V8 of low memory conditions. /// Note that this must be called within a tokio runtime. /// Calling this method multiple times will be a no-op. #[cfg(target_os = "linux")] pub fn setup_memory_trim_handler(&mut self) { if self.memory_trim_handle.is_some() { return; } if !*MEMORY_TRIM_HANDLER_ENABLED { return; } let mut sigusr2_rx = SIGUSR2_RX.clone(); let spawner = self .js_runtime .op_state() .borrow() .borrow::<deno_core::V8CrossThreadTaskSpawner>() .clone(); let memory_trim_handle = tokio::spawn(async move { loop { if sigusr2_rx.changed().await.is_err() { break; } spawner.spawn(move |isolate| { isolate.low_memory_notification(); }); } }); self.memory_trim_handle = Some(memory_trim_handle); } /// See [JsRuntime::execute_script](deno_core::JsRuntime::execute_script) pub fn execute_script( &mut self, script_name: &'static str, source_code: ModuleCodeString, ) -> Result<v8::Global<v8::Value>, Box<JsError>> { self.js_runtime.execute_script(script_name, source_code) } /// Loads and instantiates specified JavaScript module as "main" module. pub async fn preload_main_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, CoreError> { self.js_runtime.load_main_es_module(module_specifier).await } /// Loads and instantiates specified JavaScript module as "side" module. pub async fn preload_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, CoreError> { self.js_runtime.load_side_es_module(module_specifier).await } /// Executes specified JavaScript module. pub async fn evaluate_module( &mut self, id: ModuleId, ) -> Result<(), CoreError> { self.wait_for_inspector_session(); let mut receiver = self.js_runtime.mod_evaluate(id); tokio::select! { // Not using biased mode leads to non-determinism for relatively simple // programs. biased; maybe_result = &mut receiver => { debug!("received module evaluate {:#?}", maybe_result); maybe_result } event_loop_result = self.run_event_loop(false) => { event_loop_result?; receiver.await } } } /// Run the event loop up to a given duration. If the runtime resolves early, returns /// early. Will always poll the runtime at least once. pub async fn run_up_to_duration( &mut self, duration: Duration, ) -> Result<(), CoreError> { match tokio::time::timeout( duration, self .js_runtime .run_event_loop(PollEventLoopOptions::default()), ) .await { Ok(Ok(_)) => Ok(()), Err(_) => Ok(()), Ok(Err(e)) => Err(e), } } /// Loads, instantiates and executes specified JavaScript module. pub async fn execute_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), CoreError> { let id = self.preload_side_module(module_specifier).await?; self.evaluate_module(id).await } /// Loads, instantiates and executes specified JavaScript module. /// /// This module will have "import.meta.main" equal to true. pub async fn execute_main_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), CoreError> { let id = self.preload_main_module(module_specifier).await?; self.evaluate_module(id).await } fn wait_for_inspector_session(&mut self) { if self.should_break_on_first_statement { self .js_runtime .inspector() .wait_for_session_and_break_on_next_statement(); } else if self.should_wait_for_inspector_session { self.js_runtime.inspector().wait_for_session(); } } /// Create new inspector session. This function panics if Worker /// was not configured to create inspector. pub fn create_inspector_session( &mut self, cb: deno_core::InspectorSessionSend, ) -> LocalInspectorSession { self.js_runtime.maybe_init_inspector(); let insp = self.js_runtime.inspector(); JsRuntimeInspector::create_local_session( insp, cb, InspectorSessionKind::Blocking, ) } pub async fn run_event_loop( &mut self, wait_for_inspector: bool, ) -> Result<(), CoreError> { self .js_runtime .run_event_loop(PollEventLoopOptions { wait_for_inspector, ..Default::default() }) .await } /// Return exit code set by the executed code (either in main worker /// or one of child web workers). pub fn exit_code(&self) -> i32 { self.exit_code.get() } /// Dispatches "load" event to the JavaScript runtime. /// /// Does not poll event loop, and thus not await any of the "load" event handlers. pub fn dispatch_load_event(&mut self) -> Result<(), Box<JsError>> { deno_core::scope!(scope, &mut self.js_runtime); v8::tc_scope!(tc_scope, scope); let dispatch_load_event_fn = v8::Local::new(tc_scope, &self.dispatch_load_event_fn_global); let undefined = v8::undefined(tc_scope); dispatch_load_event_fn.call(tc_scope, undefined.into(), &[]); if let Some(exception) = tc_scope.exception() { let error = JsError::from_v8_exception(tc_scope, exception); return Err(error); } Ok(()) } /// Dispatches "unload" event to the JavaScript runtime. /// /// Does not poll event loop, and thus not await any of the "unload" event handlers. pub fn dispatch_unload_event(&mut self) -> Result<(), Box<JsError>> { deno_core::scope!(scope, &mut self.js_runtime); v8::tc_scope!(tc_scope, scope); let dispatch_unload_event_fn = v8::Local::new(tc_scope, &self.dispatch_unload_event_fn_global); let undefined = v8::undefined(tc_scope); dispatch_unload_event_fn.call(tc_scope, undefined.into(), &[]); if let Some(exception) = tc_scope.exception() {
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/js.rs
runtime/js.rs
// Copyright 2018-2025 the Deno authors. MIT license. #[cfg(not(feature = "include_js_files_for_snapshotting"))] pub static SOURCE_CODE_FOR_99_MAIN_JS: &str = include_str!("js/99_main.js"); #[cfg(feature = "include_js_files_for_snapshotting")] pub static PATH_FOR_99_MAIN_JS: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/js/99_main.js");
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/worker_bootstrap.rs
runtime/worker_bootstrap.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::thread; use deno_core::ModuleSpecifier; use deno_core::v8; use deno_node::ops::ipc::ChildIpcSerialization; use deno_telemetry::OtelConfig; use deno_terminal::colors; use serde::Serialize; /// The execution mode for this worker. Some modes may have implicit behaviour. #[derive(Copy, Clone)] pub enum WorkerExecutionMode { /// No special behaviour. None, /// Running in a worker. Worker, /// `deno run` Run, /// `deno repl` Repl, /// `deno eval` Eval, /// `deno test` Test, /// `deno bench` Bench, /// `deno serve` ServeMain { worker_count: usize, }, ServeWorker { worker_index: usize, }, /// `deno jupyter` Jupyter, /// `deno deploy` Deploy, } impl WorkerExecutionMode { pub fn discriminant(&self) -> u8 { match self { WorkerExecutionMode::None => 0, WorkerExecutionMode::Worker => 1, WorkerExecutionMode::Run => 2, WorkerExecutionMode::Repl => 3, WorkerExecutionMode::Eval => 4, WorkerExecutionMode::Test => 5, WorkerExecutionMode::Bench => 6, WorkerExecutionMode::ServeMain { .. } | WorkerExecutionMode::ServeWorker { .. } => 7, WorkerExecutionMode::Jupyter => 8, WorkerExecutionMode::Deploy => 9, } } } /// The log level to use when printing diagnostic log messages, warnings, /// or errors in the worker. /// /// Note: This is disconnected with the log crate's log level and the Rust code /// in this crate will respect that value instead. To specify that, use /// `log::set_max_level`. #[derive(Debug, Default, Clone, Copy)] pub enum WorkerLogLevel { // WARNING: Ensure this is kept in sync with // the JS values (search for LogLevel). Error = 1, Warn = 2, #[default] Info = 3, Debug = 4, } impl From<log::Level> for WorkerLogLevel { fn from(value: log::Level) -> Self { match value { log::Level::Error => WorkerLogLevel::Error, log::Level::Warn => WorkerLogLevel::Warn, log::Level::Info => WorkerLogLevel::Info, log::Level::Debug => WorkerLogLevel::Debug, log::Level::Trace => WorkerLogLevel::Debug, } } } /// Common bootstrap options for MainWorker & WebWorker #[derive(Clone)] pub struct BootstrapOptions { pub deno_version: String, /// Sets `Deno.args` in JS runtime. pub args: Vec<String>, pub cpu_count: usize, pub log_level: WorkerLogLevel, pub enable_op_summary_metrics: bool, pub enable_testing_features: bool, pub locale: String, pub location: Option<ModuleSpecifier>, pub color_level: deno_terminal::colors::ColorLevel, // --unstable-* flags pub unstable_features: Vec<i32>, pub user_agent: String, pub inspect: bool, /// If this is a `deno compile`-ed executable. pub is_standalone: bool, pub has_node_modules_dir: bool, pub argv0: Option<String>, pub node_debug: Option<String>, pub node_ipc_init: Option<(i64, ChildIpcSerialization)>, pub mode: WorkerExecutionMode, pub no_legacy_abort: bool, // Used by `deno serve` pub serve_port: Option<u16>, pub serve_host: Option<String>, pub auto_serve: bool, pub otel_config: OtelConfig, pub close_on_idle: bool, } impl Default for BootstrapOptions { fn default() -> Self { let cpu_count = thread::available_parallelism() .map(|p| p.get()) .unwrap_or(1); // this version is not correct as its the version of deno_runtime // and the implementor should supply a user agent that makes sense let runtime_version = env!("CARGO_PKG_VERSION"); let user_agent = format!("Deno/{runtime_version}"); Self { deno_version: runtime_version.to_string(), user_agent, cpu_count, color_level: colors::get_color_level(), enable_op_summary_metrics: false, enable_testing_features: false, log_level: Default::default(), locale: "en".to_string(), location: Default::default(), unstable_features: Default::default(), inspect: false, args: Default::default(), is_standalone: false, auto_serve: false, has_node_modules_dir: false, argv0: None, node_debug: None, node_ipc_init: None, mode: WorkerExecutionMode::None, no_legacy_abort: false, serve_port: Default::default(), serve_host: Default::default(), otel_config: Default::default(), close_on_idle: false, } } } /// This is a struct that we use to serialize the contents of the `BootstrapOptions` /// struct above to a V8 form. While `serde_v8` is not as fast as hand-coding this, /// it's "fast enough" while serializing a large tuple like this that it doesn't appear /// on flamegraphs. /// /// Note that a few fields in here are derived from the process and environment and /// are not sourced from the underlying `BootstrapOptions`. /// /// Keep this in sync with `99_main.js`. #[derive(Serialize)] struct BootstrapV8<'a>( // deno version &'a str, // location Option<&'a str>, // granular unstable flags &'a [i32], // inspect bool, // enable_testing_features bool, // has_node_modules_dir bool, // argv0 Option<&'a str>, // node_debug Option<&'a str>, // mode i32, // serve port u16, // serve host Option<&'a str>, // serve is main bool, // serve worker count Option<usize>, // OTEL config Box<[u8]>, // close on idle bool, // is_standalone bool, // auto serve bool, ); impl BootstrapOptions { /// Return the v8 equivalent of this structure. pub fn as_v8<'s>( &self, scope: &mut v8::PinScope<'s, '_>, ) -> v8::Local<'s, v8::Value> { let scope = RefCell::new(scope); let ser = deno_core::serde_v8::Serializer::new(&scope); let bootstrap = BootstrapV8( &self.deno_version, self.location.as_ref().map(|l| l.as_str()), self.unstable_features.as_ref(), self.inspect, self.enable_testing_features, self.has_node_modules_dir, self.argv0.as_deref(), self.node_debug.as_deref(), self.mode.discriminant() as _, self.serve_port.unwrap_or_default(), self.serve_host.as_deref(), matches!(self.mode, WorkerExecutionMode::ServeMain { .. }), match self.mode { WorkerExecutionMode::ServeMain { worker_count } => Some(worker_count), WorkerExecutionMode::ServeWorker { worker_index } => Some(worker_index), _ => None, }, self.otel_config.as_v8(), self.close_on_idle, self.is_standalone, self.auto_serve, ); bootstrap.serialize(ser).unwrap() } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/inspector_server.rs
runtime/inspector_server.rs
// Copyright 2018-2025 the Deno authors. MIT license. // Alias for the future `!` type. use core::convert::Infallible as Never; use std::cell::RefCell; use std::collections::HashMap; use std::net::SocketAddr; use std::pin::pin; use std::process; use std::rc::Rc; use std::sync::Arc; use std::task::Poll; use std::thread; use deno_core::InspectorMsg; use deno_core::InspectorSessionChannels; use deno_core::InspectorSessionKind; use deno_core::InspectorSessionProxy; use deno_core::JsRuntimeInspector; use deno_core::futures::channel::mpsc; use deno_core::futures::channel::mpsc::UnboundedReceiver; use deno_core::futures::channel::mpsc::UnboundedSender; use deno_core::futures::channel::oneshot; use deno_core::futures::future; use deno_core::futures::prelude::*; use deno_core::futures::stream::StreamExt; use deno_core::parking_lot::Mutex; use deno_core::serde_json; use deno_core::serde_json::Value; use deno_core::serde_json::json; use deno_core::unsync::spawn; use deno_core::url::Url; use deno_node::InspectorServerUrl; use fastwebsockets::Frame; use fastwebsockets::OpCode; use fastwebsockets::WebSocket; use hyper::body::Bytes; use hyper_util::rt::TokioIo; use tokio::net::TcpListener; use tokio::sync::broadcast; use uuid::Uuid; /// Websocket server that is used to proxy connections from /// devtools to the inspector. pub struct InspectorServer { pub host: SocketAddr, register_inspector_tx: UnboundedSender<InspectorInfo>, shutdown_server_tx: Option<broadcast::Sender<()>>, thread_handle: Option<thread::JoinHandle<()>>, } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum InspectorServerError { #[class(inherit)] #[error(transparent)] Io(#[from] std::io::Error), #[class(inherit)] #[error("Failed to start inspector server at \"{host}\"")] Connect { host: SocketAddr, #[source] #[inherit] source: std::io::Error, }, } impl InspectorServer { pub fn new( host: SocketAddr, name: &'static str, ) -> Result<Self, InspectorServerError> { let (register_inspector_tx, register_inspector_rx) = mpsc::unbounded::<InspectorInfo>(); let (shutdown_server_tx, shutdown_server_rx) = broadcast::channel(1); let tcp_listener = std::net::TcpListener::bind(host) .map_err(|source| InspectorServerError::Connect { host, source })?; tcp_listener.set_nonblocking(true)?; let thread_handle = thread::spawn(move || { let rt = crate::tokio_util::create_basic_runtime(); let local = tokio::task::LocalSet::new(); local.block_on( &rt, server( tcp_listener, register_inspector_rx, shutdown_server_rx, name, ), ) }); Ok(Self { host, register_inspector_tx, shutdown_server_tx: Some(shutdown_server_tx), thread_handle: Some(thread_handle), }) } pub fn register_inspector( &self, module_url: String, inspector: Rc<JsRuntimeInspector>, wait_for_session: bool, ) -> InspectorServerUrl { let session_sender = inspector.get_session_sender(); let deregister_rx = inspector.add_deregister_handler(); let info = InspectorInfo::new( self.host, session_sender, deregister_rx, module_url, wait_for_session, ); let url = InspectorServerUrl( info.get_websocket_debugger_url(&self.host.to_string()), ); self.register_inspector_tx.unbounded_send(info).unwrap(); url } } impl Drop for InspectorServer { fn drop(&mut self) { if let Some(shutdown_server_tx) = self.shutdown_server_tx.take() { shutdown_server_tx .send(()) .expect("unable to send shutdown signal"); } if let Some(thread_handle) = self.thread_handle.take() { thread_handle.join().expect("unable to join thread"); } } } fn handle_ws_request( req: http::Request<hyper::body::Incoming>, inspector_map_rc: Rc<RefCell<HashMap<Uuid, InspectorInfo>>>, ) -> http::Result<http::Response<Box<http_body_util::Full<Bytes>>>> { let (parts, body) = req.into_parts(); let req = http::Request::from_parts(parts, ()); let maybe_uuid = req .uri() .path() .strip_prefix("/ws/") .and_then(|s| Uuid::parse_str(s).ok()); let Some(uuid) = maybe_uuid else { return http::Response::builder() .status(http::StatusCode::BAD_REQUEST) .body(Box::new(Bytes::from("Malformed inspector UUID").into())); }; // run in a block to not hold borrow to `inspector_map` for too long let new_session_tx = { let inspector_map = inspector_map_rc.borrow(); let maybe_inspector_info = inspector_map.get(&uuid); if maybe_inspector_info.is_none() { return http::Response::builder() .status(http::StatusCode::NOT_FOUND) .body(Box::new(Bytes::from("Invalid inspector UUID").into())); } let info = maybe_inspector_info.unwrap(); info.new_session_tx.clone() }; let (parts, _) = req.into_parts(); let mut req = http::Request::from_parts(parts, body); let Ok((resp, upgrade_fut)) = fastwebsockets::upgrade::upgrade(&mut req) else { return http::Response::builder() .status(http::StatusCode::BAD_REQUEST) .body(Box::new( Bytes::from("Not a valid Websocket Request").into(), )); }; // spawn a task that will wait for websocket connection and then pump messages between // the socket and inspector proxy spawn(async move { let websocket = match upgrade_fut.await { Ok(w) => w, Err(err) => { log::error!( "Inspector server failed to upgrade to WS connection: {:?}", err ); return; } }; // The 'outbound' channel carries messages sent to the websocket. let (outbound_tx, outbound_rx) = mpsc::unbounded(); // The 'inbound' channel carries messages received from the websocket. let (inbound_tx, inbound_rx) = mpsc::unbounded(); let inspector_session_proxy = InspectorSessionProxy { channels: InspectorSessionChannels::Regular { tx: outbound_tx, rx: inbound_rx, }, kind: InspectorSessionKind::NonBlocking { wait_for_disconnect: true, }, }; log::info!("Debugger session started."); let _ = new_session_tx.unbounded_send(inspector_session_proxy); pump_websocket_messages(websocket, inbound_tx, outbound_rx).await; }); let (parts, _body) = resp.into_parts(); let resp = http::Response::from_parts( parts, Box::new(http_body_util::Full::new(Bytes::new())), ); Ok(resp) } fn handle_json_request( inspector_map: Rc<RefCell<HashMap<Uuid, InspectorInfo>>>, host: Option<String>, ) -> http::Result<http::Response<Box<http_body_util::Full<Bytes>>>> { let data = inspector_map .borrow() .values() .map(move |info| info.get_json_metadata(&host)) .collect::<Vec<_>>(); let body: http_body_util::Full<Bytes> = Bytes::from(serde_json::to_string(&data).unwrap()).into(); http::Response::builder() .status(http::StatusCode::OK) .header(http::header::CONTENT_TYPE, "application/json") .body(Box::new(body)) } fn handle_json_version_request( version_response: Value, ) -> http::Result<http::Response<Box<http_body_util::Full<Bytes>>>> { let body = Box::new(http_body_util::Full::from( serde_json::to_string(&version_response).unwrap(), )); http::Response::builder() .status(http::StatusCode::OK) .header(http::header::CONTENT_TYPE, "application/json") .body(body) } async fn server( listener: std::net::TcpListener, register_inspector_rx: UnboundedReceiver<InspectorInfo>, shutdown_server_rx: broadcast::Receiver<()>, name: &str, ) { let inspector_map_ = Rc::new(RefCell::new(HashMap::<Uuid, InspectorInfo>::new())); let inspector_map = Rc::clone(&inspector_map_); let register_inspector_handler = listen_for_new_inspectors(register_inspector_rx, inspector_map.clone()) .boxed_local(); let inspector_map = Rc::clone(&inspector_map_); let deregister_inspector_handler = future::poll_fn(|cx| { inspector_map .borrow_mut() .retain(|_, info| info.deregister_rx.poll_unpin(cx) == Poll::Pending); Poll::<Never>::Pending }) .boxed_local(); let json_version_response = json!({ "Browser": name, "Protocol-Version": "1.3", "V8-Version": deno_core::v8::VERSION_STRING, }); // Create the server manually so it can use the Local Executor let listener = match TcpListener::from_std(listener) { Ok(l) => l, Err(err) => { log::error!("Cannot start inspector server: {:?}", err); return; } }; let server_handler = async move { loop { let mut rx = shutdown_server_rx.resubscribe(); let mut shutdown_rx = pin!(rx.recv()); let mut accept = pin!(listener.accept()); let stream = tokio::select! { accept_result = &mut accept => { match accept_result { Ok((s, _)) => s, Err(err) => { log::error!("Failed to accept inspector connection: {:?}", err); continue; } } }, _ = &mut shutdown_rx => { break; } }; let io = TokioIo::new(stream); let inspector_map = Rc::clone(&inspector_map_); let json_version_response = json_version_response.clone(); let mut shutdown_server_rx = shutdown_server_rx.resubscribe(); let service = hyper::service::service_fn( move |req: http::Request<hyper::body::Incoming>| { future::ready({ // If the host header can make a valid URL, use it let host = req .headers() .get("host") .and_then(|host| host.to_str().ok()) .and_then(|host| Url::parse(&format!("http://{host}")).ok()) .and_then(|url| match (url.host(), url.port()) { (Some(host), Some(port)) => Some(format!("{host}:{port}")), (Some(host), None) => Some(format!("{host}")), _ => None, }); match (req.method(), req.uri().path()) { (&http::Method::GET, path) if path.starts_with("/ws/") => { handle_ws_request(req, Rc::clone(&inspector_map)) } (&http::Method::GET, "/json/version") => { handle_json_version_request(json_version_response.clone()) } (&http::Method::GET, "/json") => { handle_json_request(Rc::clone(&inspector_map), host) } (&http::Method::GET, "/json/list") => { handle_json_request(Rc::clone(&inspector_map), host) } _ => http::Response::builder() .status(http::StatusCode::NOT_FOUND) .body(Box::new(http_body_util::Full::new(Bytes::from( "Not Found", )))), } }) }, ); deno_core::unsync::spawn(async move { let server = hyper::server::conn::http1::Builder::new(); let mut conn = pin!(server.serve_connection(io, service).with_upgrades()); let mut shutdown_rx = pin!(shutdown_server_rx.recv()); tokio::select! { result = conn.as_mut() => { if let Err(err) = result { log::error!("Failed to serve connection: {:?}", err); } }, _ = &mut shutdown_rx => { conn.as_mut().graceful_shutdown(); let _ = conn.await; } } }); } } .boxed_local(); tokio::select! { _ = register_inspector_handler => {}, _ = deregister_inspector_handler => unreachable!(), _ = server_handler => {}, } } async fn listen_for_new_inspectors( mut register_inspector_rx: UnboundedReceiver<InspectorInfo>, inspector_map: Rc<RefCell<HashMap<Uuid, InspectorInfo>>>, ) { while let Some(info) = register_inspector_rx.next().await { log::info!( "Debugger listening on {}", info.get_websocket_debugger_url(&info.host.to_string()) ); log::info!("Visit chrome://inspect to connect to the debugger."); if info.wait_for_session { log::info!("Deno is waiting for debugger to connect."); } if inspector_map.borrow_mut().insert(info.uuid, info).is_some() { panic!("Inspector UUID already in map"); } } } /// The pump future takes care of forwarding messages between the websocket /// and channels. It resolves when either side disconnects, ignoring any /// errors. /// /// The future proxies messages sent and received on a warp WebSocket /// to a UnboundedSender/UnboundedReceiver pair. We need these "unbounded" channel ends to sidestep /// Tokio's task budget, which causes issues when JsRuntimeInspector::poll_sessions() /// needs to block the thread because JavaScript execution is paused. /// /// This works because UnboundedSender/UnboundedReceiver are implemented in the /// 'futures' crate, therefore they can't participate in Tokio's cooperative /// task yielding. async fn pump_websocket_messages( mut websocket: WebSocket<TokioIo<hyper::upgrade::Upgraded>>, inbound_tx: UnboundedSender<String>, mut outbound_rx: UnboundedReceiver<InspectorMsg>, ) { 'pump: loop { tokio::select! { Some(msg) = outbound_rx.next() => { let msg = Frame::text(msg.content.into_bytes().into()); let _ = websocket.write_frame(msg).await; } Ok(msg) = websocket.read_frame() => { match msg.opcode { OpCode::Text => { if let Ok(s) = String::from_utf8(msg.payload.to_vec()) { let _ = inbound_tx.unbounded_send(s); } } OpCode::Close => { // Users don't care if there was an error coming from debugger, // just about the fact that debugger did disconnect. log::info!("Debugger session ended"); break 'pump; } _ => { // Ignore other messages. } } } else => { break 'pump; } } } } /// Inspector information that is sent from the isolate thread to the server /// thread when a new inspector is created. pub struct InspectorInfo { pub host: SocketAddr, pub uuid: Uuid, pub thread_name: Option<String>, pub new_session_tx: UnboundedSender<InspectorSessionProxy>, pub deregister_rx: oneshot::Receiver<()>, pub url: String, pub wait_for_session: bool, } impl InspectorInfo { pub fn new( host: SocketAddr, new_session_tx: mpsc::UnboundedSender<InspectorSessionProxy>, deregister_rx: oneshot::Receiver<()>, url: String, wait_for_session: bool, ) -> Self { Self { host, uuid: Uuid::new_v4(), thread_name: thread::current().name().map(|n| n.to_owned()), new_session_tx, deregister_rx, url, wait_for_session, } } fn get_json_metadata(&self, host: &Option<String>) -> Value { let host_listen = format!("{}", self.host); let host = host.as_ref().unwrap_or(&host_listen); json!({ "description": "deno", "devtoolsFrontendUrl": self.get_frontend_url(host), "faviconUrl": "https://deno.land/favicon.ico", "id": self.uuid.to_string(), "title": self.get_title(), "type": "node", "url": self.url.to_string(), "webSocketDebuggerUrl": self.get_websocket_debugger_url(host), }) } pub fn get_websocket_debugger_url(&self, host: &str) -> String { format!("ws://{}/ws/{}", host, &self.uuid) } fn get_frontend_url(&self, host: &str) -> String { format!( "devtools://devtools/bundled/js_app.html?ws={}/ws/{}&experiments=true&v8only=true", host, &self.uuid ) } fn get_title(&self) -> String { format!( "deno{} [pid: {}]", self .thread_name .as_ref() .map(|n| format!(" - {n}")) .unwrap_or_default(), process::id(), ) } } /// Channel for forwarding worker inspector session proxies to the main runtime. /// Workers send their InspectorSessionProxy through this channel to establish /// bidirectional debugging communication with the main inspector session. pub struct MainInspectorSessionChannel( Arc<Mutex<Option<UnboundedSender<InspectorSessionProxy>>>>, ); impl MainInspectorSessionChannel { pub fn new() -> Self { Self(Arc::new(Mutex::new(None))) } pub fn set(&self, tx: UnboundedSender<InspectorSessionProxy>) { *self.0.lock() = Some(tx); } pub fn get(&self) -> Option<UnboundedSender<InspectorSessionProxy>> { self.0.lock().clone() } } impl Default for MainInspectorSessionChannel { fn default() -> Self { Self::new() } } impl Clone for MainInspectorSessionChannel { fn clone(&self) -> Self { Self(self.0.clone()) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/shared.rs
runtime/shared.rs
// Copyright 2018-2025 the Deno authors. MIT license. // Utilities shared between `build.rs` and the rest of the crate. use deno_core::Extension; use deno_core::extension; extension!(runtime, deps = [ deno_webidl, deno_tls, deno_web, deno_fetch, deno_cache, deno_websocket, deno_webstorage, deno_crypto, deno_node, deno_ffi, deno_net, deno_napi, deno_http, deno_io, deno_fs, deno_bundle_runtime ], esm_entry_point = "ext:runtime/90_deno_ns.js", esm = [ dir "js", "01_errors.js", "01_version.ts", "06_util.js", "10_permissions.js", "11_workers.js", "40_fs_events.js", "40_tty.js", "41_prompt.js", "90_deno_ns.js", "98_global_scope_shared.js", "98_global_scope_window.js", "98_global_scope_worker.js" ], customizer = |ext: &mut Extension| { #[cfg(not(feature = "exclude_runtime_main_js"))] { use deno_core::ascii_str_include; use deno_core::ExtensionFileSource; ext.esm_files.to_mut().push(ExtensionFileSource::new("ext:deno_features/flags.js", deno_features::JS_SOURCE)); ext.esm_files.to_mut().push(ExtensionFileSource::new("ext:runtime_main/js/99_main.js", ascii_str_include!("./js/99_main.js"))); ext.esm_entry_point = Some("ext:runtime_main/js/99_main.js"); } } );
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/snapshot.rs
runtime/snapshot.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::io::Write; use std::path::PathBuf; use std::rc::Rc; use deno_core::Extension; use deno_core::snapshot::*; use deno_core::v8; use deno_resolver::npm::DenoInNpmPackageChecker; use deno_resolver::npm::NpmResolver; use crate::ops; use crate::ops::bootstrap::SnapshotOptions; use crate::shared::runtime; pub fn create_runtime_snapshot( snapshot_path: PathBuf, snapshot_options: SnapshotOptions, // NOTE: For embedders that wish to add additional extensions to the snapshot custom_extensions: Vec<Extension>, ) { // NOTE(bartlomieju): ordering is important here, keep it in sync with // `runtime/worker.rs`, `runtime/web_worker.rs`, `runtime/snapshot_info.rs` // and `runtime/snapshot.rs`! let mut extensions: Vec<Extension> = vec![ deno_telemetry::deno_telemetry::lazy_init(), deno_webidl::deno_webidl::lazy_init(), deno_web::deno_web::lazy_init(), deno_webgpu::deno_webgpu::lazy_init(), deno_canvas::deno_canvas::lazy_init(), deno_fetch::deno_fetch::lazy_init(), deno_cache::deno_cache::lazy_init(), deno_websocket::deno_websocket::lazy_init(), deno_webstorage::deno_webstorage::lazy_init(), deno_crypto::deno_crypto::lazy_init(), deno_ffi::deno_ffi::lazy_init(), deno_net::deno_net::lazy_init(), deno_tls::deno_tls::lazy_init(), deno_kv::deno_kv::lazy_init::<deno_kv::sqlite::SqliteDbHandler>(), deno_cron::deno_cron::init(deno_cron::local::LocalCronHandler::new()), deno_napi::deno_napi::lazy_init(), deno_http::deno_http::lazy_init(), deno_io::deno_io::lazy_init(), deno_fs::deno_fs::lazy_init(), deno_os::deno_os::lazy_init(), deno_process::deno_process::lazy_init(), deno_node::deno_node::lazy_init::< DenoInNpmPackageChecker, NpmResolver<sys_traits::impls::RealSys>, sys_traits::impls::RealSys, >(), ops::runtime::deno_runtime::lazy_init(), ops::worker_host::deno_worker_host::lazy_init(), ops::fs_events::deno_fs_events::lazy_init(), ops::permissions::deno_permissions::lazy_init(), ops::tty::deno_tty::lazy_init(), ops::http::deno_http_runtime::lazy_init(), deno_bundle_runtime::deno_bundle_runtime::lazy_init(), ops::bootstrap::deno_bootstrap::init(Some(snapshot_options), false), runtime::lazy_init(), ops::web_worker::deno_web_worker::lazy_init(), ]; extensions.extend(custom_extensions); let output = create_snapshot( CreateSnapshotOptions { cargo_manifest_dir: env!("CARGO_MANIFEST_DIR"), startup_snapshot: None, extensions, extension_transpiler: Some(Rc::new(|specifier, source| { crate::transpile::maybe_transpile_source(specifier, source) })), with_runtime_cb: Some(Box::new(|rt| { let isolate = rt.v8_isolate(); v8::scope!(scope, isolate); let tmpl = deno_node::init_global_template( scope, deno_node::ContextInitMode::ForSnapshot, ); let ctx = deno_node::create_v8_context( scope, tmpl, deno_node::ContextInitMode::ForSnapshot, std::ptr::null_mut(), ); assert_eq!(scope.add_context(ctx), deno_node::VM_CONTEXT_INDEX); })), skip_op_registration: false, }, None, ) .unwrap(); let mut snapshot = std::fs::File::create(snapshot_path).unwrap(); snapshot.write_all(&output.output).unwrap(); #[allow(clippy::print_stdout)] for path in output.files_loaded_during_snapshot { println!("cargo:rerun-if-changed={}", path.display()); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/tokio_util.rs
runtime/tokio_util.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::fmt::Debug; use std::str::FromStr; use deno_core::unsync::MaskFutureAsSend; #[cfg(tokio_unstable)] use tokio_metrics::RuntimeMonitor; /// Default configuration for tokio. In the future, this method may have different defaults /// depending on the platform and/or CPU layout. const fn tokio_configuration() -> (u32, u32, usize) { (61, 31, 1024) } fn tokio_env<T: FromStr>(name: &'static str, default: T) -> T where <T as FromStr>::Err: Debug, { match std::env::var(name) { Ok(value) => value.parse().unwrap(), Err(_) => default, } } pub fn create_basic_runtime() -> tokio::runtime::Runtime { let (event_interval, global_queue_interval, max_io_events_per_tick) = tokio_configuration(); tokio::runtime::Builder::new_current_thread() .enable_io() .enable_time() .event_interval(tokio_env("DENO_TOKIO_EVENT_INTERVAL", event_interval)) .global_queue_interval(tokio_env( "DENO_TOKIO_GLOBAL_QUEUE_INTERVAL", global_queue_interval, )) .max_io_events_per_tick(tokio_env( "DENO_TOKIO_MAX_IO_EVENTS_PER_TICK", max_io_events_per_tick, )) // This limits the number of threads for blocking operations (like for // synchronous fs ops) or CPU bound tasks like when we run dprint in // parallel for deno fmt. // The default value is 512, which is an unhelpfully large thread pool. We // don't ever want to have more than a couple dozen threads. .max_blocking_threads(if cfg!(windows) { // on windows, tokio uses blocking tasks for child process IO, make sure // we have enough available threads for other tasks to run 4 * std::thread::available_parallelism() .map(|n| n.get()) .unwrap_or(8) } else { 32 }) .build() .unwrap() } #[inline(always)] fn create_and_run_current_thread_inner<F, R>( future: F, metrics_enabled: bool, ) -> R where F: std::future::Future<Output = R> + 'static, R: Send + 'static, { let rt = create_basic_runtime(); // Since this is the main future, we want to box it in debug mode because it tends to be fairly // large and the compiler won't optimize repeated copies. We also make this runtime factory // function #[inline(always)] to avoid holding the unboxed, unused future on the stack. #[cfg(debug_assertions)] // SAFETY: this is guaranteed to be running on a current-thread executor let future = Box::pin(unsafe { MaskFutureAsSend::new(future) }); #[cfg(not(debug_assertions))] // SAFETY: this is guaranteed to be running on a current-thread executor let future = unsafe { MaskFutureAsSend::new(future) }; #[cfg(tokio_unstable)] let join_handle = if metrics_enabled { rt.spawn(async move { let metrics_interval: u64 = std::env::var("DENO_TOKIO_METRICS_INTERVAL") .ok() .and_then(|val| val.parse().ok()) .unwrap_or(1000); let handle = tokio::runtime::Handle::current(); let runtime_monitor = RuntimeMonitor::new(&handle); tokio::spawn(async move { #[allow(clippy::print_stderr)] for interval in runtime_monitor.intervals() { eprintln!("{:#?}", interval); // wait 500ms tokio::time::sleep(std::time::Duration::from_millis( metrics_interval, )) .await; } }); future.await }) } else { rt.spawn(future) }; #[cfg(not(tokio_unstable))] let join_handle = rt.spawn(future); let r = rt.block_on(join_handle).unwrap().into_inner(); // Forcefully shutdown the runtime - we're done executing JS code at this // point, but there might be outstanding blocking tasks that were created and // latered "unrefed". They won't terminate on their own, so we're forcing // termination of Tokio runtime at this point. rt.shutdown_background(); r } #[inline(always)] pub fn create_and_run_current_thread<F, R>(future: F) -> R where F: std::future::Future<Output = R> + 'static, R: Send + 'static, { create_and_run_current_thread_inner(future, false) } #[inline(always)] pub fn create_and_run_current_thread_with_maybe_metrics<F, R>(future: F) -> R where F: std::future::Future<Output = R> + 'static, R: Send + 'static, { let metrics_enabled = std::env::var("DENO_TOKIO_METRICS").ok().is_some(); create_and_run_current_thread_inner(future, metrics_enabled) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/snapshot_info.rs
runtime/snapshot_info.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::sync::Arc; use deno_core::Extension; use deno_resolver::npm::DenoInNpmPackageChecker; use deno_resolver::npm::NpmResolver; use crate::ops; use crate::shared::runtime; pub fn get_extensions_in_snapshot() -> Vec<Extension> { // NOTE(bartlomieju): ordering is important here, keep it in sync with // `runtime/worker.rs`, `runtime/web_worker.rs`, `runtime/snapshot_info.rs` // and `runtime/snapshot.rs`! let fs = std::sync::Arc::new(deno_fs::RealFs); vec![ deno_telemetry::deno_telemetry::init(), deno_webidl::deno_webidl::init(), deno_web::deno_web::init( Default::default(), Default::default(), deno_web::InMemoryBroadcastChannel::default(), ), deno_webgpu::deno_webgpu::init(), deno_canvas::deno_canvas::init(), deno_fetch::deno_fetch::init(Default::default()), deno_cache::deno_cache::init(None), deno_websocket::deno_websocket::init(), deno_webstorage::deno_webstorage::init(None), deno_crypto::deno_crypto::init(None), deno_ffi::deno_ffi::init(None), deno_net::deno_net::init(None, None), deno_tls::deno_tls::init(), deno_kv::deno_kv::init( deno_kv::sqlite::SqliteDbHandler::new(None, None), deno_kv::KvConfig::builder().build(), ), deno_cron::deno_cron::init(deno_cron::local::LocalCronHandler::new()), deno_napi::deno_napi::init(None), deno_http::deno_http::init(deno_http::Options::default()), deno_io::deno_io::init(Some(Default::default())), deno_fs::deno_fs::init(fs.clone()), deno_os::deno_os::init(Default::default()), deno_process::deno_process::init(Default::default()), deno_node::deno_node::init::< DenoInNpmPackageChecker, NpmResolver<sys_traits::impls::RealSys>, sys_traits::impls::RealSys, >(None, fs.clone()), ops::runtime::deno_runtime::init("deno:runtime".parse().unwrap()), ops::worker_host::deno_worker_host::init( Arc::new(|_| unreachable!("not used in snapshot.")), None, ), ops::fs_events::deno_fs_events::init(), ops::permissions::deno_permissions::init(), ops::tty::deno_tty::init(), ops::http::deno_http_runtime::init(), deno_bundle_runtime::deno_bundle_runtime::init(None), ops::bootstrap::deno_bootstrap::init(None, false), runtime::init(), ops::web_worker::deno_web_worker::init(), ] }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/web_worker.rs
runtime/web_worker.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::fmt; use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicU32; use std::sync::atomic::Ordering; use std::task::Context; use std::task::Poll; use deno_cache::CacheImpl; use deno_cache::CreateCache; use deno_cache::SqliteBackedCache; use deno_core::CancelHandle; use deno_core::CompiledWasmModuleStore; use deno_core::DetachedBuffer; use deno_core::Extension; use deno_core::JsRuntime; use deno_core::ModuleCodeString; use deno_core::ModuleId; use deno_core::ModuleLoader; use deno_core::ModuleSpecifier; use deno_core::PollEventLoopOptions; use deno_core::RuntimeOptions; use deno_core::SharedArrayBufferStore; use deno_core::error::CoreError; use deno_core::error::CoreErrorKind; use deno_core::futures::channel::mpsc; use deno_core::futures::future::poll_fn; use deno_core::futures::stream::StreamExt; use deno_core::futures::task::AtomicWaker; use deno_core::located_script_name; use deno_core::serde::Deserialize; use deno_core::serde::Serialize; use deno_core::serde_json::json; use deno_core::v8; use deno_cron::local::LocalCronHandler; use deno_error::JsErrorClass; use deno_fs::FileSystem; use deno_io::Stdio; use deno_kv::dynamic::MultiBackendDbHandler; use deno_napi::DenoRtNativeAddonLoaderRc; use deno_node::ExtNodeSys; use deno_node::NodeExtInitServices; use deno_permissions::PermissionsContainer; use deno_process::NpmProcessStateProviderRc; use deno_terminal::colors; use deno_tls::RootCertStoreProvider; use deno_tls::TlsKeys; use deno_web::BlobStore; use deno_web::InMemoryBroadcastChannel; use deno_web::JsMessageData; use deno_web::MessagePort; use deno_web::Transferable; use deno_web::create_entangled_message_port; use deno_web::serialize_transferables; use log::debug; use node_resolver::InNpmPackageChecker; use node_resolver::NpmPackageFolderResolver; use crate::BootstrapOptions; use crate::FeatureChecker; use crate::coverage::CoverageCollector; use crate::inspector_server::InspectorServer; use crate::inspector_server::MainInspectorSessionChannel; use crate::ops; use crate::shared::runtime; use crate::worker::FormatJsErrorFn; #[cfg(target_os = "linux")] use crate::worker::MEMORY_TRIM_HANDLER_ENABLED; #[cfg(target_os = "linux")] use crate::worker::SIGUSR2_RX; use crate::worker::create_op_metrics; use crate::worker::create_validate_import_attributes_callback; pub struct WorkerMetadata { pub buffer: DetachedBuffer, pub transferables: Vec<Transferable>, } static WORKER_ID_COUNTER: AtomicU32 = AtomicU32::new(1); #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct WorkerId(u32); impl WorkerId { pub fn new() -> WorkerId { let id = WORKER_ID_COUNTER.fetch_add(1, Ordering::SeqCst); WorkerId(id) } } impl fmt::Display for WorkerId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "worker-{}", self.0) } } impl Default for WorkerId { fn default() -> Self { Self::new() } } #[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum WorkerThreadType { // Used only for testing Classic, // Regular Web Worker Module, // `node:worker_threads` worker, technically // not a web worker, will be cleaned up in the future. Node, } impl<'s> WorkerThreadType { pub fn to_v8( &self, scope: &mut v8::PinScope<'s, '_>, ) -> v8::Local<'s, v8::String> { v8::String::new( scope, match self { WorkerThreadType::Classic => "classic", WorkerThreadType::Module => "module", WorkerThreadType::Node => "node", }, ) .unwrap() } } /// Events that are sent to host from child /// worker. #[allow(clippy::large_enum_variant)] pub enum WorkerControlEvent { TerminalError(CoreError), Close, } use deno_core::serde::Serializer; impl Serialize for WorkerControlEvent { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let type_id = match &self { WorkerControlEvent::TerminalError(_) => 1_i32, WorkerControlEvent::Close => 3_i32, }; match self { WorkerControlEvent::TerminalError(error) => { let value = match error.as_kind() { CoreErrorKind::Js(js_error) => { let frame = js_error.frames.iter().find(|f| match &f.file_name { Some(s) => !s.trim_start_matches('[').starts_with("ext:"), None => false, }); json!({ "message": js_error.exception_message, "fileName": frame.map(|f| f.file_name.as_ref()), "lineNumber": frame.map(|f| f.line_number.as_ref()), "columnNumber": frame.map(|f| f.column_number.as_ref()), }) } _ => json!({ "message": error.to_string(), }), }; Serialize::serialize(&(type_id, value), serializer) } _ => Serialize::serialize(&(type_id, ()), serializer), } } } // Channels used for communication with worker's parent #[derive(Clone)] pub struct WebWorkerInternalHandle { sender: mpsc::Sender<WorkerControlEvent>, pub port: Rc<MessagePort>, pub cancel: Rc<CancelHandle>, termination_signal: Arc<AtomicBool>, has_terminated: Arc<AtomicBool>, terminate_waker: Arc<AtomicWaker>, isolate_handle: v8::IsolateHandle, pub name: String, pub worker_type: WorkerThreadType, } impl WebWorkerInternalHandle { /// Post WorkerEvent to parent as a worker #[allow(clippy::result_large_err)] pub fn post_event( &self, event: WorkerControlEvent, ) -> Result<(), mpsc::TrySendError<WorkerControlEvent>> { let mut sender = self.sender.clone(); // If the channel is closed, // the worker must have terminated but the termination message has not yet been received. // // Therefore just treat it as if the worker has terminated and return. if sender.is_closed() { self.has_terminated.store(true, Ordering::SeqCst); return Ok(()); } sender.try_send(event) } /// Check if this worker is terminated or being terminated pub fn is_terminated(&self) -> bool { self.has_terminated.load(Ordering::SeqCst) } /// Check if this worker must terminate (because the termination signal is /// set), and terminates it if so. Returns whether the worker is terminated or /// being terminated, as with [`Self::is_terminated()`]. pub fn terminate_if_needed(&mut self) -> bool { let has_terminated = self.is_terminated(); if !has_terminated && self.termination_signal.load(Ordering::SeqCst) { self.terminate(); return true; } has_terminated } /// Terminate the worker /// This function will set terminated to true, terminate the isolate and close the message channel pub fn terminate(&mut self) { self.cancel.cancel(); self.terminate_waker.wake(); // This function can be called multiple times by whomever holds // the handle. However only a single "termination" should occur so // we need a guard here. let already_terminated = self.has_terminated.swap(true, Ordering::SeqCst); if !already_terminated { // Stop javascript execution self.isolate_handle.terminate_execution(); } // Wake parent by closing the channel self.sender.close_channel(); } } pub struct SendableWebWorkerHandle { port: MessagePort, receiver: mpsc::Receiver<WorkerControlEvent>, termination_signal: Arc<AtomicBool>, has_terminated: Arc<AtomicBool>, terminate_waker: Arc<AtomicWaker>, isolate_handle: v8::IsolateHandle, } impl From<SendableWebWorkerHandle> for WebWorkerHandle { fn from(handle: SendableWebWorkerHandle) -> Self { WebWorkerHandle { receiver: Rc::new(RefCell::new(handle.receiver)), port: Rc::new(handle.port), termination_signal: handle.termination_signal, has_terminated: handle.has_terminated, terminate_waker: handle.terminate_waker, isolate_handle: handle.isolate_handle, } } } /// This is the handle to the web worker that the parent thread uses to /// communicate with the worker. It is created from a `SendableWebWorkerHandle` /// which is sent to the parent thread from the worker thread where it is /// created. The reason for this separation is that the handle first needs to be /// `Send` when transferring between threads, and then must be `Clone` when it /// has arrived on the parent thread. It can not be both at once without large /// amounts of Arc<Mutex> and other fun stuff. #[derive(Clone)] pub struct WebWorkerHandle { pub port: Rc<MessagePort>, receiver: Rc<RefCell<mpsc::Receiver<WorkerControlEvent>>>, termination_signal: Arc<AtomicBool>, has_terminated: Arc<AtomicBool>, terminate_waker: Arc<AtomicWaker>, isolate_handle: v8::IsolateHandle, } impl WebWorkerHandle { /// Get the WorkerEvent with lock /// Return error if more than one listener tries to get event #[allow(clippy::await_holding_refcell_ref)] // TODO(ry) remove! pub async fn get_control_event(&self) -> Option<WorkerControlEvent> { let mut receiver = self.receiver.borrow_mut(); receiver.next().await } /// Terminate the worker /// This function will set the termination signal, close the message channel, /// and schedule to terminate the isolate after two seconds. pub fn terminate(self) { use std::thread::sleep; use std::thread::spawn; use std::time::Duration; let schedule_termination = !self.termination_signal.swap(true, Ordering::SeqCst); self.port.disentangle(); if schedule_termination && !self.has_terminated.load(Ordering::SeqCst) { // Wake up the worker's event loop so it can terminate. self.terminate_waker.wake(); let has_terminated = self.has_terminated.clone(); // Schedule to terminate the isolate's execution. spawn(move || { sleep(Duration::from_secs(2)); // A worker's isolate can only be terminated once, so we need a guard // here. let already_terminated = has_terminated.swap(true, Ordering::SeqCst); if !already_terminated { // Stop javascript execution self.isolate_handle.terminate_execution(); } }); } } } fn create_handles( isolate_handle: v8::IsolateHandle, name: String, worker_type: WorkerThreadType, ) -> (WebWorkerInternalHandle, SendableWebWorkerHandle) { let (parent_port, worker_port) = create_entangled_message_port(); let (ctrl_tx, ctrl_rx) = mpsc::channel::<WorkerControlEvent>(1); let termination_signal = Arc::new(AtomicBool::new(false)); let has_terminated = Arc::new(AtomicBool::new(false)); let terminate_waker = Arc::new(AtomicWaker::new()); let internal_handle = WebWorkerInternalHandle { name, port: Rc::new(parent_port), termination_signal: termination_signal.clone(), has_terminated: has_terminated.clone(), terminate_waker: terminate_waker.clone(), isolate_handle: isolate_handle.clone(), cancel: CancelHandle::new_rc(), sender: ctrl_tx, worker_type, }; let external_handle = SendableWebWorkerHandle { receiver: ctrl_rx, port: worker_port, termination_signal, has_terminated, terminate_waker, isolate_handle, }; (internal_handle, external_handle) } pub struct WebWorkerServiceOptions< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TExtNodeSys: ExtNodeSys + 'static, > { pub blob_store: Arc<BlobStore>, pub broadcast_channel: InMemoryBroadcastChannel, pub deno_rt_native_addon_loader: Option<DenoRtNativeAddonLoaderRc>, pub compiled_wasm_module_store: Option<CompiledWasmModuleStore>, pub feature_checker: Arc<FeatureChecker>, pub fs: Arc<dyn FileSystem>, pub maybe_inspector_server: Option<Arc<InspectorServer>>, pub main_inspector_session_tx: MainInspectorSessionChannel, pub module_loader: Rc<dyn ModuleLoader>, pub node_services: Option< NodeExtInitServices< TInNpmPackageChecker, TNpmPackageFolderResolver, TExtNodeSys, >, >, pub npm_process_state_provider: Option<NpmProcessStateProviderRc>, pub permissions: PermissionsContainer, pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>, pub shared_array_buffer_store: Option<SharedArrayBufferStore>, pub bundle_provider: Option<Arc<dyn deno_bundle_runtime::BundleProvider>>, } pub struct WebWorkerOptions { pub name: String, pub main_module: ModuleSpecifier, pub worker_id: WorkerId, pub bootstrap: BootstrapOptions, pub extensions: Vec<Extension>, pub startup_snapshot: Option<&'static [u8]>, pub unsafely_ignore_certificate_errors: Option<Vec<String>>, /// Optional isolate creation parameters, such as heap limits. pub create_params: Option<v8::CreateParams>, pub seed: Option<u64>, pub create_web_worker_cb: Arc<ops::worker_host::CreateWebWorkerCb>, pub format_js_error_fn: Option<Arc<FormatJsErrorFn>>, pub worker_type: WorkerThreadType, pub cache_storage_dir: Option<std::path::PathBuf>, pub stdio: Stdio, pub trace_ops: Option<Vec<String>>, pub close_on_idle: bool, pub maybe_worker_metadata: Option<WorkerMetadata>, pub maybe_coverage_dir: Option<PathBuf>, pub enable_raw_imports: bool, pub enable_stack_trace_arg_in_ops: bool, } /// This struct is an implementation of `Worker` Web API /// /// Each `WebWorker` is either a child of `MainWorker` or other /// `WebWorker`. pub struct WebWorker { id: WorkerId, pub js_runtime: JsRuntime, pub name: String, close_on_idle: bool, internal_handle: WebWorkerInternalHandle, pub worker_type: WorkerThreadType, pub main_module: ModuleSpecifier, poll_for_messages_fn: Option<v8::Global<v8::Value>>, has_message_event_listener_fn: Option<v8::Global<v8::Value>>, bootstrap_fn_global: Option<v8::Global<v8::Function>>, // Consumed when `bootstrap_fn` is called maybe_worker_metadata: Option<WorkerMetadata>, memory_trim_handle: Option<tokio::task::JoinHandle<()>>, maybe_coverage_dir: Option<PathBuf>, } impl Drop for WebWorker { fn drop(&mut self) { // clean up the package.json thread local cache node_resolver::PackageJsonThreadLocalCache::clear(); if let Some(memory_trim_handle) = self.memory_trim_handle.take() { memory_trim_handle.abort(); } } } impl WebWorker { pub fn bootstrap_from_options< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TExtNodeSys: ExtNodeSys + 'static, >( services: WebWorkerServiceOptions< TInNpmPackageChecker, TNpmPackageFolderResolver, TExtNodeSys, >, options: WebWorkerOptions, ) -> (Self, SendableWebWorkerHandle) { let (mut worker, handle, bootstrap_options) = Self::from_options(services, options); worker.bootstrap(&bootstrap_options); (worker, handle) } fn from_options< TInNpmPackageChecker: InNpmPackageChecker + 'static, TNpmPackageFolderResolver: NpmPackageFolderResolver + 'static, TExtNodeSys: ExtNodeSys + 'static, >( services: WebWorkerServiceOptions< TInNpmPackageChecker, TNpmPackageFolderResolver, TExtNodeSys, >, mut options: WebWorkerOptions, ) -> (Self, SendableWebWorkerHandle, BootstrapOptions) { // Permissions: many ops depend on this let enable_testing_features = options.bootstrap.enable_testing_features; fn create_cache_inner(options: &WebWorkerOptions) -> Option<CreateCache> { if let Ok(var) = std::env::var("DENO_CACHE_LSC_ENDPOINT") { let elems: Vec<_> = var.split(",").collect(); if elems.len() == 2 { let endpoint = elems[0]; let token = elems[1]; use deno_cache::CacheShard; let shard = Rc::new(CacheShard::new(endpoint.to_string(), token.to_string())); let create_cache_fn = move || { let x = deno_cache::LscBackend::default(); x.set_shard(shard.clone()); Ok(CacheImpl::Lsc(x)) }; #[allow(clippy::arc_with_non_send_sync)] return Some(CreateCache(Arc::new(create_cache_fn))); } } if let Some(storage_dir) = &options.cache_storage_dir { let storage_dir = storage_dir.clone(); let create_cache_fn = move || { let s = SqliteBackedCache::new(storage_dir.clone())?; Ok(CacheImpl::Sqlite(s)) }; return Some(CreateCache(Arc::new(create_cache_fn))); } None } let create_cache = create_cache_inner(&options); // NOTE(bartlomieju): ordering is important here, keep it in sync with // `runtime/worker.rs`, `runtime/web_worker.rs`, `runtime/snapshot_info.rs` // and `runtime/snapshot.rs`! let mut extensions = vec![ deno_telemetry::deno_telemetry::init(), // Web APIs deno_webidl::deno_webidl::init(), deno_web::deno_web::init( services.blob_store, Some(options.main_module.clone()), services.broadcast_channel, ), deno_webgpu::deno_webgpu::init(), deno_canvas::deno_canvas::init(), deno_fetch::deno_fetch::init(deno_fetch::Options { user_agent: options.bootstrap.user_agent.clone(), root_cert_store_provider: services.root_cert_store_provider.clone(), unsafely_ignore_certificate_errors: options .unsafely_ignore_certificate_errors .clone(), file_fetch_handler: Rc::new(deno_fetch::FsFetchHandler), ..Default::default() }), deno_cache::deno_cache::init(create_cache), deno_websocket::deno_websocket::init(), deno_webstorage::deno_webstorage::init(None).disable(), deno_crypto::deno_crypto::init(options.seed), deno_ffi::deno_ffi::init(services.deno_rt_native_addon_loader.clone()), deno_net::deno_net::init( services.root_cert_store_provider.clone(), options.unsafely_ignore_certificate_errors.clone(), ), deno_tls::deno_tls::init(), deno_kv::deno_kv::init( MultiBackendDbHandler::remote_or_sqlite( None, options.seed, deno_kv::remote::HttpOptions { user_agent: options.bootstrap.user_agent.clone(), root_cert_store_provider: services.root_cert_store_provider, unsafely_ignore_certificate_errors: options .unsafely_ignore_certificate_errors .clone(), client_cert_chain_and_key: TlsKeys::Null, proxy: None, }, ), deno_kv::KvConfig::builder().build(), ), deno_cron::deno_cron::init(LocalCronHandler::new()), deno_napi::deno_napi::init(services.deno_rt_native_addon_loader.clone()), deno_http::deno_http::init(deno_http::Options { no_legacy_abort: options.bootstrap.no_legacy_abort, ..Default::default() }), deno_io::deno_io::init(Some(options.stdio)), deno_fs::deno_fs::init(services.fs.clone()), deno_os::deno_os::init(None), deno_process::deno_process::init(services.npm_process_state_provider), deno_node::deno_node::init::< TInNpmPackageChecker, TNpmPackageFolderResolver, TExtNodeSys, >(services.node_services, services.fs), // Runtime ops that are always initialized for WebWorkers ops::runtime::deno_runtime::init(options.main_module.clone()), ops::worker_host::deno_worker_host::init( options.create_web_worker_cb, options.format_js_error_fn, ), ops::fs_events::deno_fs_events::init(), ops::permissions::deno_permissions::init(), ops::tty::deno_tty::init(), ops::http::deno_http_runtime::init(), deno_bundle_runtime::deno_bundle_runtime::init(services.bundle_provider), ops::bootstrap::deno_bootstrap::init( options.startup_snapshot.and_then(|_| Default::default()), false, ), runtime::init(), ops::web_worker::deno_web_worker::init(), ]; #[cfg(feature = "hmr")] const { assert!( cfg!(not(feature = "only_snapshotted_js_sources")), "'hmr' is incompatible with 'only_snapshotted_js_sources'." ); } for extension in &mut extensions { if options.startup_snapshot.is_some() { extension.js_files = std::borrow::Cow::Borrowed(&[]); extension.esm_files = std::borrow::Cow::Borrowed(&[]); extension.esm_entry_point = None; } } extensions.extend(std::mem::take(&mut options.extensions)); #[cfg(feature = "only_snapshotted_js_sources")] options.startup_snapshot.as_ref().expect("A user snapshot was not provided, even though 'only_snapshotted_js_sources' is used."); // Get our op metrics let (op_summary_metrics, op_metrics_factory_fn) = create_op_metrics( options.bootstrap.enable_op_summary_metrics, options.trace_ops, ); let mut js_runtime = JsRuntime::new(RuntimeOptions { module_loader: Some(services.module_loader), startup_snapshot: options.startup_snapshot, create_params: options.create_params, shared_array_buffer_store: services.shared_array_buffer_store, compiled_wasm_module_store: services.compiled_wasm_module_store, extensions, #[cfg(feature = "transpile")] extension_transpiler: Some(Rc::new(|specifier, source| { crate::transpile::maybe_transpile_source(specifier, source) })), #[cfg(not(feature = "transpile"))] extension_transpiler: None, inspector: true, op_metrics_factory_fn, validate_import_attributes_cb: Some( create_validate_import_attributes_callback(Arc::new(AtomicBool::new( options.enable_raw_imports, ))), ), import_assertions_support: deno_core::ImportAssertionsSupport::Error, maybe_op_stack_trace_callback: options .enable_stack_trace_arg_in_ops .then(crate::worker::create_permissions_stack_trace_callback), extension_code_cache: None, skip_op_registration: false, v8_platform: None, is_main: false, worker_id: Some(options.worker_id.0), wait_for_inspector_disconnect_callback: None, custom_module_evaluation_cb: None, eval_context_code_cache_cbs: None, }); if let Some(op_summary_metrics) = op_summary_metrics { js_runtime.op_state().borrow_mut().put(op_summary_metrics); } { let state = js_runtime.op_state(); let mut state = state.borrow_mut(); state.put::<PermissionsContainer>(services.permissions); state.put(ops::TestingFeaturesEnabled(enable_testing_features)); state.put(services.feature_checker); // Put inspector handle into the op state so we can put a breakpoint when // executing a CJS entrypoint. state.put(js_runtime.inspector()); } if let Some(main_session_tx) = services.main_inspector_session_tx.get() { let (main_proxy, worker_proxy) = deno_core::create_worker_inspector_session_pair( options.main_module.to_string(), ); // Send worker proxy to the main runtime if main_session_tx.unbounded_send(main_proxy).is_err() { log::debug!("Failed to send inspector session proxy to main runtime"); } // Send worker proxy to the worker runtime if js_runtime .inspector() .get_session_sender() .unbounded_send(worker_proxy) .is_err() { log::debug!("Failed to send inspector session proxy to worker runtime"); } } let (internal_handle, external_handle) = { let handle = js_runtime.v8_isolate().thread_safe_handle(); let (internal_handle, external_handle) = create_handles(handle, options.name.clone(), options.worker_type); let op_state = js_runtime.op_state(); let mut op_state = op_state.borrow_mut(); op_state.put(internal_handle.clone()); (internal_handle, external_handle) }; let bootstrap_fn_global = { let context = js_runtime.main_context(); deno_core::scope!(scope, &mut js_runtime); let context_local = v8::Local::new(scope, context); let global_obj = context_local.global(scope); let bootstrap_str = v8::String::new_external_onebyte_static(scope, b"bootstrap").unwrap(); let bootstrap_ns: v8::Local<v8::Object> = global_obj .get(scope, bootstrap_str.into()) .unwrap() .try_into() .unwrap(); let main_runtime_str = v8::String::new_external_onebyte_static(scope, b"workerRuntime") .unwrap(); let bootstrap_fn = bootstrap_ns.get(scope, main_runtime_str.into()).unwrap(); let bootstrap_fn = v8::Local::<v8::Function>::try_from(bootstrap_fn).unwrap(); v8::Global::new(scope, bootstrap_fn) }; ( Self { id: options.worker_id, js_runtime, name: options.name, internal_handle, worker_type: options.worker_type, main_module: options.main_module, poll_for_messages_fn: None, has_message_event_listener_fn: None, bootstrap_fn_global: Some(bootstrap_fn_global), close_on_idle: options.close_on_idle, maybe_worker_metadata: options.maybe_worker_metadata, memory_trim_handle: None, maybe_coverage_dir: options.maybe_coverage_dir, }, external_handle, options.bootstrap, ) } pub fn bootstrap(&mut self, options: &BootstrapOptions) { let op_state = self.js_runtime.op_state(); op_state.borrow_mut().put(options.clone()); // Instead of using name for log we use `worker-${id}` because // WebWorkers can have empty string as name. { deno_core::scope!(scope, &mut self.js_runtime); let args = options.as_v8(scope); let bootstrap_fn = self.bootstrap_fn_global.take().unwrap(); let bootstrap_fn = v8::Local::new(scope, bootstrap_fn); let undefined = v8::undefined(scope); let mut worker_data: v8::Local<v8::Value> = v8::undefined(scope).into(); if let Some(data) = self.maybe_worker_metadata.take() { let js_transferables = serialize_transferables( &mut op_state.borrow_mut(), data.transferables, ); let js_message_data = JsMessageData { data: data.buffer, transferables: js_transferables, }; worker_data = deno_core::serde_v8::to_v8(scope, js_message_data).unwrap(); } let name_str: v8::Local<v8::Value> = v8::String::new(scope, &self.name).unwrap().into(); let id_str: v8::Local<v8::Value> = v8::String::new(scope, &format!("{}", self.id)) .unwrap() .into(); let id: v8::Local<v8::Value> = v8::Integer::new(scope, self.id.0 as i32).into(); let worker_type: v8::Local<v8::Value> = self.worker_type.to_v8(scope).into(); bootstrap_fn .call( scope, undefined.into(), &[args, name_str, id_str, id, worker_type, worker_data], ) .unwrap(); let context = scope.get_current_context(); let global = context.global(scope); let poll_for_messages_str = v8::String::new_external_onebyte_static(scope, b"pollForMessages") .unwrap(); let poll_for_messages_fn = global .get(scope, poll_for_messages_str.into()) .expect("get globalThis.pollForMessages"); global.delete(scope, poll_for_messages_str.into()); self.poll_for_messages_fn = Some(v8::Global::new(scope, poll_for_messages_fn)); let has_message_event_listener_str = v8::String::new_external_onebyte_static( scope, b"hasMessageEventListener", ) .unwrap(); let has_message_event_listener_fn = global .get(scope, has_message_event_listener_str.into()) .expect("get globalThis.hasMessageEventListener"); global.delete(scope, has_message_event_listener_str.into()); self.has_message_event_listener_fn = Some(v8::Global::new(scope, has_message_event_listener_fn)); } } pub fn maybe_setup_coverage_collector( &mut self, ) -> Option<CoverageCollector> { let coverage_dir = self.maybe_coverage_dir.as_ref()?; let mut coverage_collector = CoverageCollector::new(&mut self.js_runtime, coverage_dir.clone()); coverage_collector.start_collecting(); Some(coverage_collector) } #[cfg(not(target_os = "linux"))] pub fn setup_memory_trim_handler(&mut self) { // Noop } /// Sets up a handler that responds to SIGUSR2 signals by trimming unused /// memory and notifying V8 of low memory conditions. /// Note that this must be called within a tokio runtime. /// Calling this method multiple times will be a no-op. #[cfg(target_os = "linux")] pub fn setup_memory_trim_handler(&mut self) { if self.memory_trim_handle.is_some() { return; } if !*MEMORY_TRIM_HANDLER_ENABLED { return; } let mut sigusr2_rx = SIGUSR2_RX.clone(); let spawner = self .js_runtime .op_state() .borrow() .borrow::<deno_core::V8CrossThreadTaskSpawner>() .clone(); let memory_trim_handle = tokio::spawn(async move { loop { if sigusr2_rx.changed().await.is_err() { break; } spawner.spawn(move |isolate| { isolate.low_memory_notification(); }); } }); self.memory_trim_handle = Some(memory_trim_handle); } /// See [JsRuntime::execute_script](deno_core::JsRuntime::execute_script) #[allow(clippy::result_large_err)] pub fn execute_script( &mut self, name: &'static str, source_code: ModuleCodeString, ) -> Result<(), CoreError> { self.js_runtime.execute_script(name, source_code)?; Ok(()) } /// Loads and instantiates specified JavaScript module as "main" module. pub async fn preload_main_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, CoreError> { self.js_runtime.load_main_es_module(module_specifier).await } /// Loads and instantiates specified JavaScript module as "side" module. pub async fn preload_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, CoreError> { self.js_runtime.load_side_es_module(module_specifier).await } /// Loads, instantiates and executes specified JavaScript module. /// /// This method assumes that worker can't be terminated when executing /// side module code. pub async fn execute_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), CoreError> { let id = self.preload_side_module(module_specifier).await?; let mut receiver = self.js_runtime.mod_evaluate(id); tokio::select! { biased; maybe_result = &mut receiver => { debug!("received module evaluate {:#?}", maybe_result); maybe_result } event_loop_result = self.js_runtime.run_event_loop(PollEventLoopOptions::default()) => { event_loop_result?; receiver.await } } } /// Loads, instantiates and executes specified JavaScript module. /// /// This module will have "import.meta.main" equal to true. pub async fn execute_main_module( &mut self, id: ModuleId, ) -> Result<(), CoreError> { let mut receiver = self.js_runtime.mod_evaluate(id); let poll_options = PollEventLoopOptions::default(); tokio::select! { biased; maybe_result = &mut receiver => { debug!("received worker module evaluate {:#?}", maybe_result); maybe_result } event_loop_result = self.run_event_loop(poll_options) => { if self.internal_handle.is_terminated() { return Ok(()); } event_loop_result?; receiver.await } } } fn poll_event_loop( &mut self, cx: &mut Context, poll_options: PollEventLoopOptions, ) -> Poll<Result<(), CoreError>> { // If awakened because we are terminating, just return Ok if self.internal_handle.terminate_if_needed() { return Poll::Ready(Ok(())); } self.internal_handle.terminate_waker.register(cx.waker()); match self.js_runtime.poll_event_loop(cx, poll_options) { Poll::Ready(r) => { // If js ended because we are terminating, just return Ok if self.internal_handle.terminate_if_needed() { return Poll::Ready(Ok(())); } if let Err(e) = r { return Poll::Ready(Err(e)); } if self.close_on_idle {
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/subprocess_windows/src/lib.rs
runtime/subprocess_windows/src/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. // Parts adapted from tokio, license below // MIT License // // Copyright (c) Tokio Contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #![allow(clippy::undocumented_unsafe_blocks)] #![cfg(windows)] #[cfg(test)] mod tests; mod process; mod process_stdio; mod anon_pipe; mod env; mod uv_error; mod widestr; use std::borrow::Cow; use std::ffi::OsStr; use std::ffi::OsString; use std::future::Future; use std::io; use std::io::Read; use std::os::windows::io::FromRawHandle; use std::os::windows::io::IntoRawHandle; use std::os::windows::process::ExitStatusExt; use std::os::windows::raw::HANDLE; use std::path::Path; use std::pin::Pin; use std::process::ChildStderr; use std::process::ChildStdin; use std::process::ChildStdout; use std::process::ExitStatus; use std::process::Output; use std::task::Context; use std::task::Poll; use anon_pipe::read2; use env::CommandEnv; pub use process::process_kill; pub use process_stdio::disable_stdio_inheritance; use crate::process::*; use crate::process_stdio::*; #[derive(Debug)] pub enum Stdio { Inherit, Pipe, Null, RawHandle(HANDLE), } impl From<Stdio> for std::process::Stdio { fn from(stdio: Stdio) -> Self { match stdio { Stdio::Inherit => std::process::Stdio::inherit(), Stdio::Pipe => std::process::Stdio::piped(), Stdio::Null => std::process::Stdio::null(), Stdio::RawHandle(handle) => unsafe { std::process::Stdio::from_raw_handle(handle) }, } } } impl Stdio { pub fn inherit() -> Self { Stdio::Inherit } pub fn piped() -> Self { Stdio::Pipe } pub fn null() -> Self { Stdio::Null } } impl<T: IntoRawHandle> From<T> for Stdio { fn from(value: T) -> Self { Stdio::RawHandle(value.into_raw_handle()) } } pub struct Child { inner: FusedChild, pub stdin: Option<ChildStdin>, pub stdout: Option<ChildStdout>, pub stderr: Option<ChildStderr>, } /// An interface for killing a running process. /// Copied from https://github.com/tokio-rs/tokio/blob/ab8d7b82a1252b41dc072f641befb6d2afcb3373/tokio/src/process/kill.rs pub(crate) trait Kill { /// Forcefully kills the process. fn kill(&mut self) -> io::Result<()>; } impl<T: Kill> Kill for &mut T { fn kill(&mut self) -> io::Result<()> { (**self).kill() } } /// A drop guard which can ensure the child process is killed on drop if specified. /// /// From https://github.com/tokio-rs/tokio/blob/ab8d7b82a1252b41dc072f641befb6d2afcb3373/tokio/src/process/mod.rs #[derive(Debug)] struct ChildDropGuard<T: Kill> { inner: T, kill_on_drop: bool, } impl<T: Kill> Kill for ChildDropGuard<T> { fn kill(&mut self) -> io::Result<()> { let ret = self.inner.kill(); if ret.is_ok() { self.kill_on_drop = false; } ret } } impl<T: Kill> Drop for ChildDropGuard<T> { fn drop(&mut self) { if self.kill_on_drop { drop(self.kill()); } } } // copied from https://github.com/tokio-rs/tokio/blob/ab8d7b82a1252b41dc072f641befb6d2afcb3373/tokio/src/process/mod.rs impl<T, E, F> Future for ChildDropGuard<F> where F: Future<Output = Result<T, E>> + Kill + Unpin, { type Output = Result<T, E>; fn poll( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Self::Output> { let ret = Pin::new(&mut self.inner).poll(cx); if let Poll::Ready(Ok(_)) = ret { // Avoid the overhead of trying to kill a reaped process self.kill_on_drop = false; } ret } } /// Keeps track of the exit status of a child process without worrying about /// polling the underlying futures even after they have completed. /// /// From https://github.com/tokio-rs/tokio/blob/ab8d7b82a1252b41dc072f641befb6d2afcb3373/tokio/src/process/mod.rs #[derive(Debug)] enum FusedChild { Child(ChildDropGuard<ChildProcess>), Done(i32), } impl Child { pub fn id(&self) -> Option<u32> { match &self.inner { FusedChild::Child(child) => Some(child.inner.pid() as u32), FusedChild::Done(_) => None, } } pub fn wait_blocking(&mut self) -> Result<ExitStatus, std::io::Error> { drop(self.stdin.take()); match &mut self.inner { FusedChild::Child(child) => child .inner .wait() .map(|code| ExitStatus::from_raw(code as u32)), FusedChild::Done(code) => Ok(ExitStatus::from_raw(*code as u32)), } } pub async fn wait(&mut self) -> io::Result<ExitStatus> { // Ensure stdin is closed so the child isn't stuck waiting on // input while the parent is waiting for it to exit. drop(self.stdin.take()); match &mut self.inner { FusedChild::Done(exit) => Ok(ExitStatus::from_raw(*exit as u32)), FusedChild::Child(child) => { let ret = child.await; if let Ok(exit) = ret { self.inner = FusedChild::Done(exit); } ret.map(|code| ExitStatus::from_raw(code as u32)) } } } pub fn try_wait(&mut self) -> Result<Option<i32>, std::io::Error> { match &mut self.inner { FusedChild::Done(exit) => Ok(Some(*exit)), FusedChild::Child(child) => child.inner.try_wait(), } } // from std pub fn wait_with_output(&mut self) -> io::Result<Output> { drop(self.stdin.take()); let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); match (self.stdout.take(), self.stderr.take()) { (None, None) => {} (Some(mut out), None) => { let res = out.read_to_end(&mut stdout); res.unwrap(); } (None, Some(mut err)) => { let res = err.read_to_end(&mut stderr); res.unwrap(); } (Some(out), Some(err)) => { let res = read2( unsafe { crate::anon_pipe::AnonPipe::from_raw_handle(out.into_raw_handle()) }, &mut stdout, unsafe { crate::anon_pipe::AnonPipe::from_raw_handle(err.into_raw_handle()) }, &mut stderr, ); res.unwrap(); } } let status = self.wait_blocking()?; Ok(Output { status, stdout, stderr, }) } } pub struct Command { program: OsString, args: Vec<OsString>, envs: CommandEnv, detached: bool, cwd: Option<OsString>, stdin: Stdio, stdout: Stdio, stderr: Stdio, extra_handles: Vec<Option<HANDLE>>, kill_on_drop: bool, verbatim_arguments: bool, } impl Command { pub fn new<S: AsRef<OsStr>>(program: S) -> Self { Self { program: program.as_ref().to_os_string(), args: vec![program.as_ref().to_os_string()], envs: CommandEnv::default(), detached: false, cwd: None, stdin: Stdio::Inherit, stdout: Stdio::Inherit, stderr: Stdio::Inherit, extra_handles: vec![], kill_on_drop: false, verbatim_arguments: false, } } pub fn verbatim_arguments(&mut self, verbatim: bool) -> &mut Self { self.verbatim_arguments = verbatim; self } pub fn get_current_dir(&self) -> Option<&Path> { self.cwd.as_deref().map(Path::new) } pub fn current_dir<S: AsRef<Path>>(&mut self, cwd: S) -> &mut Self { self.cwd = Some(cwd.as_ref().to_path_buf().into_os_string()); self } pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self { self.args.push(arg.as_ref().to_os_string()); self } pub fn args<I: IntoIterator<Item = S>, S: AsRef<OsStr>>( &mut self, args: I, ) -> &mut Self { self .args .extend(args.into_iter().map(|a| a.as_ref().to_os_string())); self } pub fn env<S: AsRef<OsStr>, T: AsRef<OsStr>>( &mut self, key: S, value: T, ) -> &mut Self { self.envs.set(key.as_ref(), value.as_ref()); self } pub fn get_program(&self) -> &OsStr { self.program.as_os_str() } pub fn get_args(&self) -> impl Iterator<Item = &OsStr> { self.args.iter().skip(1).map(|a| a.as_os_str()) } pub fn envs< I: IntoIterator<Item = (S, T)>, S: AsRef<OsStr>, T: AsRef<OsStr>, >( &mut self, envs: I, ) -> &mut Self { for (k, v) in envs { self.envs.set(k.as_ref(), v.as_ref()); } self } pub fn kill_on_drop(&mut self, kill_on_drop: bool) -> &mut Self { self.kill_on_drop = kill_on_drop; self } pub fn detached(&mut self) -> &mut Self { self.detached = true; self.kill_on_drop = false; self } pub fn env_clear(&mut self) -> &mut Self { self.envs.clear(); self } pub fn stdin(&mut self, stdin: Stdio) -> &mut Self { self.stdin = stdin; self } pub fn stdout(&mut self, stdout: Stdio) -> &mut Self { self.stdout = stdout; self } pub fn stderr(&mut self, stderr: Stdio) -> &mut Self { self.stderr = stderr; self } pub fn extra_handle(&mut self, handle: Option<HANDLE>) -> &mut Self { self.extra_handles.push(handle); self } pub fn spawn(&mut self) -> Result<Child, std::io::Error> { let mut flags = 0; if self.detached { flags |= uv_process_flags::Detached; } if self.verbatim_arguments { flags |= uv_process_flags::WindowsVerbatimArguments; } let (stdin, child_stdin) = match self.stdin { Stdio::Pipe => { let pipes = crate::anon_pipe::anon_pipe(false, true)?; let child_stdin_handle = pipes.ours.into_handle(); let stdin_handle = pipes.theirs.into_handle().into_raw_handle(); ( StdioContainer::RawHandle(stdin_handle), Some(ChildStdin::from(child_stdin_handle)), ) } Stdio::Null => (StdioContainer::Ignore, None), Stdio::Inherit => (StdioContainer::InheritFd(0), None), Stdio::RawHandle(handle) => (StdioContainer::RawHandle(handle), None), }; let (stdout, child_stdout) = match self.stdout { Stdio::Pipe => { let pipes = crate::anon_pipe::anon_pipe(true, true)?; let child_stdout_handle = pipes.ours.into_handle(); let stdout_handle = pipes.theirs.into_handle().into_raw_handle(); ( StdioContainer::RawHandle(stdout_handle), Some(ChildStdout::from(child_stdout_handle)), ) } Stdio::Null => (StdioContainer::Ignore, None), Stdio::Inherit => (StdioContainer::InheritFd(1), None), Stdio::RawHandle(handle) => (StdioContainer::RawHandle(handle), None), }; let (stderr, child_stderr) = match self.stderr { Stdio::Pipe => { let pipes = crate::anon_pipe::anon_pipe(true, true)?; let child_stderr_handle = pipes.ours.into_handle(); let stderr_handle = pipes.theirs.into_handle().into_raw_handle(); ( StdioContainer::RawHandle(stderr_handle), Some(ChildStderr::from(child_stderr_handle)), ) } Stdio::Null => (StdioContainer::Ignore, None), Stdio::Inherit => (StdioContainer::InheritFd(2), None), Stdio::RawHandle(handle) => (StdioContainer::RawHandle(handle), None), }; let mut stdio = Vec::with_capacity(3 + self.extra_handles.len()); stdio.extend([stdin, stdout, stderr]); stdio.extend(self.extra_handles.iter().map(|h| { h.map(StdioContainer::RawHandle) .unwrap_or(StdioContainer::Ignore) })); crate::process::spawn(&SpawnOptions { flags, file: Cow::Borrowed(&self.program), args: self .args .iter() .map(|a| Cow::Borrowed(a.as_os_str())) .collect(), env: &self.envs, cwd: self.cwd.as_deref().map(Cow::Borrowed), stdio, }) .map_err(|err| std::io::Error::other(err.to_string())) .map(|process| Child { inner: FusedChild::Child(ChildDropGuard { inner: process, kill_on_drop: self.kill_on_drop, }), stdin: child_stdin, stdout: child_stdout, stderr: child_stderr, }) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/subprocess_windows/src/uv_error.rs
runtime/subprocess_windows/src/uv_error.rs
// Copyright 2018-2025 the Deno authors. MIT license. // ported straight from libuv use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED; use windows_sys::Win32::Foundation::ERROR_ADDRESS_ALREADY_ASSOCIATED; use windows_sys::Win32::Foundation::ERROR_ALREADY_EXISTS; use windows_sys::Win32::Foundation::ERROR_BAD_EXE_FORMAT; use windows_sys::Win32::Foundation::ERROR_BAD_PATHNAME; use windows_sys::Win32::Foundation::ERROR_BAD_PIPE; use windows_sys::Win32::Foundation::ERROR_BEGINNING_OF_MEDIA; use windows_sys::Win32::Foundation::ERROR_BROKEN_PIPE; use windows_sys::Win32::Foundation::ERROR_BUFFER_OVERFLOW; use windows_sys::Win32::Foundation::ERROR_BUS_RESET; use windows_sys::Win32::Foundation::ERROR_CANNOT_MAKE; use windows_sys::Win32::Foundation::ERROR_CANT_ACCESS_FILE; use windows_sys::Win32::Foundation::ERROR_CANT_RESOLVE_FILENAME; use windows_sys::Win32::Foundation::ERROR_CONNECTION_ABORTED; use windows_sys::Win32::Foundation::ERROR_CONNECTION_REFUSED; use windows_sys::Win32::Foundation::ERROR_CRC; use windows_sys::Win32::Foundation::ERROR_DEVICE_DOOR_OPEN; use windows_sys::Win32::Foundation::ERROR_DEVICE_REQUIRES_CLEANING; use windows_sys::Win32::Foundation::ERROR_DIR_NOT_EMPTY; use windows_sys::Win32::Foundation::ERROR_DIRECTORY; use windows_sys::Win32::Foundation::ERROR_DISK_CORRUPT; use windows_sys::Win32::Foundation::ERROR_DISK_FULL; use windows_sys::Win32::Foundation::ERROR_EA_TABLE_FULL; use windows_sys::Win32::Foundation::ERROR_ELEVATION_REQUIRED; use windows_sys::Win32::Foundation::ERROR_END_OF_MEDIA; use windows_sys::Win32::Foundation::ERROR_ENVVAR_NOT_FOUND; use windows_sys::Win32::Foundation::ERROR_EOM_OVERFLOW; use windows_sys::Win32::Foundation::ERROR_FILE_EXISTS; use windows_sys::Win32::Foundation::ERROR_FILE_NOT_FOUND; use windows_sys::Win32::Foundation::ERROR_FILEMARK_DETECTED; use windows_sys::Win32::Foundation::ERROR_FILENAME_EXCED_RANGE; use windows_sys::Win32::Foundation::ERROR_GEN_FAILURE; use windows_sys::Win32::Foundation::ERROR_HANDLE_DISK_FULL; use windows_sys::Win32::Foundation::ERROR_HOST_UNREACHABLE; use windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER; use windows_sys::Win32::Foundation::ERROR_INVALID_BLOCK_LENGTH; use windows_sys::Win32::Foundation::ERROR_INVALID_DATA; use windows_sys::Win32::Foundation::ERROR_INVALID_DRIVE; use windows_sys::Win32::Foundation::ERROR_INVALID_FLAGS; use windows_sys::Win32::Foundation::ERROR_INVALID_FUNCTION; use windows_sys::Win32::Foundation::ERROR_INVALID_HANDLE; use windows_sys::Win32::Foundation::ERROR_INVALID_NAME; use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER; use windows_sys::Win32::Foundation::ERROR_INVALID_REPARSE_DATA; use windows_sys::Win32::Foundation::ERROR_IO_DEVICE; use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION; use windows_sys::Win32::Foundation::ERROR_META_EXPANSION_TOO_LONG; use windows_sys::Win32::Foundation::ERROR_MOD_NOT_FOUND; use windows_sys::Win32::Foundation::ERROR_NETNAME_DELETED; use windows_sys::Win32::Foundation::ERROR_NETWORK_UNREACHABLE; use windows_sys::Win32::Foundation::ERROR_NO_DATA; use windows_sys::Win32::Foundation::ERROR_NO_DATA_DETECTED; use windows_sys::Win32::Foundation::ERROR_NO_SIGNAL_SENT; use windows_sys::Win32::Foundation::ERROR_NO_UNICODE_TRANSLATION; use windows_sys::Win32::Foundation::ERROR_NOACCESS; use windows_sys::Win32::Foundation::ERROR_NOT_CONNECTED; use windows_sys::Win32::Foundation::ERROR_NOT_ENOUGH_MEMORY; use windows_sys::Win32::Foundation::ERROR_NOT_SAME_DEVICE; use windows_sys::Win32::Foundation::ERROR_NOT_SUPPORTED; use windows_sys::Win32::Foundation::ERROR_OPEN_FAILED; use windows_sys::Win32::Foundation::ERROR_OPERATION_ABORTED; use windows_sys::Win32::Foundation::ERROR_OUTOFMEMORY; use windows_sys::Win32::Foundation::ERROR_PATH_NOT_FOUND; use windows_sys::Win32::Foundation::ERROR_PIPE_BUSY; use windows_sys::Win32::Foundation::ERROR_PIPE_NOT_CONNECTED; use windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD; use windows_sys::Win32::Foundation::ERROR_SEM_TIMEOUT; use windows_sys::Win32::Foundation::ERROR_SETMARK_DETECTED; use windows_sys::Win32::Foundation::ERROR_SHARING_VIOLATION; use windows_sys::Win32::Foundation::ERROR_SIGNAL_REFUSED; use windows_sys::Win32::Foundation::ERROR_SYMLINK_NOT_SUPPORTED; use windows_sys::Win32::Foundation::ERROR_TOO_MANY_OPEN_FILES; use windows_sys::Win32::Foundation::ERROR_WRITE_PROTECT; pub const UV_E2BIG: i32 = -7; pub const UV_EACCES: i32 = -13; pub const UV_EADDRINUSE: i32 = -98; pub const UV_EAGAIN: i32 = -11; pub const UV_EBADF: i32 = -9; pub const UV_EBUSY: i32 = -16; pub const UV_ECANCELED: i32 = -125; pub const UV_ECHARSET: i32 = -4080; pub const UV_ECONNABORTED: i32 = -103; pub const UV_ECONNREFUSED: i32 = -111; pub const UV_ECONNRESET: i32 = -104; pub const UV_EEXIST: i32 = -17; pub const UV_EFAULT: i32 = -14; pub const UV_EHOSTUNREACH: i32 = -113; pub const UV_EINVAL: i32 = -22; pub const UV_EIO: i32 = -5; pub const UV_EISDIR: i32 = -21; pub const UV_ELOOP: i32 = -40; pub const UV_EMFILE: i32 = -24; pub const UV_ENAMETOOLONG: i32 = -36; pub const UV_ENETUNREACH: i32 = -101; pub const UV_ENOENT: i32 = -2; pub const UV_ENOMEM: i32 = -12; pub const UV_ENOSPC: i32 = -28; pub const UV_ENOTCONN: i32 = -107; pub const UV_ENOTEMPTY: i32 = -39; pub const UV_ENOTSUP: i32 = -95; pub const UV_EOF: i32 = -4095; pub const UV_EPERM: i32 = -1; pub const UV_EPIPE: i32 = -32; pub const UV_EROFS: i32 = -30; pub const UV_ETIMEDOUT: i32 = -110; pub const UV_EXDEV: i32 = -18; pub const UV_EFTYPE: i32 = -4028; pub const UV_UNKNOWN: i32 = -4094; pub const UV_ESRCH: i32 = -4040; pub fn uv_translate_sys_error(sys_errno: u32) -> i32 { match sys_errno { ERROR_ELEVATION_REQUIRED => UV_EACCES, ERROR_CANT_ACCESS_FILE => UV_EACCES, ERROR_ADDRESS_ALREADY_ASSOCIATED => UV_EADDRINUSE, ERROR_NO_DATA => UV_EAGAIN, ERROR_INVALID_FLAGS => UV_EBADF, ERROR_INVALID_HANDLE => UV_EBADF, ERROR_LOCK_VIOLATION => UV_EBUSY, ERROR_PIPE_BUSY => UV_EBUSY, ERROR_SHARING_VIOLATION => UV_EBUSY, ERROR_OPERATION_ABORTED => UV_ECANCELED, ERROR_NO_UNICODE_TRANSLATION => UV_ECHARSET, ERROR_CONNECTION_ABORTED => UV_ECONNABORTED, ERROR_CONNECTION_REFUSED => UV_ECONNREFUSED, ERROR_NETNAME_DELETED => UV_ECONNRESET, ERROR_ALREADY_EXISTS => UV_EEXIST, ERROR_FILE_EXISTS => UV_EEXIST, ERROR_NOACCESS => UV_EFAULT, ERROR_HOST_UNREACHABLE => UV_EHOSTUNREACH, ERROR_INSUFFICIENT_BUFFER => UV_EINVAL, ERROR_INVALID_DATA => UV_EINVAL, ERROR_INVALID_PARAMETER => UV_EINVAL, ERROR_SYMLINK_NOT_SUPPORTED => UV_EINVAL, ERROR_BEGINNING_OF_MEDIA => UV_EIO, ERROR_BUS_RESET => UV_EIO, ERROR_CRC => UV_EIO, ERROR_DEVICE_DOOR_OPEN => UV_EIO, ERROR_DEVICE_REQUIRES_CLEANING => UV_EIO, ERROR_DISK_CORRUPT => UV_EIO, ERROR_EOM_OVERFLOW => UV_EIO, ERROR_FILEMARK_DETECTED => UV_EIO, ERROR_GEN_FAILURE => UV_EIO, ERROR_INVALID_BLOCK_LENGTH => UV_EIO, ERROR_IO_DEVICE => UV_EIO, ERROR_NO_DATA_DETECTED => UV_EIO, ERROR_NO_SIGNAL_SENT => UV_EIO, ERROR_OPEN_FAILED => UV_EIO, ERROR_SETMARK_DETECTED => UV_EIO, ERROR_SIGNAL_REFUSED => UV_EIO, ERROR_CANT_RESOLVE_FILENAME => UV_ELOOP, ERROR_TOO_MANY_OPEN_FILES => UV_EMFILE, ERROR_BUFFER_OVERFLOW => UV_ENAMETOOLONG, ERROR_FILENAME_EXCED_RANGE => UV_ENAMETOOLONG, ERROR_NETWORK_UNREACHABLE => UV_ENETUNREACH, ERROR_BAD_PATHNAME => UV_ENOENT, ERROR_DIRECTORY => UV_ENOENT, ERROR_ENVVAR_NOT_FOUND => UV_ENOENT, ERROR_FILE_NOT_FOUND => UV_ENOENT, ERROR_INVALID_NAME => UV_ENOENT, ERROR_INVALID_DRIVE => UV_ENOENT, ERROR_INVALID_REPARSE_DATA => UV_ENOENT, ERROR_MOD_NOT_FOUND => UV_ENOENT, ERROR_PATH_NOT_FOUND => UV_ENOENT, ERROR_NOT_ENOUGH_MEMORY => UV_ENOMEM, ERROR_OUTOFMEMORY => UV_ENOMEM, ERROR_CANNOT_MAKE => UV_ENOSPC, ERROR_DISK_FULL => UV_ENOSPC, ERROR_EA_TABLE_FULL => UV_ENOSPC, ERROR_END_OF_MEDIA => UV_ENOSPC, ERROR_HANDLE_DISK_FULL => UV_ENOSPC, ERROR_NOT_CONNECTED => UV_ENOTCONN, ERROR_DIR_NOT_EMPTY => UV_ENOTEMPTY, ERROR_NOT_SUPPORTED => UV_ENOTSUP, ERROR_BROKEN_PIPE => UV_EOF, ERROR_ACCESS_DENIED => UV_EPERM, ERROR_PRIVILEGE_NOT_HELD => UV_EPERM, ERROR_BAD_PIPE => UV_EPIPE, ERROR_PIPE_NOT_CONNECTED => UV_EPIPE, ERROR_WRITE_PROTECT => UV_EROFS, ERROR_SEM_TIMEOUT => UV_ETIMEDOUT, ERROR_NOT_SAME_DEVICE => UV_EXDEV, ERROR_INVALID_FUNCTION => UV_EISDIR, ERROR_META_EXPANSION_TOO_LONG => UV_E2BIG, ERROR_BAD_EXE_FORMAT => UV_EFTYPE, _ => UV_UNKNOWN, } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/subprocess_windows/src/process.rs
runtime/subprocess_windows/src/process.rs
// Copyright 2018-2025 the Deno authors. MIT license. /* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ // Ported partly from https://github.com/libuv/libuv/blob/b00c5d1a09c094020044e79e19f478a25b8e1431/src/win/process.c #![allow(nonstandard_style)] use std::borrow::Cow; use std::ffi::CStr; use std::ffi::OsStr; use std::future::Future; use std::io; use std::mem; use std::ops::BitAnd; use std::ops::BitAndAssign; use std::ops::BitOr; use std::ops::BitOrAssign; use std::os::windows::ffi::OsStrExt; use std::os::windows::io::AsRawHandle; use std::os::windows::io::FromRawHandle; use std::os::windows::io::OwnedHandle; use std::pin::Pin; use std::ptr::null_mut; use std::ptr::{self}; use std::sync::OnceLock; use std::task::Poll; use futures_channel::oneshot; use windows_sys::Win32::Foundation::BOOL; use windows_sys::Win32::Foundation::BOOLEAN; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED; use windows_sys::Win32::Foundation::ERROR_INVALID_PARAMETER; use windows_sys::Win32::Foundation::ERROR_SUCCESS; use windows_sys::Win32::Foundation::FALSE; use windows_sys::Win32::Foundation::GENERIC_WRITE; use windows_sys::Win32::Foundation::GetLastError; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; use windows_sys::Win32::Foundation::LocalFree; use windows_sys::Win32::Foundation::STILL_ACTIVE; use windows_sys::Win32::Foundation::TRUE; use windows_sys::Win32::Foundation::WAIT_FAILED; use windows_sys::Win32::Foundation::WAIT_OBJECT_0; use windows_sys::Win32::Foundation::WAIT_TIMEOUT; use windows_sys::Win32::Globalization::GetSystemDefaultLangID; use windows_sys::Win32::Security::SECURITY_ATTRIBUTES; use windows_sys::Win32::Storage::FileSystem::CREATE_NEW; use windows_sys::Win32::Storage::FileSystem::CreateDirectoryW; use windows_sys::Win32::Storage::FileSystem::CreateFileW; use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL; use windows_sys::Win32::Storage::FileSystem::FILE_DISPOSITION_INFO; use windows_sys::Win32::Storage::FileSystem::FileDispositionInfo; use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW; use windows_sys::Win32::Storage::FileSystem::SYNCHRONIZE; use windows_sys::Win32::Storage::FileSystem::SetFileInformationByHandle; use windows_sys::Win32::System::Com::CoTaskMemFree; use windows_sys::Win32::System::Diagnostics::Debug::FORMAT_MESSAGE_ALLOCATE_BUFFER; use windows_sys::Win32::System::Diagnostics::Debug::FORMAT_MESSAGE_FROM_SYSTEM; use windows_sys::Win32::System::Diagnostics::Debug::FORMAT_MESSAGE_IGNORE_INSERTS; use windows_sys::Win32::System::Diagnostics::Debug::FormatMessageA; use windows_sys::Win32::System::Diagnostics::Debug::MINIDUMP_TYPE; use windows_sys::Win32::System::Diagnostics::Debug::MiniDumpIgnoreInaccessibleMemory; use windows_sys::Win32::System::Diagnostics::Debug::MiniDumpWithFullMemory; use windows_sys::Win32::System::Diagnostics::Debug::MiniDumpWriteDump; use windows_sys::Win32::System::Diagnostics::Debug::SymGetOptions; use windows_sys::Win32::System::Diagnostics::Debug::SymSetOptions; use windows_sys::Win32::System::Environment::NeedCurrentDirectoryForExePathW; use windows_sys::Win32::System::ProcessStatus::GetModuleBaseNameW; use windows_sys::Win32::System::Registry::HKEY; use windows_sys::Win32::System::Registry::HKEY_LOCAL_MACHINE; use windows_sys::Win32::System::Registry::KEY_QUERY_VALUE; use windows_sys::Win32::System::Registry::RRF_RT_ANY; use windows_sys::Win32::System::Registry::RegCloseKey; use windows_sys::Win32::System::Registry::RegGetValueW; use windows_sys::Win32::System::Registry::RegOpenKeyExW; use windows_sys::Win32::System::SystemInformation::GetSystemDirectoryW; use windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP; use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW; use windows_sys::Win32::System::Threading::CREATE_SUSPENDED; use windows_sys::Win32::System::Threading::CREATE_UNICODE_ENVIRONMENT; use windows_sys::Win32::System::Threading::CreateProcessW; use windows_sys::Win32::System::Threading::DETACHED_PROCESS; use windows_sys::Win32::System::Threading::GetCurrentProcess; use windows_sys::Win32::System::Threading::GetExitCodeProcess; use windows_sys::Win32::System::Threading::GetProcessId; use windows_sys::Win32::System::Threading::INFINITE; use windows_sys::Win32::System::Threading::OpenProcess; use windows_sys::Win32::System::Threading::PROCESS_INFORMATION; use windows_sys::Win32::System::Threading::PROCESS_QUERY_INFORMATION; use windows_sys::Win32::System::Threading::PROCESS_TERMINATE; use windows_sys::Win32::System::Threading::RegisterWaitForSingleObject; use windows_sys::Win32::System::Threading::ResumeThread; use windows_sys::Win32::System::Threading::STARTF_USESHOWWINDOW; use windows_sys::Win32::System::Threading::STARTF_USESTDHANDLES; use windows_sys::Win32::System::Threading::STARTUPINFOW; use windows_sys::Win32::System::Threading::TerminateProcess; use windows_sys::Win32::System::Threading::UnregisterWaitEx; use windows_sys::Win32::System::Threading::WT_EXECUTEINWAITTHREAD; use windows_sys::Win32::System::Threading::WT_EXECUTEONLYONCE; use windows_sys::Win32::System::Threading::WaitForSingleObject; use windows_sys::Win32::UI::Shell::FOLDERID_LocalAppData; use windows_sys::Win32::UI::Shell::SHGetKnownFolderPath; use windows_sys::Win32::UI::WindowsAndMessaging::SW_HIDE; use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWDEFAULT; use windows_sys::w; use crate::env::CommandEnv; use crate::env::EnvKey; use crate::process_stdio::StdioContainer; use crate::process_stdio::free_stdio_buffer; use crate::process_stdio::uv_stdio_create; use crate::uv_error; use crate::widestr::WCStr; use crate::widestr::WCString; unsafe extern "C" { fn wcsncpy(dest: *mut u16, src: *const u16, count: usize) -> *mut u16; fn wcspbrk(str: *const u16, accept: *const u16) -> *const u16; } unsafe fn wcslen(mut str: *const u16) -> usize { let mut len = 0; while unsafe { *str != 0 } { len += 1; str = str.wrapping_add(1); } len } fn get_last_error() -> u32 { unsafe { GetLastError() } } struct GlobalJobHandle(HANDLE); unsafe impl Send for GlobalJobHandle {} unsafe impl Sync for GlobalJobHandle {} static UV_GLOBAL_JOB_HANDLE: OnceLock<GlobalJobHandle> = OnceLock::new(); fn uv_fatal_error_with_no(syscall: &str, errno: Option<u32>) { let errno = errno.unwrap_or_else(|| unsafe { GetLastError() }); let mut buf: *mut i8 = null_mut(); unsafe { FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, null_mut(), errno, GetSystemDefaultLangID().into(), (&raw mut buf).cast(), 0, null_mut(), ); } let errmsg = if buf.is_null() { "Unknown error" } else { unsafe { CStr::from_ptr(buf).to_str().unwrap() } }; let msg = if syscall.is_empty() { format!("({}) {}", errno, errmsg) } else { format!("{}: ({}) {}", syscall, errno, errmsg) }; if !buf.is_null() { unsafe { LocalFree(buf.cast()) }; } panic!("{}", msg); } fn uv_fatal_error(syscall: &str) { uv_fatal_error_with_no(syscall, None) } fn uv_init_global_job_handle() { use windows_sys::Win32::System::JobObjects::*; UV_GLOBAL_JOB_HANDLE.get_or_init(|| { unsafe { // SAFETY: SECURITY_ATTRIBUTES is a POD type, repr(C) let mut attr = mem::zeroed::<SECURITY_ATTRIBUTES>(); // SAFETY: JOBOBJECT_EXTENDED_LIMIT_INFORMATION is a POD type, repr(C) let mut info = mem::zeroed::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>(); attr.bInheritHandle = FALSE; info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_BREAKAWAY_OK | JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; // SAFETY: called with valid parameters let job = CreateJobObjectW(&attr, ptr::null()); if job.is_null() { uv_fatal_error("CreateJobObjectW"); } if SetInformationJobObject( job, JobObjectExtendedLimitInformation, &raw const info as _, mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32, ) == 0 { uv_fatal_error("SetInformationJobObject"); } if AssignProcessToJobObject(job, GetCurrentProcess()) == 0 { let err = GetLastError(); if err != ERROR_ACCESS_DENIED { uv_fatal_error_with_no("AssignProcessToJobObject", Some(err)); } } GlobalJobHandle(job) } }); } #[derive(Debug)] struct Waiting { rx: oneshot::Receiver<()>, wait_object: HANDLE, tx: *mut Option<oneshot::Sender<()>>, } impl Drop for Waiting { fn drop(&mut self) { unsafe { let rc = UnregisterWaitEx(self.wait_object, INVALID_HANDLE_VALUE); if rc == 0 { panic!("failed to unregister: {}", io::Error::last_os_error()); } drop(Box::from_raw(self.tx)); } } } unsafe impl Sync for Waiting {} unsafe impl Send for Waiting {} pub struct SpawnOptions<'a> { // pub exit_cb: Option<fn(*const uv_process, u64, i32)>, pub flags: u32, pub file: Cow<'a, OsStr>, pub args: Vec<Cow<'a, OsStr>>, pub env: &'a CommandEnv, pub cwd: Option<Cow<'a, OsStr>>, pub stdio: Vec<super::process_stdio::StdioContainer>, } macro_rules! wchar { ($s: literal) => {{ const INPUT: char = $s; const OUTPUT: u16 = { let len = INPUT.len_utf16(); if len != 1 { panic!("wchar! macro requires a single UTF-16 character"); } let mut buf = [0; 1]; INPUT.encode_utf16(&mut buf); buf[0] }; OUTPUT }}; } fn quote_cmd_arg(src: &WCStr, target: &mut Vec<u16>) { let len = src.len(); if len == 0 { // Need double quotation for empty argument target.push(wchar!('"')); target.push(wchar!('"')); return; } debug_assert!(src.has_nul()); if unsafe { wcspbrk(src.as_ptr(), w!(" \t\"")) }.is_null() { // No quotation needed target.extend(src.wchars_no_null()); return; } if unsafe { wcspbrk(src.as_ptr(), w!("\"\\")) }.is_null() { // No embedded double quotes or backlashes, so I can just wrap // quote marks around the whole thing. target.push(wchar!('"')); target.extend(src.wchars_no_null()); target.push(wchar!('"')); return; } // Expected input/output: // input : hello"world // output: "hello\"world" // input : hello""world // output: "hello\"\"world" // input : hello\world // output: hello\world // input : hello\\world // output: hello\\world // input : hello\"world // output: "hello\\\"world" // input : hello\\"world // output: "hello\\\\\"world" // input : hello world\ // output: "hello world\\" target.push(wchar!('"')); let start = target.len(); let mut quote_hit = true; for i in (0..len).rev() { target.push(src[i]); if quote_hit && src[i] == wchar!('\\') { target.push(wchar!('\\')); } else if src[i] == wchar!('"') { quote_hit = true; target.push(wchar!('\\')); } else { quote_hit = false; } } target[start..].reverse(); target.push(wchar!('"')); } fn make_program_args( args: &[&OsStr], verbatim_arguments: bool, ) -> Result<WCString, std::io::Error> { let mut dst_len = 0; let mut temp_buffer_len = 0; // Count the required size. for arg in args { let arg_len = arg.encode_wide().count(); dst_len += arg_len; if arg_len > temp_buffer_len { temp_buffer_len = arg_len; } } // Adjust for potential quotes. Also assume the worst-case scenario that // every character needs escaping, so we need twice as much space. dst_len = dst_len * 2 + args.len() * 2; let mut dst = Vec::with_capacity(dst_len); let mut temp_buffer = Vec::with_capacity(temp_buffer_len); for (i, arg) in args.iter().enumerate() { temp_buffer.clear(); temp_buffer.extend(arg.encode_wide()); if verbatim_arguments { dst.extend(temp_buffer.as_slice()); } else { temp_buffer.push(0); quote_cmd_arg(WCStr::from_wchars(&temp_buffer), &mut dst); } if i < args.len() - 1 { dst.push(wchar!(' ')); } } let wcstring = WCString::from_vec(dst); Ok(wcstring) } fn cvt(result: BOOL) -> Result<(), std::io::Error> { if result == 0 { Err(std::io::Error::last_os_error()) } else { Ok(()) } } #[derive(Debug)] pub struct ChildProcess { pid: i32, handle: OwnedHandle, waiting: Option<Waiting>, } impl crate::Kill for ChildProcess { fn kill(&mut self) -> std::io::Result<()> { process_kill(self.pid, SIGTERM).map_err(|e| { if let Some(sys_error) = e.as_sys_error() { std::io::Error::from_raw_os_error(sys_error as i32) } else if e.as_uv_error() == uv_error::UV_ESRCH { std::io::Error::new( std::io::ErrorKind::InvalidInput, "Process not found", ) } else { std::io::Error::other(format!( "Failed to kill process: {}", e.as_uv_error() )) } }) } } impl ChildProcess { pub fn pid(&self) -> i32 { self.pid } pub fn try_wait(&mut self) -> Result<Option<i32>, std::io::Error> { unsafe { match WaitForSingleObject(self.handle.as_raw_handle(), 0) { WAIT_OBJECT_0 => {} WAIT_TIMEOUT => return Ok(None), // TODO: io error probably _ => { return Err(std::io::Error::last_os_error()); } } let mut status = 0; cvt(GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?; Ok(Some(status as i32)) } } pub fn wait(&mut self) -> Result<i32, std::io::Error> { unsafe { let res = WaitForSingleObject(self.handle.as_raw_handle(), INFINITE); if res != WAIT_OBJECT_0 { return Err(std::io::Error::last_os_error()); } let mut status = 0; cvt(GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?; Ok(status as i32) } } } unsafe extern "system" fn callback( ptr: *mut std::ffi::c_void, _timer_fired: BOOLEAN, ) { let complete = unsafe { &mut *(ptr as *mut Option<oneshot::Sender<()>>) }; let _ = complete.take().unwrap().send(()); } impl Future for ChildProcess { type Output = Result<i32, std::io::Error>; fn poll( self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Self::Output> { let inner = Pin::get_mut(self); loop { if let Some(ref mut w) = inner.waiting { match Pin::new(&mut w.rx).poll(cx) { Poll::Ready(Ok(())) => {} Poll::Ready(Err(_)) => panic!("should not be canceled"), Poll::Pending => return Poll::Pending, } let status = inner.try_wait()?.expect("not ready yet"); return Poll::Ready(Ok(status)); } if let Some(e) = inner.try_wait()? { return Poll::Ready(Ok(e)); } let (tx, rx) = oneshot::channel(); let ptr = Box::into_raw(Box::new(Some(tx))); let mut wait_object = null_mut(); let rc = unsafe { RegisterWaitForSingleObject( &mut wait_object, inner.handle.as_raw_handle() as _, Some(callback), ptr as *mut _, INFINITE, WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE, ) }; if rc == 0 { let err = io::Error::last_os_error(); drop(unsafe { Box::from_raw(ptr) }); return Poll::Ready(Err(err)); } inner.waiting = Some(Waiting { rx, wait_object, tx: ptr, }); } } } pub fn spawn(options: &SpawnOptions) -> Result<ChildProcess, std::io::Error> { let mut startup = unsafe { mem::zeroed::<STARTUPINFOW>() }; let mut info = unsafe { mem::zeroed::<PROCESS_INFORMATION>() }; if options.file.is_empty() || options.args.is_empty() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "Invalid arguments", )); } // Convert file path to UTF-16 let application = WCString::new(&options.file); // Create environment block if provided let env_saw_path = options.env.have_changed_path(); let maybe_env = options.env.capture_if_changed(); let child_paths = if env_saw_path { if let Some(env) = maybe_env.as_ref() { env.get(&EnvKey::new("PATH")).map(|s| s.as_os_str()) } else { None } } else { None }; // Handle current working directory let cwd = if let Some(cwd_option) = &options.cwd { // Explicit cwd WCString::new(cwd_option) } else { // Inherit cwd #[allow(clippy::disallowed_methods)] let cwd = std::env::current_dir().unwrap(); WCString::new(cwd) }; // If cwd is too long, shorten it let cwd = if cwd.len_no_nul() >= windows_sys::Win32::Foundation::MAX_PATH as usize { unsafe { let cwd_ptr = cwd.as_ptr(); let mut short_buf = vec![0u16; cwd.len_no_nul()]; let cwd_len = GetShortPathNameW( cwd_ptr, short_buf.as_mut_ptr(), cwd.len_no_nul() as u32, ); if cwd_len == 0 { return Err(std::io::Error::last_os_error()); } WCString::from_vec(short_buf) } } else { cwd }; // Get PATH environment variable let path = child_paths .map(|p| p.encode_wide().chain(Some(0)).collect::<Vec<_>>()) .or_else(|| { // PATH not found in provided environment, get system PATH std::env::var_os("PATH") .map(|p| p.encode_wide().chain(Some(0)).collect::<Vec<_>>()) }); // Create and set up stdio let child_stdio_buffer = uv_stdio_create(options)?; // Search for the executable let Some(application_path) = search_path( application.as_slice_no_nul(), cwd.as_slice_no_nul(), path.as_deref(), options.flags, ) else { return Err(std::io::Error::new( std::io::ErrorKind::NotFound, "File not found", )); }; // Create command line arguments let args: Vec<&OsStr> = options.args.iter().map(|s| s.as_ref()).collect(); let verbatim_arguments = (options.flags & uv_process_flags::WindowsVerbatimArguments) != 0; let has_bat_extension = |program: &[u16]| { // lifted from https://github.com/rust-lang/rust/blob/bc1d7273dfbc6f8a11c0086fa35f6748a13e8d3c/library/std/src/sys/process/windows.rs#L284 // Copyright The Rust Project Contributors - MIT matches!( // Case insensitive "ends_with" of UTF-16 encoded ".bat" or ".cmd" program.len().checked_sub(4).and_then(|i| program.get(i..)), Some( [46, 98 | 66, 97 | 65, 116 | 84] | [46, 99 | 67, 109 | 77, 100 | 68] ) ) }; let is_batch_file = has_bat_extension(application_path.as_slice_no_nul()); let (application_path, arguments) = if is_batch_file { ( command_prompt()?, WCString::from_vec(make_bat_command_line( application_path.as_slice_no_nul(), &args, !verbatim_arguments, )?), ) } else { ( application_path, make_program_args(&args, verbatim_arguments)?, ) }; // Set up process creation startup.cb = std::mem::size_of::<STARTUPINFOW>() as u32; startup.lpReserved = ptr::null_mut(); startup.lpDesktop = ptr::null_mut(); startup.lpTitle = ptr::null_mut(); startup.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; startup.cbReserved2 = child_stdio_buffer.size() as u16; startup.hStdInput = unsafe { child_stdio_buffer.get_handle(0) }; startup.hStdOutput = unsafe { child_stdio_buffer.get_handle(1) }; startup.hStdError = unsafe { child_stdio_buffer.get_handle(2) }; startup.lpReserved2 = child_stdio_buffer.into_raw(); // Set up process flags let mut process_flags = CREATE_UNICODE_ENVIRONMENT; // Handle console window visibility if (options.flags & uv_process_flags::WindowsHideConsole) != 0 || (options.flags & uv_process_flags::WindowsHide) != 0 { // Avoid creating console window if stdio is not inherited let mut can_hide = true; for i in 0..options.stdio.len() { if matches!(options.stdio[i], StdioContainer::InheritFd(_)) { can_hide = false; break; } } if can_hide { process_flags |= CREATE_NO_WINDOW; } } // Set window show state if (options.flags & uv_process_flags::WindowsHideGui) != 0 || (options.flags & uv_process_flags::WindowsHide) != 0 { startup.wShowWindow = SW_HIDE as u16; } else { startup.wShowWindow = SW_SHOWDEFAULT as u16; } // Handle detached processes if (options.flags & uv_process_flags::Detached) != 0 { process_flags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP; process_flags |= CREATE_SUSPENDED; } // Create the process let app_path_ptr = application_path.as_ptr(); let args_ptr = arguments.as_ptr(); let (env_ptr, _data) = crate::env::make_envp(maybe_env)?; let cwd_ptr = cwd.as_ptr(); let create_result = unsafe { CreateProcessW( app_path_ptr, // Application path args_ptr as *mut u16, // Command line ptr::null(), // Process attributes ptr::null(), // Thread attributes TRUE, // Inherit handles process_flags, // Creation flags env_ptr as *mut _, // Environment cwd_ptr, // Current directory &startup, // Startup info &mut info, // Process information ) }; if create_result == 0 { // CreateProcessW failed return Err(std::io::Error::last_os_error()); } // If the process isn't spawned as detached, assign to the global job object if (options.flags & uv_process_flags::Detached) == 0 { uv_init_global_job_handle(); let job_handle = UV_GLOBAL_JOB_HANDLE.get().unwrap().0; unsafe { if windows_sys::Win32::System::JobObjects::AssignProcessToJobObject( job_handle, info.hProcess, ) == 0 { // AssignProcessToJobObject might fail if this process is under job control // and the job doesn't have the JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK flag set, // on a Windows version that doesn't support nested jobs. let err = GetLastError(); if err != ERROR_ACCESS_DENIED { uv_fatal_error_with_no("AssignProcessToJobObject", Some(err)); } } } } // Resume thread if it was suspended if (process_flags & CREATE_SUSPENDED) != 0 { unsafe { if ResumeThread(info.hThread) == u32::MAX { TerminateProcess(info.hProcess, 1); return Err(std::io::Error::last_os_error()); } } } let child = ChildProcess { pid: info.dwProcessId as i32, handle: unsafe { OwnedHandle::from_raw_handle(info.hProcess) }, waiting: None, }; // Close the thread handle as we don't need it unsafe { windows_sys::Win32::Foundation::CloseHandle(info.hThread) }; if !startup.lpReserved2.is_null() { unsafe { free_stdio_buffer(startup.lpReserved2) }; } Ok(child) } macro_rules! impl_bitops { ($t: ty : $other: ty) => { impl_bitops!(@help; $t, $other; out = $other); impl_bitops!(@help; $other, $t; out = $other); impl_bitops!(@help; $t, $t; out = $other); impl BitOrAssign<$t> for $other { fn bitor_assign(&mut self, rhs: $t) { *self |= rhs as $other; } } impl BitAndAssign<$t> for $other { fn bitand_assign(&mut self, rhs: $t) { *self &= rhs as $other; } } }; (@help; $lhs: ty , $rhs: ty; out = $out: ty) => { impl BitOr<$rhs> for $lhs { type Output = $out; fn bitor(self, rhs: $rhs) -> Self::Output { self as $out | rhs as $out } } impl BitAnd<$rhs> for $lhs { type Output = $out; fn bitand(self, rhs: $rhs) -> Self::Output { self as $out & rhs as $out } } }; } impl_bitops!( uv_process_flags : u32 ); #[repr(u32)] pub enum uv_process_flags { /// Set the child process' user id. SetUid = 1 << 0, /// Set the child process' group id. SetGid = 1 << 1, /// Do not wrap any arguments in quotes, or perform any other escaping, when /// converting the argument list into a command line string. This option is /// only meaningful on Windows systems. On Unix it is silently ignored. WindowsVerbatimArguments = 1 << 2, /// Spawn the child process in a detached state - this will make it a process /// group leader, and will effectively enable the child to keep running after /// the parent exits. Note that the child process will still keep the /// parent's event loop alive unless the parent process calls uv_unref() on /// the child's process handle. Detached = 1 << 3, /// Hide the subprocess window that would normally be created. This option is /// only meaningful on Windows systems. On Unix it is silently ignored. WindowsHide = 1 << 4, /// Hide the subprocess console window that would normally be created. This /// option is only meaningful on Windows systems. On Unix it is silently /// ignored. WindowsHideConsole = 1 << 5, /// Hide the subprocess GUI window that would normally be created. This /// option is only meaningful on Windows systems. On Unix it is silently /// ignored. WindowsHideGui = 1 << 6, /// On Windows, if the path to the program to execute, specified in /// uv_process_options_t's file field, has a directory component, /// search for the exact file name before trying variants with /// extensions like '.exe' or '.cmd'. WindowsFilePathExactName = 1 << 7, } fn search_path_join_test( dir: &[u16], name: &[u16], ext: &[u16], cwd: &[u16], ) -> Option<WCString> { use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_DIRECTORY; use windows_sys::Win32::Storage::FileSystem::GetFileAttributesW; use windows_sys::Win32::Storage::FileSystem::INVALID_FILE_ATTRIBUTES; let dir_len = dir.len(); let name_len = name.len(); let ext_len = ext.len(); let mut cwd_len = cwd.len(); // Adjust cwd_len based on the path type if dir_len > 2 && ((dir[0] == wchar!('\\') || dir[0] == wchar!('/')) && (dir[1] == wchar!('\\') || dir[1] == wchar!('/'))) { // UNC path, ignore cwd cwd_len = 0; } else if dir_len >= 1 && (dir[0] == wchar!('/') || dir[0] == wchar!('\\')) { // Full path without drive letter, use cwd's drive letter only cwd_len = 2; } else if dir_len >= 2 && dir[1] == wchar!(':') && (dir_len < 3 || (dir[2] != wchar!('/') && dir[2] != wchar!('\\'))) { // Relative path with drive letter if cwd_len < 2 || dir[..2] != cwd[..2] { cwd_len = 0; } else { // Skip the drive letter part in dir let new_dir = &dir[2..]; return search_path_join_test(new_dir, name, ext, cwd); } } else if dir_len > 2 && dir[1] == wchar!(':') { // Absolute path with drive letter, don't use cwd cwd_len = 0; } // Allocate buffer for output let mut result = Vec::with_capacity(128); // Copy cwd if cwd_len > 0 { result.extend_from_slice(&cwd[..cwd_len]); // Add path separator if needed if let Some(last) = result.last() && !(*last == wchar!('\\') || *last == wchar!('/') || *last == wchar!(':')) { result.push(wchar!('\\')); } } // Copy dir if dir_len > 0 { result.extend_from_slice(&dir[..dir_len]); // Add separator if needed if let Some(last) = result.last() && !(*last == wchar!('\\') || *last == wchar!('/') || *last == wchar!(':')) { result.push(wchar!('\\')); } } // Copy filename result.extend_from_slice(&name[..name_len]); if ext_len > 0 { // Add dot if needed if name_len > 0 && result.last() != Some(&wchar!('.')) { result.push(wchar!('.')); } // Copy extension result.extend_from_slice(&ext[..ext_len]); } // Create WCString and check if file exists let path = WCString::from_vec(result); let attrs = unsafe { GetFileAttributesW(path.as_ptr()) }; if attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY) == 0 { Some(path) } else { None } } fn search_path_walk_ext( dir: &[u16], name: &[u16], cwd: &[u16], name_has_ext: bool, ) -> Option<WCString> { // If the name itself has a nonempty extension, try this extension first if name_has_ext && let Some(result) = search_path_join_test(dir, name, &[], cwd) { return Some(result); } // Try .com extension if let Some(result) = search_path_join_test( dir, name, &[wchar!('c'), wchar!('o'), wchar!('m')], cwd, ) { return Some(result); } // Try .exe extension if let Some(result) = search_path_join_test( dir, name, &[wchar!('e'), wchar!('x'), wchar!('e')], cwd, ) { return Some(result); } None } fn search_path( file: &[u16], cwd: &[u16], path: Option<&[u16]>, _flags: u32, ) -> Option<WCString> { // If the caller supplies an empty filename, // we're not gonna return c:\windows\.exe -- GFY! if file.is_empty() || (file.len() == 1 && file[0] == wchar!('.')) { return None; } let file_len = file.len(); // Find the start of the filename so we can split the directory from the name let mut file_name_start = file_len; while file_name_start > 0 { let prev = file[file_name_start - 1]; if prev == wchar!('\\') || prev == wchar!('/') || prev == wchar!(':') { break; } file_name_start -= 1; } let file_has_dir = file_name_start > 0; // Check if the filename includes an extension let name_slice = &file[file_name_start..]; let dot_pos = name_slice.iter().position(|&c| c == wchar!('.')); let name_has_ext = dot_pos.is_some_and(|pos| pos + 1 < name_slice.len()); if file_has_dir { // The file has a path inside, don't use path return search_path_walk_ext( &file[..file_name_start], &file[file_name_start..], cwd, name_has_ext, ); } else { // Check if we need to search in the current directory first let empty = [0u16; 1]; let need_cwd = unsafe { NeedCurrentDirectoryForExePathW(empty.as_ptr()) != 0 }; if need_cwd { // The file is really only a name; look in cwd first, then scan path if let Some(result) = search_path_walk_ext(&[], file, cwd, name_has_ext) { return Some(result); } } // If path is None, we've checked cwd and there's nothing else to do let path = path?; // Handle path segments let mut dir_end = 0; loop { // If we've reached the end of the path, stop searching if dir_end >= path.len() || path[dir_end] == 0 { break; } // Skip the separator that dir_end now points to if dir_end > 0 || path[0] == wchar!(';') { dir_end += 1; } // Next slice starts just after where the previous one ended let dir_start = dir_end; // Handle quoted paths let is_quoted = path[dir_start] == wchar!('"') || path[dir_start] == wchar!('\''); let quote_char = if is_quoted { path[dir_start] } else { 0 }; // Find the end of this directory component if is_quoted { // Find closing quote dir_end = dir_start + 1; while dir_end < path.len() && path[dir_end] != quote_char { dir_end += 1; } if dir_end == path.len() { // No closing quote, treat rest as the path dir_end = path.len(); } } // Find next separator (;) or end
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/subprocess_windows/src/tests.rs
runtime/subprocess_windows/src/tests.rs
// Copyright 2018-2025 the Deno authors. MIT license. // TODO
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/subprocess_windows/src/env.rs
runtime/subprocess_windows/src/env.rs
// Copyright 2018-2025 the Deno authors. MIT license. // Copyright (c) The Rust Project Contributors // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the // Software without restriction, including without // limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice // shall be included in all copies or substantial portions // of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // https://github.com/rust-lang/rust/blob/2eef47813f25df637026ce3288880e5c587abd92/library/std/src/sys/process/env.rs use std::cmp; use std::collections::BTreeMap; use std::env; use std::ffi::OsStr; use std::ffi::OsString; use std::ffi::c_void; use std::fmt; use std::io; use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Foundation::TRUE; use windows_sys::Win32::Globalization::CSTR_EQUAL; use windows_sys::Win32::Globalization::CSTR_GREATER_THAN; use windows_sys::Win32::Globalization::CSTR_LESS_THAN; use windows_sys::Win32::Globalization::CompareStringOrdinal; /// Stores a set of changes to an environment #[derive(Clone, Default)] pub struct CommandEnv { clear: bool, saw_path: bool, vars: BTreeMap<EnvKey, Option<OsString>>, } impl fmt::Debug for CommandEnv { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut debug_command_env = f.debug_struct("CommandEnv"); debug_command_env .field("clear", &self.clear) .field("vars", &self.vars); debug_command_env.finish() } } impl CommandEnv { // Capture the current environment with these changes applied pub fn capture(&self) -> BTreeMap<EnvKey, OsString> { let mut result = BTreeMap::<EnvKey, OsString>::new(); if !self.clear { for (k, v) in env::vars_os() { result.insert(k.into(), v); } } for (k, maybe_v) in &self.vars { if let Some(v) = maybe_v { result.insert(k.clone(), v.clone()); } else { result.remove(k); } } result } pub fn is_unchanged(&self) -> bool { !self.clear && self.vars.is_empty() } pub fn capture_if_changed(&self) -> Option<BTreeMap<EnvKey, OsString>> { if self.is_unchanged() { None } else { Some(self.capture()) } } // The following functions build up changes pub fn set(&mut self, key: &OsStr, value: &OsStr) { let key = EnvKey::from(key); self.maybe_saw_path(&key); self.vars.insert(key, Some(value.to_owned())); } pub fn clear(&mut self) { self.clear = true; self.vars.clear(); } pub fn have_changed_path(&self) -> bool { self.saw_path || self.clear } fn maybe_saw_path(&mut self, key: &EnvKey) { if !self.saw_path && key == "PATH" { self.saw_path = true; } } } // https://github.com/rust-lang/rust/blob/2eef47813f25df637026ce3288880e5c587abd92/library/std/src/sys/process/windows.rs #[derive(Clone, Debug, Eq)] #[doc(hidden)] pub struct EnvKey { os_string: OsString, // This stores a UTF-16 encoded string to workaround the mismatch between // Rust's OsString (WTF-8) and the Windows API string type (UTF-16). // Normally converting on every API call is acceptable but here // `c::CompareStringOrdinal` will be called for every use of `==`. utf16: Vec<u16>, } impl EnvKey { pub fn new<T: Into<OsString>>(key: T) -> Self { EnvKey::from(key.into()) } } // Comparing Windows environment variable keys[1] are behaviorally the // composition of two operations[2]: // // 1. Case-fold both strings. This is done using a language-independent // uppercase mapping that's unique to Windows (albeit based on data from an // older Unicode spec). It only operates on individual UTF-16 code units so // surrogates are left unchanged. This uppercase mapping can potentially change // between Windows versions. // // 2. Perform an ordinal comparison of the strings. A comparison using ordinal // is just a comparison based on the numerical value of each UTF-16 code unit[3]. // // Because the case-folding mapping is unique to Windows and not guaranteed to // be stable, we ask the OS to compare the strings for us. This is done by // calling `CompareStringOrdinal`[4] with `bIgnoreCase` set to `TRUE`. // // [1] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call // [2] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#stringtoupper-and-stringtolower // [3] https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparison?view=net-5.0#System_StringComparison_Ordinal // [4] https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-comparestringordinal impl Ord for EnvKey { fn cmp(&self, other: &Self) -> cmp::Ordering { unsafe { let result = CompareStringOrdinal( self.utf16.as_ptr(), self.utf16.len() as _, other.utf16.as_ptr(), other.utf16.len() as _, TRUE, ); match result { CSTR_LESS_THAN => cmp::Ordering::Less, CSTR_EQUAL => cmp::Ordering::Equal, CSTR_GREATER_THAN => cmp::Ordering::Greater, // `CompareStringOrdinal` should never fail so long as the parameters are correct. _ => panic!( "comparing environment keys failed: {}", std::io::Error::last_os_error() ), } } } } impl PartialOrd for EnvKey { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { Some(self.cmp(other)) } } impl PartialEq for EnvKey { fn eq(&self, other: &Self) -> bool { if self.utf16.len() != other.utf16.len() { false } else { self.cmp(other) == cmp::Ordering::Equal } } } impl PartialOrd<str> for EnvKey { fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> { Some(self.cmp(&EnvKey::new(other))) } } impl PartialEq<str> for EnvKey { fn eq(&self, other: &str) -> bool { if self.os_string.len() != other.len() { false } else { self.cmp(&EnvKey::new(other)) == cmp::Ordering::Equal } } } // Environment variable keys should preserve their original case even though // they are compared using a caseless string mapping. impl From<OsString> for EnvKey { fn from(k: OsString) -> Self { EnvKey { utf16: k.encode_wide().collect(), os_string: k, } } } impl From<&OsStr> for EnvKey { fn from(k: &OsStr) -> Self { Self::from(k.to_os_string()) } } pub fn ensure_no_nuls<T: AsRef<OsStr>>(s: T) -> io::Result<T> { if s.as_ref().encode_wide().any(|b| b == 0) { Err(io::Error::new( io::ErrorKind::InvalidInput, "nul byte found in provided data", )) } else { Ok(s) } } pub fn make_envp( maybe_env: Option<BTreeMap<EnvKey, OsString>>, ) -> io::Result<(*mut c_void, Vec<u16>)> { // On Windows we pass an "environment block" which is not a char**, but // rather a concatenation of null-terminated k=v\0 sequences, with a final // \0 to terminate. if let Some(env) = maybe_env { let mut blk = Vec::new(); // If there are no environment variables to set then signal this by // pushing a null. if env.is_empty() { blk.push(0); } for (k, v) in env { ensure_no_nuls(k.os_string)?; blk.extend(k.utf16); blk.push('=' as u16); blk.extend(ensure_no_nuls(v)?.encode_wide()); blk.push(0); } blk.push(0); Ok((blk.as_mut_ptr() as *mut c_void, blk)) } else { Ok((std::ptr::null_mut(), Vec::new())) } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/subprocess_windows/src/widestr.rs
runtime/subprocess_windows/src/widestr.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ffi::OsStr; use std::fmt; use std::ops::Index; use std::ops::Range; use std::ops::RangeFrom; use std::ops::RangeTo; use std::os::windows::ffi::OsStrExt; #[derive(Clone, PartialEq, Eq)] pub struct WCString { buf: Box<[u16]>, } impl fmt::Display for WCString { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", String::from_utf16_lossy(&self.buf[..self.buf.len() - 1]) ) } } impl fmt::Debug for WCString { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "\"{:?}\"", String::from_utf16_lossy(&self.buf[..self.buf.len() - 1]) ) } } impl WCString { pub fn new<T: AsRef<OsStr>>(s: T) -> Self { let buf = s.as_ref().encode_wide().chain(Some(0)).collect::<Vec<_>>(); Self { buf: buf.into_boxed_slice(), } } pub fn from_vec(vec: Vec<u16>) -> Self { if vec.last().unwrap_or(&1) == &0 { Self { buf: vec.into_boxed_slice(), } } else { let mut buf = vec; buf.push(0); Self { buf: buf.into_boxed_slice(), } } } pub fn as_ptr(&self) -> *const u16 { self.buf.as_ptr() } pub fn len_no_nul(&self) -> usize { self.buf.len() - 1 } #[allow(dead_code)] pub fn as_wcstr(&self) -> &WCStr { WCStr::from_wchars(&self.buf) } pub fn as_slice_no_nul(&self) -> &[u16] { &self.buf[..self.len_no_nul()] } } #[repr(transparent)] pub struct WCStr { buf: [u16], } impl WCStr { // pub fn new<B: ?Sized + AsRef<[u16]>(buf: &B) -> &Self { // } pub fn len(&self) -> usize { if self.has_nul() { self.buf.len() - 1 } else { self.buf.len() } } pub fn from_wchars(wchars: &[u16]) -> &WCStr { if wchars.last().unwrap_or(&1) == &0 { unsafe { &*(wchars as *const [u16] as *const WCStr) } } else { panic!("wchars must have a null terminator"); } } pub fn as_ptr(&self) -> *const u16 { self.buf.as_ptr() } pub fn has_nul(&self) -> bool { if self.buf.is_empty() { false } else { self.buf[self.buf.len() - 1] == 0 } } pub fn wchars_no_null(&self) -> &[u16] { if self.buf.is_empty() { return &[]; } if self.has_nul() { &self.buf[0..self.buf.len() - 1] } else { &self.buf } } } impl Index<usize> for WCStr { type Output = u16; fn index(&self, index: usize) -> &Self::Output { &self.buf[index] } } impl Index<Range<usize>> for WCStr { type Output = [u16]; fn index(&self, index: Range<usize>) -> &Self::Output { &self.buf[index] } } impl Index<RangeTo<usize>> for WCStr { type Output = [u16]; fn index(&self, index: RangeTo<usize>) -> &Self::Output { &self.buf[index] } } impl Index<RangeFrom<usize>> for WCStr { type Output = [u16]; fn index(&self, index: RangeFrom<usize>) -> &Self::Output { &self.buf[index] } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/subprocess_windows/src/anon_pipe.rs
runtime/subprocess_windows/src/anon_pipe.rs
// Copyright 2018-2025 the Deno authors. MIT license. // Copyright (c) The Rust Project Contributors // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the // Software without restriction, including without // limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice // shall be included in all copies or substantial portions // of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // Pulled from https://github.com/rust-lang/rust/blob/3e674b06b5c74adea662bd0b0b06450757994b16/library/std/src/sys/pal/windows/pipe.rs use std::cmp; use std::ffi::OsStr; use std::fs::OpenOptions; use std::io; use std::mem; use std::os::windows::prelude::*; use std::ptr; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::Relaxed; use windows_sys::Win32::Foundation::BOOL; use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED; use windows_sys::Win32::Foundation::ERROR_BROKEN_PIPE; use windows_sys::Win32::Foundation::ERROR_HANDLE_EOF; use windows_sys::Win32::Foundation::ERROR_IO_PENDING; use windows_sys::Win32::Foundation::FALSE; use windows_sys::Win32::Foundation::GENERIC_READ; use windows_sys::Win32::Foundation::GENERIC_WRITE; use windows_sys::Win32::Foundation::GetLastError; use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; use windows_sys::Win32::Foundation::TRUE; use windows_sys::Win32::Foundation::WAIT_OBJECT_0; use windows_sys::Win32::Security::SECURITY_ATTRIBUTES; use windows_sys::Win32::Storage::FileSystem::CreateFileW; use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_FIRST_PIPE_INSTANCE; use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OVERLAPPED; use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING; use windows_sys::Win32::Storage::FileSystem::PIPE_ACCESS_INBOUND; use windows_sys::Win32::Storage::FileSystem::PIPE_ACCESS_OUTBOUND; use windows_sys::Win32::Storage::FileSystem::ReadFile; use windows_sys::Win32::System::IO::CancelIo; use windows_sys::Win32::System::IO::GetOverlappedResult; use windows_sys::Win32::System::IO::OVERLAPPED; use windows_sys::Win32::System::Pipes::CreateNamedPipeW; use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE; use windows_sys::Win32::System::Pipes::PIPE_REJECT_REMOTE_CLIENTS; use windows_sys::Win32::System::Pipes::PIPE_TYPE_BYTE; use windows_sys::Win32::System::Pipes::PIPE_WAIT; use windows_sys::Win32::System::Threading::CreateEventW; use windows_sys::Win32::System::Threading::GetCurrentProcessId; use windows_sys::Win32::System::Threading::INFINITE; use windows_sys::Win32::System::Threading::WaitForMultipleObjects; pub type Handle = std::os::windows::io::OwnedHandle; //////////////////////////////////////////////////////////////////////////////// // Anonymous pipes //////////////////////////////////////////////////////////////////////////////// pub struct AnonPipe { inner: Handle, } impl AnonPipe { // fn try_clone(&self) -> io::Result<AnonPipe> { // let handle = handle_dup(&self.inner, 0, false, DUPLICATE_SAME_ACCESS)?; // Ok(AnonPipe { inner: handle }) // } } impl FromRawHandle for AnonPipe { unsafe fn from_raw_handle(handle: RawHandle) -> Self { AnonPipe { inner: unsafe { Handle::from_raw_handle(handle) }, } } } fn get_last_error() -> u32 { unsafe { GetLastError() } } pub struct Pipes { pub ours: AnonPipe, pub theirs: AnonPipe, } fn cvt(res: BOOL) -> io::Result<()> { if res == 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } /// Although this looks similar to `anon_pipe` in the Unix module it's actually /// subtly different. Here we'll return two pipes in the `Pipes` return value, /// but one is intended for "us" where as the other is intended for "someone /// else". /// /// Currently the only use case for this function is pipes for stdio on /// processes in the standard library, so "ours" is the one that'll stay in our /// process whereas "theirs" will be inherited to a child. /// /// The ours/theirs pipes are *not* specifically readable or writable. Each /// one only supports a read or a write, but which is which depends on the /// boolean flag given. If `ours_readable` is `true`, then `ours` is readable and /// `theirs` is writable. Conversely, if `ours_readable` is `false`, then `ours` /// is writable and `theirs` is readable. /// /// Also note that the `ours` pipe is always a handle opened up in overlapped /// mode. This means that technically speaking it should only ever be used /// with `OVERLAPPED` instances, but also works out ok if it's only ever used /// once at a time (which we do indeed guarantee). pub fn anon_pipe( ours_readable: bool, their_handle_inheritable: bool, ) -> io::Result<Pipes> { // A 64kb pipe capacity is the same as a typical Linux default. const PIPE_BUFFER_CAPACITY: u32 = 64 * 1024; // Note that we specifically do *not* use `CreatePipe` here because // unfortunately the anonymous pipes returned do not support overlapped // operations. Instead, we create a "hopefully unique" name and create a // named pipe which has overlapped operations enabled. // // Once we do this, we connect do it as usual via `CreateFileW`, and then // we return those reader/writer halves. Note that the `ours` pipe return // value is always the named pipe, whereas `theirs` is just the normal file. // This should hopefully shield us from child processes which assume their // stdout is a named pipe, which would indeed be odd! unsafe { let ours; let mut name; let mut tries = 0; loop { tries += 1; name = format!( r"\\.\pipe\__rust_anonymous_pipe1__.{}.{}", GetCurrentProcessId(), random_number(), ); let wide_name = OsStr::new(&name) .encode_wide() .chain(Some(0)) .collect::<Vec<_>>(); let mut flags = FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED; if ours_readable { flags |= PIPE_ACCESS_INBOUND; } else { flags |= PIPE_ACCESS_OUTBOUND; } let handle = CreateNamedPipeW( wide_name.as_ptr(), flags, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, 1, PIPE_BUFFER_CAPACITY, PIPE_BUFFER_CAPACITY, 0, ptr::null_mut(), ); // We pass the `FILE_FLAG_FIRST_PIPE_INSTANCE` flag above, and we're // also just doing a best effort at selecting a unique name. If // `ERROR_ACCESS_DENIED` is returned then it could mean that we // accidentally conflicted with an already existing pipe, so we try // again. // // Don't try again too much though as this could also perhaps be a // legit error. if handle == INVALID_HANDLE_VALUE { let error = get_last_error(); if tries < 10 && error == ERROR_ACCESS_DENIED { continue; } else { return Err(io::Error::from_raw_os_error(error as i32)); } } ours = Handle::from_raw_handle(handle); break; } // Connect to the named pipe we just created. This handle is going to be // returned in `theirs`, so if `ours` is readable we want this to be // writable, otherwise if `ours` is writable we want this to be // readable. // // Additionally we don't enable overlapped mode on this because most // client processes aren't enabled to work with that. #[allow(clippy::disallowed_methods)] let mut opts = OpenOptions::new(); opts.write(ours_readable); opts.read(!ours_readable); opts.share_mode(0); let access = if ours_readable { GENERIC_WRITE } else { GENERIC_READ }; let size = size_of::<SECURITY_ATTRIBUTES>(); let sa = SECURITY_ATTRIBUTES { nLength: size as u32, lpSecurityDescriptor: ptr::null_mut(), bInheritHandle: their_handle_inheritable as i32, }; let path_utf16 = OsStr::new(&name) .encode_wide() .chain(Some(0)) .collect::<Vec<_>>(); let handle2 = CreateFileW( path_utf16.as_ptr(), access, 0, &sa, OPEN_EXISTING, 0, ptr::null_mut(), ); let theirs = Handle::from_raw_handle(handle2); Ok(Pipes { ours: AnonPipe { inner: ours }, theirs: AnonPipe { inner: theirs }, }) } } fn random_number() -> usize { static N: std::sync::atomic::AtomicUsize = AtomicUsize::new(0); loop { if N.load(Relaxed) != 0 { return N.fetch_add(1, Relaxed); } N.store(fastrand::usize(..), Relaxed); } } impl AnonPipe { // pub fn handle(&self) -> &Handle { // &self.inner // } pub fn into_handle(self) -> Handle { self.inner } } pub fn read2( p1: AnonPipe, v1: &mut Vec<u8>, p2: AnonPipe, v2: &mut Vec<u8>, ) -> io::Result<()> { let p1 = p1.into_handle(); let p2 = p2.into_handle(); let mut p1 = AsyncPipe::new(p1, v1)?; let mut p2 = AsyncPipe::new(p2, v2)?; let objs = [p1.event.as_raw_handle(), p2.event.as_raw_handle()]; // In a loop we wait for either pipe's scheduled read operation to complete. // If the operation completes with 0 bytes, that means EOF was reached, in // which case we just finish out the other pipe entirely. // // Note that overlapped I/O is in general super unsafe because we have to // be careful to ensure that all pointers in play are valid for the entire // duration of the I/O operation (where tons of operations can also fail). // The destructor for `AsyncPipe` ends up taking care of most of this. loop { let res = unsafe { WaitForMultipleObjects(2, objs.as_ptr(), FALSE, INFINITE) }; if res == WAIT_OBJECT_0 { if !p1.result()? || !p1.schedule_read()? { return p2.finish(); } } else if res == WAIT_OBJECT_0 + 1 { if !p2.result()? || !p2.schedule_read()? { return p1.finish(); } } else { return Err(io::Error::last_os_error()); } } } struct AsyncPipe<'a> { pipe: Handle, event: Handle, overlapped: Box<OVERLAPPED>, // needs a stable address dst: &'a mut Vec<u8>, state: State, } #[derive(PartialEq, Debug)] enum State { NotReading, Reading, Read(usize), } impl<'a> AsyncPipe<'a> { fn new(pipe: Handle, dst: &'a mut Vec<u8>) -> io::Result<AsyncPipe<'a>> { // Create an event which we'll use to coordinate our overlapped // operations, this event will be used in WaitForMultipleObjects // and passed as part of the OVERLAPPED handle. // // Note that we do a somewhat clever thing here by flagging the // event as being manually reset and setting it initially to the // signaled state. This means that we'll naturally fall through the // WaitForMultipleObjects call above for pipes created initially, // and the only time an even will go back to "unset" will be once an // I/O operation is successfully scheduled (what we want). let event = new_event(true, true)?; let mut overlapped: Box<OVERLAPPED> = unsafe { Box::new(mem::zeroed()) }; overlapped.hEvent = event.as_raw_handle(); Ok(AsyncPipe { pipe, overlapped, event, dst, state: State::NotReading, }) } /// Executes an overlapped read operation. /// /// Must not currently be reading, and returns whether the pipe is currently /// at EOF or not. If the pipe is not at EOF then `result()` must be called /// to complete the read later on (may block), but if the pipe is at EOF /// then `result()` should not be called as it will just block forever. fn schedule_read(&mut self) -> io::Result<bool> { assert_eq!(self.state, State::NotReading); let amt = unsafe { if self.dst.capacity() == self.dst.len() { let additional = if self.dst.capacity() == 0 { 16 } else { 1 }; self.dst.reserve(additional); } read_overlapped( &self.pipe, self.dst.spare_capacity_mut(), &mut *self.overlapped, )? }; // If this read finished immediately then our overlapped event will // remain signaled (it was signaled coming in here) and we'll progress // down to the method below. // // Otherwise the I/O operation is scheduled and the system set our event // to not signaled, so we flag ourselves into the reading state and move // on. self.state = match amt { Some(0) => return Ok(false), Some(amt) => State::Read(amt), None => State::Reading, }; Ok(true) } /// Wait for the result of the overlapped operation previously executed. /// /// Takes a parameter `wait` which indicates if this pipe is currently being /// read whether the function should block waiting for the read to complete. /// /// Returns values: /// /// * `true` - finished any pending read and the pipe is not at EOF (keep /// going) /// * `false` - finished any pending read and pipe is at EOF (stop issuing /// reads) fn result(&mut self) -> io::Result<bool> { let amt = match self.state { State::NotReading => return Ok(true), State::Reading => { overlapped_result(&self.pipe, &mut *self.overlapped, true)? } State::Read(amt) => amt, }; self.state = State::NotReading; unsafe { let len = self.dst.len(); self.dst.set_len(len + amt); } Ok(amt != 0) } /// Finishes out reading this pipe entirely. /// /// Waits for any pending and schedule read, and then calls `read_to_end` /// if necessary to read all the remaining information. fn finish(&mut self) -> io::Result<()> { while self.result()? && self.schedule_read()? { // ... } Ok(()) } } impl Drop for AsyncPipe<'_> { fn drop(&mut self) { match self.state { State::Reading => {} _ => return, } // If we have a pending read operation, then we have to make sure that // it's *done* before we actually drop this type. The kernel requires // that the `OVERLAPPED` and buffer pointers are valid for the entire // I/O operation. // // To do that, we call `CancelIo` to cancel any pending operation, and // if that succeeds we wait for the overlapped result. // // If anything here fails, there's not really much we can do, so we leak // the buffer/OVERLAPPED pointers to ensure we're at least memory safe. if cancel_io(&self.pipe).is_err() || self.result().is_err() { let buf = mem::take(self.dst); let overlapped = Box::new(unsafe { mem::zeroed() }); let overlapped = mem::replace(&mut self.overlapped, overlapped); mem::forget((buf, overlapped)); } } } pub fn cancel_io(handle: &Handle) -> io::Result<()> { unsafe { cvt(CancelIo(handle.as_raw_handle())) } } pub fn overlapped_result( handle: &Handle, overlapped: *mut OVERLAPPED, wait: bool, ) -> io::Result<usize> { unsafe { let mut bytes = 0; let wait = if wait { TRUE } else { FALSE }; let res = cvt(GetOverlappedResult( handle.as_raw_handle(), overlapped, &mut bytes, wait, )); match res { Ok(_) => Ok(bytes as usize), Err(e) => { if e.raw_os_error() == Some(ERROR_HANDLE_EOF as i32) || e.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) { Ok(0) } else { Err(e) } } } } } pub unsafe fn read_overlapped( handle: &Handle, buf: &mut [mem::MaybeUninit<u8>], overlapped: *mut OVERLAPPED, ) -> io::Result<Option<usize>> { // SAFETY: We have exclusive access to the buffer and it's up to the caller to // ensure the OVERLAPPED pointer is valid for the lifetime of this function. let (res, amt) = unsafe { let len = cmp::min(buf.len(), u32::MAX as usize) as u32; let mut amt = 0; let res = cvt(ReadFile( handle.as_raw_handle(), buf.as_mut_ptr().cast::<u8>(), len, &mut amt, overlapped, )); (res, amt) }; match res { Ok(_) => Ok(Some(amt as usize)), Err(e) => { if e.raw_os_error() == Some(ERROR_IO_PENDING as i32) { Ok(None) } else if e.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) { Ok(Some(0)) } else { Err(e) } } } } pub fn new_event(manual: bool, init: bool) -> io::Result<Handle> { unsafe { let event = CreateEventW(ptr::null_mut(), manual as BOOL, init as BOOL, ptr::null()); if event.is_null() { Err(io::Error::last_os_error()) } else { Ok(Handle::from_raw_handle(event)) } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/subprocess_windows/src/process_stdio.rs
runtime/subprocess_windows/src/process_stdio.rs
// Copyright 2018-2025 the Deno authors. MIT license. /* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ // Ported partly from https://github.com/libuv/libuv/blob/b00c5d1a09c094020044e79e19f478a25b8e1431/src/win/process-stdio.c use std::ffi::c_int; use std::ptr::null_mut; use buffer::StdioBuffer; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::DUPLICATE_SAME_ACCESS; use windows_sys::Win32::Foundation::DuplicateHandle; use windows_sys::Win32::Foundation::GetLastError; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::Foundation::HANDLE_FLAG_INHERIT; use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; use windows_sys::Win32::Foundation::SetHandleInformation; use windows_sys::Win32::Security::SECURITY_ATTRIBUTES; use windows_sys::Win32::Storage::FileSystem::CreateFileW; use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ; use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE; use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES; use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ; use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE; use windows_sys::Win32::Storage::FileSystem::FILE_TYPE_CHAR; use windows_sys::Win32::Storage::FileSystem::FILE_TYPE_DISK; use windows_sys::Win32::Storage::FileSystem::FILE_TYPE_PIPE; use windows_sys::Win32::Storage::FileSystem::FILE_TYPE_REMOTE; use windows_sys::Win32::Storage::FileSystem::FILE_TYPE_UNKNOWN; use windows_sys::Win32::Storage::FileSystem::GetFileType; use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING; use windows_sys::Win32::System::Console::GetStdHandle; use windows_sys::Win32::System::Console::STD_ERROR_HANDLE; use windows_sys::Win32::System::Console::STD_HANDLE; use windows_sys::Win32::System::Console::STD_INPUT_HANDLE; use windows_sys::Win32::System::Console::STD_OUTPUT_HANDLE; use windows_sys::Win32::System::Threading::GetCurrentProcess; use windows_sys::Win32::System::Threading::GetStartupInfoW; use windows_sys::Win32::System::Threading::STARTUPINFOW; use crate::process::SpawnOptions; const FOPEN: u8 = 0x01; // const FEOFLAG: u8 = 0x02; // const FCRLF: u8 = 0x04; const FPIPE: u8 = 0x08; // const FNOINHERIT: u8 = 0x10; // const FAPPEND: u8 = 0x20; const FDEV: u8 = 0x40; // const FTEXT: u8 = 0x80; const fn child_stdio_size(count: usize) -> usize { size_of::<c_int>() + size_of::<u8>() * count + size_of::<usize>() * count } unsafe fn child_stdio_count(buffer: *mut u8) -> usize { unsafe { buffer.cast::<std::ffi::c_uint>().read_unaligned() as usize } // unsafe { *buffer.cast::<std::ffi::c_uint>() as usize } } unsafe fn child_stdio_handle(buffer: *mut u8, fd: i32) -> HANDLE { unsafe { buffer.add( size_of::<c_int>() + child_stdio_count(buffer) + size_of::<HANDLE>() * (fd as usize), ) } .cast() } unsafe fn child_stdio_crt_flags(buffer: *mut u8, fd: i32) -> *mut u8 { unsafe { buffer.add(size_of::<c_int>() + fd as usize) }.cast() } #[allow(dead_code)] unsafe fn uv_stdio_verify(buffer: *mut u8, size: u16) -> bool { if buffer.is_null() { return false; } if (size as usize) < child_stdio_size(0) { return false; } let count = unsafe { child_stdio_count(buffer) }; if count > 256 { return false; } if (size as usize) < child_stdio_size(count) { return false; } true } fn uv_create_nul_handle(access: u32) -> Result<HANDLE, std::io::Error> { let sa = SECURITY_ATTRIBUTES { nLength: size_of::<SECURITY_ATTRIBUTES>() as u32, lpSecurityDescriptor: null_mut(), bInheritHandle: 1, }; let handle = unsafe { CreateFileW( windows_sys::w!("NUL"), access, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, null_mut(), ) }; if handle == INVALID_HANDLE_VALUE { return Err(std::io::Error::last_os_error()); } Ok(handle) } #[allow(dead_code)] unsafe fn uv_stdio_noinherit(buffer: *mut u8) { let count = unsafe { child_stdio_count(buffer) }; for i in 0..count { let handle = unsafe { uv_stdio_handle(buffer, i as i32) }; if handle != INVALID_HANDLE_VALUE { unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0) }; } } } pub(crate) unsafe fn uv_stdio_handle(buffer: *mut u8, fd: i32) -> HANDLE { let mut handle = INVALID_HANDLE_VALUE; unsafe { copy_handle( child_stdio_handle(buffer, fd) .cast::<HANDLE>() .read_unaligned(), &mut handle, ) }; handle } pub unsafe fn uv_duplicate_handle( handle: HANDLE, ) -> Result<HANDLE, std::io::Error> { if handle == INVALID_HANDLE_VALUE || handle.is_null() || handle == ((-2i32) as usize as HANDLE) { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "Invalid handle", )); } let mut dup = INVALID_HANDLE_VALUE; let current_process = unsafe { GetCurrentProcess() }; if unsafe { DuplicateHandle( current_process, handle, current_process, &mut dup, 0, 1, DUPLICATE_SAME_ACCESS, ) } == 0 { return Err(std::io::Error::last_os_error()); } Ok(dup) } pub unsafe fn free_stdio_buffer(buffer: *mut u8) { let _ = unsafe { StdioBuffer::from_raw(buffer) }; } /*INLINE static HANDLE uv__get_osfhandle(int fd) { /* _get_osfhandle() raises an assert in debug builds if the FD is invalid. * But it also correctly checks the FD and returns INVALID_HANDLE_VALUE for * invalid FDs in release builds (or if you let the assert continue). So this * wrapper function disables asserts when calling _get_osfhandle. */ HANDLE handle; UV_BEGIN_DISABLE_CRT_ASSERT(); handle = (HANDLE) _get_osfhandle(fd); UV_END_DISABLE_CRT_ASSERT(); return handle; } */ unsafe fn uv_get_osfhandle(fd: i32) -> HANDLE { unsafe { libc::get_osfhandle(fd) as usize as HANDLE } } fn uv_duplicate_fd(fd: i32) -> Result<HANDLE, std::io::Error> { let handle = unsafe { uv_get_osfhandle(fd) }; unsafe { uv_duplicate_handle(handle) } } unsafe fn copy_handle(mut handle: HANDLE, dest: *mut HANDLE) { let handle = &raw mut handle; unsafe { std::ptr::copy_nonoverlapping( handle.cast::<u8>(), dest.cast::<u8>(), size_of::<HANDLE>(), ) } } #[derive(Debug, Clone, Copy)] pub enum StdioContainer { Ignore, InheritFd(i32), RawHandle(HANDLE), } #[inline(never)] pub(crate) fn uv_stdio_create( options: &SpawnOptions, ) -> Result<StdioBuffer, std::io::Error> { let mut count = options.stdio.len(); if count > 255 { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "Invalid stdio count", )); } else if count < 3 { count = 3; } let mut buffer = StdioBuffer::new(count); for i in 0..count { let fdopt = if i < options.stdio.len() { options.stdio[i] } else { StdioContainer::Ignore }; match fdopt { StdioContainer::RawHandle(handle) => { let dup = unsafe { uv_duplicate_handle(handle)? }; unsafe { buffer.set_handle(i as i32, dup) }; let flags = unsafe { handle_file_type_flags(dup)? }; unsafe { buffer.set_flags(i as i32, flags) }; unsafe { CloseHandle(handle) }; } StdioContainer::Ignore => unsafe { if i <= 2 { let access = if i == 0 { FILE_GENERIC_READ } else { FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES }; let nul = uv_create_nul_handle(access)?; buffer.set_handle(i as i32, nul); buffer.set_flags(i as i32, FOPEN | FDEV); } }, StdioContainer::InheritFd(fd) => { let handle = uv_duplicate_fd(fd); let handle = match handle { Ok(handle) => handle, Err(_) if fd <= 2 => { unsafe { buffer.set_flags(fd, 0) }; unsafe { buffer.set_handle(fd, INVALID_HANDLE_VALUE) }; continue; } Err(e) => return Err(e), }; let flags = unsafe { handle_file_type_flags(handle)? }; unsafe { buffer.set_handle(fd, handle) }; unsafe { buffer.set_flags(fd, flags) }; } } } Ok(buffer) } unsafe fn handle_file_type_flags(handle: HANDLE) -> Result<u8, std::io::Error> { Ok(match unsafe { GetFileType(handle) } { FILE_TYPE_DISK => FOPEN, FILE_TYPE_PIPE => FOPEN | FPIPE, FILE_TYPE_CHAR | FILE_TYPE_REMOTE => FOPEN | FDEV, FILE_TYPE_UNKNOWN => { if unsafe { GetLastError() } != 0 { unsafe { CloseHandle(handle) }; return Err(std::io::Error::other("Unknown file type")); } FOPEN | FDEV } other => panic!("Unknown file type: {}", other), }) } pub fn disable_stdio_inheritance() { let no_inherit = |h: STD_HANDLE| unsafe { let handle = GetStdHandle(h); if !handle.is_null() && handle != INVALID_HANDLE_VALUE { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0); } }; no_inherit(STD_INPUT_HANDLE); no_inherit(STD_OUTPUT_HANDLE); no_inherit(STD_ERROR_HANDLE); let mut si = unsafe { std::mem::zeroed::<STARTUPINFOW>() }; unsafe { GetStartupInfoW(&mut si) }; if let Some(mut stdio_buffer) = unsafe { StdioBuffer::from_raw_borrowed(si.lpReserved2, si.cbReserved2 as usize) } { stdio_buffer.no_inherit(); } } mod buffer { use std::ffi::c_uint; use std::mem::ManuallyDrop; use super::*; pub struct StdioBuffer { ptr: *mut u8, borrowed: bool, } impl Drop for StdioBuffer { fn drop(&mut self) { if self.borrowed { return; } let count = self.get_count(); for i in 0..count { let handle = unsafe { self.get_handle(i as i32) }; if handle != INVALID_HANDLE_VALUE { unsafe { CloseHandle(handle) }; } } unsafe { std::ptr::drop_in_place(self.ptr); std::alloc::dealloc( self.ptr as *mut _, std::alloc::Layout::array::<u8>(self.get_count()).unwrap(), ); } } } unsafe fn verify_buffer(ptr: *mut u8, size: usize) -> bool { if ptr.is_null() { return false; } if size < child_stdio_size(0) { return false; } let count = unsafe { child_stdio_count(ptr) }; if count > 256 { return false; } if size < child_stdio_size(count) { return false; } true } impl StdioBuffer { /// # Safety /// The buffer pointer must be valid and point to memory allocated by /// `std::alloc::alloc`. pub unsafe fn from_raw(ptr: *mut u8) -> Self { Self { ptr, borrowed: false, } } pub unsafe fn from_raw_borrowed(ptr: *mut u8, size: usize) -> Option<Self> { if unsafe { !verify_buffer(ptr, size) } { return None; } Some(Self { ptr, borrowed: true, }) } pub fn into_raw(self) -> *mut u8 { ManuallyDrop::new(self).ptr } fn create_raw(count: usize) -> Self { let layout = std::alloc::Layout::array::<u8>(child_stdio_size(count)).unwrap(); let ptr = unsafe { std::alloc::alloc(layout) }; StdioBuffer { ptr, borrowed: false, } } pub fn new(count: usize) -> Self { let buffer = Self::create_raw(count); // SAFETY: Since the buffer is uninitialized, use raw pointers // and do not read the data. unsafe { std::ptr::write(buffer.ptr.cast::<c_uint>(), count as c_uint); } for i in 0..count { // SAFETY: We initialized a big enough buffer for `count` // handles, so `i` is within bounds. unsafe { copy_handle( INVALID_HANDLE_VALUE, child_stdio_handle(buffer.ptr, i as i32).cast(), ); std::ptr::write(child_stdio_crt_flags(buffer.ptr, i as i32), 0); } } buffer } pub fn get_count(&self) -> usize { unsafe { child_stdio_count(self.ptr) } } /// # Safety /// /// This function does not check that the fd is within the bounds /// of the buffer. pub unsafe fn get_handle(&self, fd: i32) -> HANDLE { unsafe { uv_stdio_handle(self.ptr, fd) } } /// # Safety /// /// This function does not check that the fd is within the bounds /// of the buffer. pub unsafe fn set_flags(&mut self, fd: i32, flags: u8) { debug_assert!(fd < unsafe { child_stdio_count(self.ptr) } as i32,); unsafe { *child_stdio_crt_flags(self.ptr, fd) = flags; } } /// # Safety /// /// This function does not check that the fd is within the bounds /// of the buffer. pub unsafe fn set_handle(&mut self, fd: i32, handle: HANDLE) { unsafe { copy_handle(handle, child_stdio_handle(self.ptr, fd).cast()); } } pub fn size(&self) -> usize { child_stdio_size(self.get_count()) } pub fn no_inherit(&mut self) { let count = self.get_count(); for i in 0..count { let handle = unsafe { self.get_handle(i as i32) }; if handle != INVALID_HANDLE_VALUE { unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0) }; } } } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/permissions/lib.rs
runtime/permissions/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cmp::Ordering; use std::ffi::OsStr; use std::fmt; use std::fmt::Debug; use std::hash::Hash; use std::io::Write; use std::net::IpAddr; use std::net::Ipv6Addr; use std::net::SocketAddr; use std::ops::Deref; use std::path::Path; use std::path::PathBuf; use std::string::ToString; use std::sync::Arc; use std::sync::OnceLock; use capacity_builder::StringBuilder; use deno_path_util::normalize_path; use deno_path_util::url_to_file_path; use deno_terminal::colors; use deno_unsync::sync::AtomicFlag; use fqdn::FQDN; use ipnetwork::IpNetwork; use once_cell::sync::Lazy; use parking_lot::Mutex; use serde::Deserialize; use serde::Deserializer; use serde::Serialize; use serde::de; use url::Url; pub mod broker; mod ipc_pipe; pub mod prompter; mod runtime_descriptor_parser; pub mod which; use prompter::MAYBE_CURRENT_STACKTRACE; use prompter::PERMISSION_EMOJI; use prompter::permission_prompt; pub use runtime_descriptor_parser::RuntimePermissionDescriptorParser; use self::prompter::PromptResponse; use self::which::WhichSys; #[derive(Debug, Eq, PartialEq)] pub enum BrokerResponse { Allow, Deny { message: Option<String> }, } use self::broker::has_broker; use self::broker::maybe_check_with_broker; pub static AUDIT_FILE: OnceLock<Mutex<std::fs::File>> = OnceLock::new(); #[derive(Debug, thiserror::Error, deno_error::JsError)] #[error("{}", custom_message.as_ref().cloned().unwrap_or_else(|| format!("Requires {access}, {}", format_permission_error(.name))))] #[class("NotCapable")] pub struct PermissionDeniedError { pub access: String, pub name: &'static str, pub custom_message: Option<String>, pub state: PermissionState, } fn format_permission_error(name: &'static str) -> String { if is_standalone() { format!( "specify the required permissions during compilation using `deno compile --allow-{name}`" ) } else { format!("run again with the --allow-{name} flag") } } fn write_audit<T>(flag_name: &str, value: T) where T: Serialize, { let Some(file) = AUDIT_FILE.get() else { return; }; let mut file = file.lock(); let mut map = serde_json::Map::with_capacity(5); let _ = map.insert("v".into(), serde_json::Value::Number(1.into())); let _ = map.insert( "datetime".into(), serde_json::Value::String( chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), ), ); let _ = map.insert( "permission".into(), serde_json::to_value(flag_name).unwrap(), ); let _ = map.insert("value".into(), serde_json::to_value(value).unwrap()); let get_stack = MAYBE_CURRENT_STACKTRACE.lock(); if let Some(stack) = get_stack.as_ref().map(|s| s()) { let _ = map.insert("stack".into(), serde_json::to_value(&stack).unwrap()); } let _ = file.write_all( format!("{}\n", serde_json::to_string(&map).unwrap()).as_bytes(), ); } /// Fast exit from permission check routines if this permission /// is in the "fully-granted" state. macro_rules! audit_and_skip_check_if_is_permission_fully_granted { ($this:expr, $flag_name:expr, $value:expr) => { write_audit($flag_name, $value); if $this.is_allow_all() { return Ok(()); } }; } static DEBUG_LOG_ENABLED: Lazy<bool> = Lazy::new(|| log::log_enabled!(log::Level::Debug)); /// Quadri-state value for storing permission state #[derive( Eq, PartialEq, Default, Debug, Clone, Copy, Deserialize, PartialOrd, )] pub enum PermissionState { Granted = 0, GrantedPartial = 1, #[default] Prompt = 2, Denied = 3, DeniedPartial = 4, Ignored = 5, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OpenAccessKind { Read, ReadNoFollow, Write, WriteNoFollow, ReadWrite, ReadWriteNoFollow, } impl OpenAccessKind { pub fn is_no_follow(&self) -> bool { match self { OpenAccessKind::ReadNoFollow | OpenAccessKind::WriteNoFollow | OpenAccessKind::ReadWriteNoFollow => true, OpenAccessKind::Read | OpenAccessKind::Write | OpenAccessKind::ReadWrite => false, } } pub fn is_read(&self) -> bool { match self { OpenAccessKind::Read | OpenAccessKind::ReadNoFollow | OpenAccessKind::ReadWrite | OpenAccessKind::ReadWriteNoFollow => true, OpenAccessKind::Write | OpenAccessKind::WriteNoFollow => false, } } pub fn is_write(&self) -> bool { match self { OpenAccessKind::Read | OpenAccessKind::ReadNoFollow => false, OpenAccessKind::Write | OpenAccessKind::WriteNoFollow | OpenAccessKind::ReadWrite | OpenAccessKind::ReadWriteNoFollow => true, } } } #[derive(Debug)] pub struct PathWithRequested<'a> { pub path: Cow<'a, Path>, /// Custom requested display name when differs from resolved. pub requested: Option<Cow<'a, str>>, } impl<'a> PathWithRequested<'a> { pub fn only_path(path: Cow<'a, Path>) -> Self { Self { path, requested: None, } } pub fn display(&self) -> std::path::Display<'_> { match &self.requested { Some(requested) => Path::new(requested.as_ref()).display(), None => self.path.display(), } } pub fn as_owned(&self) -> PathBufWithRequested { PathBufWithRequested { path: self.path.to_path_buf(), requested: self.requested.as_ref().map(|r| r.to_string()), } } pub fn into_owned(self) -> PathBufWithRequested { PathBufWithRequested { path: self.path.into_owned(), requested: self.requested.map(|r| r.into_owned()), } } } impl Deref for PathWithRequested<'_> { type Target = Path; fn deref(&self) -> &Self::Target { &self.path } } impl AsRef<Path> for PathWithRequested<'_> { fn as_ref(&self) -> &Path { &self.path } } impl<'a> AsRef<PathWithRequested<'a>> for PathWithRequested<'a> { fn as_ref(&self) -> &PathWithRequested<'a> { self } } #[derive(Debug, Clone)] pub struct PathBufWithRequested { pub path: PathBuf, /// Custom requested display name when differs from resolved. pub requested: Option<String>, } impl PathBufWithRequested { pub fn only_path(path: PathBuf) -> Self { Self { path, requested: None, } } pub fn as_path_with_requested(&self) -> PathWithRequested<'_> { PathWithRequested { path: Cow::Borrowed(self.path.as_path()), requested: self.requested.as_deref().map(Cow::Borrowed), } } } impl Deref for PathBufWithRequested { type Target = Path; fn deref(&self) -> &Self::Target { &self.path } } #[derive(Debug)] pub struct CheckedPath<'a> { // these are private to prevent someone constructing this outside the crate path: PathWithRequested<'a>, canonicalized: bool, } impl<'a> CheckedPath<'a> { pub fn unsafe_new(path: Cow<'a, Path>) -> Self { Self { path: PathWithRequested { path, requested: None, }, canonicalized: false, } } pub fn canonicalized(&self) -> bool { self.canonicalized } pub fn display(&self) -> std::path::Display<'_> { self.path.display() } pub fn into_path_with_requested(self) -> PathWithRequested<'a> { self.path } pub fn as_owned(&self) -> CheckedPathBuf { CheckedPathBuf { path: self.path.as_owned(), canonicalized: self.canonicalized, } } pub fn into_owned(self) -> CheckedPathBuf { CheckedPathBuf { path: self.path.into_owned(), canonicalized: self.canonicalized, } } pub fn into_path(self) -> Cow<'a, Path> { self.path.path } pub fn into_owned_path(self) -> PathBuf { self.path.path.into_owned() } } impl<'a> AsRef<PathWithRequested<'a>> for CheckedPath<'a> { fn as_ref(&self) -> &PathWithRequested<'a> { &self.path } } impl Deref for CheckedPath<'_> { type Target = Path; fn deref(&self) -> &Self::Target { &self.path.path } } impl AsRef<Path> for CheckedPath<'_> { fn as_ref(&self) -> &Path { &self.path.path } } #[derive(Debug, Clone)] pub struct CheckedPathBuf { path: PathBufWithRequested, canonicalized: bool, } impl CheckedPathBuf { pub fn unsafe_new(path: PathBuf) -> Self { Self { path: PathBufWithRequested::only_path(path), canonicalized: false, } } pub fn as_checked_path(&self) -> CheckedPath<'_> { CheckedPath { path: self.path.as_path_with_requested(), canonicalized: self.canonicalized, } } pub fn into_path_buf(self) -> PathBuf { self.path.path } } impl Deref for CheckedPathBuf { type Target = Path; fn deref(&self) -> &Self::Target { &self.path.path } } impl AsRef<Path> for CheckedPathBuf { fn as_ref(&self) -> &Path { &self.path.path } } /// `AllowPartial` prescribes how to treat a permission which is partially /// denied due to a `--deny-*` flag affecting a subscope of the queried /// permission. /// /// `TreatAsGranted` is used in place of `TreatAsPartialGranted` when we don't /// want to wastefully check for partial denials when, say, checking read /// access for a file. #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[allow(clippy::enum_variant_names)] enum AllowPartial { TreatAsGranted, TreatAsDenied, TreatAsPartialGranted, } impl From<bool> for AllowPartial { fn from(value: bool) -> Self { if value { Self::TreatAsGranted } else { Self::TreatAsDenied } } } struct PromptOptions<'a> { name: &'static str, msg: &'a str, api_name: Option<&'a str>, info: Option<&'a str>, is_unary: bool, } impl PermissionState { #[inline(always)] fn log_perm_access( name: &'static str, info: impl FnOnce() -> Option<String>, ) { // Eliminates log overhead (when logging is disabled), // log_enabled!(Debug) check in a hot path still has overhead // TODO(AaronO): generalize or upstream this optimization if *DEBUG_LOG_ENABLED { log::debug!( "{}", colors::bold(&format!( "{}️ Granted {}", PERMISSION_EMOJI, Self::fmt_access(name, info().as_deref()) )) ); } } fn fmt_access(name: &'static str, info: Option<&str>) -> String { format!( "{} access{}", name, info.map(|info| format!(" to {info}")).unwrap_or_default(), ) } fn permission_denied_error( name: &'static str, info: Option<&str>, state: PermissionState, ) -> PermissionDeniedError { PermissionDeniedError { access: Self::fmt_access(name, info), name, custom_message: None, state, } } fn prompt( options: PromptOptions<'_>, ) -> (Result<(), PermissionDeniedError>, bool) { let PromptOptions { name, msg, api_name, info, is_unary, } = options; match permission_prompt(msg, name, api_name, is_unary) { PromptResponse::Allow => { Self::log_perm_access(name, || info.map(|i| i.to_string())); (Ok(()), false) } PromptResponse::AllowAll => { Self::log_perm_access(name, || info.map(|i| i.to_string())); (Ok(()), true) } PromptResponse::Deny => ( Err(Self::permission_denied_error( name, info, PermissionState::Denied, )), false, ), } } #[inline] fn check( self, name: &'static str, api_name: Option<&str>, stringify_value_fn: impl Fn() -> Option<String>, info: impl Fn() -> Option<String>, prompt: bool, ) -> (Result<(), PermissionDeniedError>, bool, bool) { if let Some(resp) = maybe_check_with_broker(name, &stringify_value_fn) { match resp { BrokerResponse::Allow => { Self::log_perm_access(name, info); return (Ok(()), false, false); } BrokerResponse::Deny { message } => { return ( Err(PermissionDeniedError { access: Self::fmt_access(name, info().as_deref()), name, custom_message: message, state: PermissionState::Denied, }), false, false, ); } } } match self { PermissionState::Granted => { Self::log_perm_access(name, info); (Ok(()), false, false) } PermissionState::Prompt if prompt => { let info = info(); let msg = StringBuilder::<String>::build(|builder| { builder.append(name); builder.append(" access"); if let Some(info) = &info { builder.append(" to "); builder.append(info); } }) .unwrap(); let (result, is_allow_all) = Self::prompt(PromptOptions { name, msg: &msg, api_name, info: info.as_deref(), is_unary: true, }); (result, true, is_allow_all) } state => { let err = Self::permission_denied_error(name, info().as_deref(), state); (Err(err), false, false) } } } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct UnitPermission { pub name: &'static str, pub description: &'static str, pub state: PermissionState, pub prompt: bool, } impl UnitPermission { pub fn query(&self) -> PermissionState { self.state } pub fn request(&mut self) -> PermissionState { if self.state == PermissionState::Prompt { if PromptResponse::Allow == permission_prompt( &format!("access to {}", self.description), self.name, Some("Deno.permissions.query()"), false, ) { self.state = PermissionState::Granted; } else { self.state = PermissionState::Denied; } } self.state } pub fn revoke(&mut self) -> PermissionState { if self.state == PermissionState::Granted { self.state = PermissionState::Prompt; } self.state } pub fn check( &mut self, stringify_value_fn: impl Fn() -> Option<String>, info: impl Fn() -> Option<String>, ) -> Result<(), PermissionDeniedError> { let (result, prompted, _is_allow_all) = self .state .check(self.name, None, stringify_value_fn, info, self.prompt); if prompted { if result.is_ok() { self.state = PermissionState::Granted; } else { self.state = PermissionState::Denied; } } result } } /// A normalized environment variable name. On Windows this will /// be uppercase and on other platforms it will stay as-is. #[derive(Clone, Eq, PartialEq, Hash, Debug, Ord, PartialOrd)] pub struct EnvVarName { inner: String, } impl EnvVarName { pub fn new(env: Cow<'_, str>) -> Self { EnvVarNameRef::new(env).into_owned() } pub fn as_env_var_name_ref(&self) -> EnvVarNameRef<'static> { EnvVarNameRef { inner: Cow::Owned(self.inner.clone()), } } } impl AsRef<str> for EnvVarName { fn as_ref(&self) -> &str { self.inner.as_ref() } } /// A normalized environment variable name. On Windows this will /// be uppercase and on other platforms it will stay as-is. #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct EnvVarNameRef<'a> { inner: Cow<'a, str>, } impl<'a> EnvVarNameRef<'a> { pub fn new(env: Cow<'a, str>) -> Self { Self { inner: if cfg!(windows) { Cow::Owned(env.to_uppercase()) } else { env }, } } pub fn into_owned(self) -> EnvVarName { EnvVarName { inner: self.inner.into_owned(), } } } impl AsRef<str> for EnvVarNameRef<'_> { fn as_ref(&self) -> &str { self.inner.as_ref() } } impl PartialEq<EnvVarNameRef<'_>> for EnvVarName { fn eq(&self, other: &EnvVarNameRef<'_>) -> bool { self.inner == other.inner } } pub trait AllowDescriptor: Debug + Eq + Clone + Hash { type QueryDesc<'a>: QueryDescriptor<AllowDesc = Self, DenyDesc = Self::DenyDesc>; type DenyDesc: DenyDescriptor; fn cmp_allow(&self, other: &Self) -> Ordering; fn cmp_deny(&self, other: &Self::DenyDesc) -> Ordering; } pub trait DenyDescriptor: Debug + Eq + Clone + Hash { fn cmp_deny(&self, other: &Self) -> Ordering; } pub trait QueryDescriptor: Debug { type AllowDesc: AllowDescriptor; type DenyDesc: DenyDescriptor; fn flag_name() -> &'static str; fn display_name(&self) -> Cow<'_, str>; fn from_allow(allow: &Self::AllowDesc) -> Self; fn as_allow(&self) -> Option<Self::AllowDesc>; fn as_deny(&self) -> Self::DenyDesc; /// Generic check function to check this descriptor against a `UnaryPermission`. fn check_in_permission( &self, perm: &mut UnaryPermission<Self::AllowDesc>, api_name: Option<&str>, ) -> Result<(), PermissionDeniedError>; fn matches_allow(&self, other: &Self::AllowDesc) -> bool; fn matches_deny(&self, other: &Self::DenyDesc) -> bool; /// Gets if this query descriptor should revoke the provided allow descriptor. fn revokes(&self, other: &Self::AllowDesc) -> bool; fn stronger_than_deny(&self, other: &Self::DenyDesc) -> bool; fn overlaps_deny(&self, other: &Self::DenyDesc) -> bool; } fn format_display_name(display_name: Cow<'_, str>) -> Cow<'_, str> { if display_name.starts_with('<') && display_name.ends_with('>') { display_name } else { Cow::Owned(format!("\"{}\"", display_name)) } } #[derive(Debug, Clone, Eq, PartialEq)] enum AllowOrDenyDescRef<'a, TAllowDesc: AllowDescriptor> { Allow(&'a TAllowDesc), Deny { desc: &'a TAllowDesc::DenyDesc, order: u8, }, } #[derive(Debug, Clone, Eq, PartialEq)] enum UnaryPermissionDesc<TAllowDesc: AllowDescriptor> { Granted(TAllowDesc), FlagDenied(TAllowDesc::DenyDesc), FlagIgnored(TAllowDesc::DenyDesc), PromptDenied(TAllowDesc::DenyDesc), } impl<TAllowDesc: AllowDescriptor> std::cmp::PartialOrd for UnaryPermissionDesc<TAllowDesc> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<TAllowDesc: AllowDescriptor> std::cmp::Ord for UnaryPermissionDesc<TAllowDesc> { fn cmp(&self, other: &Self) -> Ordering { match self.allow_or_deny_desc() { AllowOrDenyDescRef::Allow(self_desc) => { match other.allow_or_deny_desc() { AllowOrDenyDescRef::Allow(other_desc) => { self_desc.cmp_allow(other_desc) } AllowOrDenyDescRef::Deny { desc: other_desc, .. } => match self_desc.cmp_deny(other_desc) { Ordering::Equal => { self.kind_precedence().cmp(&other.kind_precedence()) } ord => ord, }, } } AllowOrDenyDescRef::Deny { desc: self_desc, order: self_order, } => { match other.allow_or_deny_desc() { AllowOrDenyDescRef::Allow(other_desc) => { match other_desc.cmp_deny(self_desc) { Ordering::Equal => { self.kind_precedence().cmp(&other.kind_precedence()) } // flip because we compared the other to self above Ordering::Less => Ordering::Greater, Ordering::Greater => Ordering::Less, } } AllowOrDenyDescRef::Deny { desc: other_desc, order: other_order, } => match self_desc.cmp_deny(other_desc) { Ordering::Equal => self_order.cmp(&other_order), ordering => ordering, }, } } } } } impl<TAllowDesc: AllowDescriptor> UnaryPermissionDesc<TAllowDesc> { fn allow_or_deny_desc(&self) -> AllowOrDenyDescRef<'_, TAllowDesc> { match self { UnaryPermissionDesc::Granted(desc) => AllowOrDenyDescRef::Allow(desc), UnaryPermissionDesc::FlagDenied(desc) => { AllowOrDenyDescRef::Deny { desc, order: 0 } } UnaryPermissionDesc::PromptDenied(desc) => { AllowOrDenyDescRef::Deny { desc, order: 1 } } UnaryPermissionDesc::FlagIgnored(desc) => { AllowOrDenyDescRef::Deny { desc, order: 2 } } } } fn kind_precedence(&self) -> u8 { match self { UnaryPermissionDesc::FlagDenied(_) => 0, UnaryPermissionDesc::PromptDenied(_) => 1, UnaryPermissionDesc::FlagIgnored(_) => 2, UnaryPermissionDesc::Granted(_) => 3, } } } #[derive(Debug, Clone, Eq, PartialEq)] struct UnaryPermissionDescriptors<TAllowDesc: AllowDescriptor> { inner: Vec<UnaryPermissionDesc<TAllowDesc>>, has_flag_denied: bool, has_prompt_denied: bool, has_flag_ignored: bool, } impl<TAllowDesc: AllowDescriptor> Default for UnaryPermissionDescriptors<TAllowDesc> { fn default() -> Self { Self { inner: Default::default(), has_flag_denied: false, has_prompt_denied: false, has_flag_ignored: false, } } } impl<TAllowDesc: AllowDescriptor> UnaryPermissionDescriptors<TAllowDesc> { pub fn with_capacity(capacity: usize) -> Self { Self { inner: Vec::with_capacity(capacity), ..Default::default() } } pub fn iter(&self) -> impl Iterator<Item = &UnaryPermissionDesc<TAllowDesc>> { self.inner.iter() } pub fn has_any_denied_or_ignored(&self) -> bool { self.has_flag_denied || self.has_prompt_denied || self.has_flag_ignored } pub fn has_prompt_denied(&self) -> bool { self.has_prompt_denied } pub fn insert(&mut self, item: UnaryPermissionDesc<TAllowDesc>) { match &item { UnaryPermissionDesc::Granted(_) => {} UnaryPermissionDesc::FlagDenied(_) => { self.has_flag_denied = true; } UnaryPermissionDesc::FlagIgnored(_) => { self.has_flag_ignored = true; } UnaryPermissionDesc::PromptDenied(_) => { self.has_prompt_denied = true; } } if let Err(insert_index) = self.inner.binary_search(&item) { self.inner.insert(insert_index, item); } } pub fn revoke_granted(&mut self, desc: &TAllowDesc::QueryDesc<'_>) { self.inner.retain(|v| match v { UnaryPermissionDesc::Granted(v) => !desc.revokes(v), UnaryPermissionDesc::FlagDenied(_) | UnaryPermissionDesc::FlagIgnored(_) | UnaryPermissionDesc::PromptDenied(_) => true, }) } pub fn revoke_all_granted(&mut self) { self.inner.retain(|v| match v { UnaryPermissionDesc::Granted(_) => false, UnaryPermissionDesc::FlagDenied(_) | UnaryPermissionDesc::FlagIgnored(_) | UnaryPermissionDesc::PromptDenied(_) => true, }) } } #[derive(Debug, Eq, PartialEq)] pub struct UnaryPermission<TAllowDesc: AllowDescriptor> { granted_global: bool, flag_denied_global: bool, flag_ignored_global: bool, prompt_denied_global: bool, descriptors: UnaryPermissionDescriptors<TAllowDesc>, prompt: bool, } impl<TAllowDesc: AllowDescriptor> Default for UnaryPermission<TAllowDesc> { fn default() -> Self { UnaryPermission { granted_global: Default::default(), flag_denied_global: Default::default(), flag_ignored_global: Default::default(), prompt_denied_global: Default::default(), descriptors: Default::default(), prompt: Default::default(), } } } impl<TAllowDesc: AllowDescriptor> Clone for UnaryPermission<TAllowDesc> { fn clone(&self) -> Self { Self { granted_global: self.granted_global, flag_denied_global: self.flag_denied_global, flag_ignored_global: self.flag_ignored_global, prompt_denied_global: self.prompt_denied_global, descriptors: self.descriptors.clone(), prompt: self.prompt, } } } impl< TAllowDesc: AllowDescriptor<DenyDesc = TDenyDesc>, TDenyDesc: DenyDescriptor, > UnaryPermission<TAllowDesc> { pub fn allow_all() -> Self { Self { granted_global: true, ..Default::default() } } pub fn is_allow_all(&self) -> bool { self.granted_global && !self.flag_denied_global && !self.prompt_denied_global && !self.flag_ignored_global && !self.descriptors.has_any_denied_or_ignored() && !has_broker() } pub fn check_all_api( &mut self, api_name: Option<&str>, ) -> Result<(), PermissionDeniedError> { audit_and_skip_check_if_is_permission_fully_granted!( self, TAllowDesc::QueryDesc::flag_name(), () ); self.check_desc(None, false, api_name) } fn check_desc( &mut self, desc: Option<&TAllowDesc::QueryDesc<'_>>, assert_non_partial: bool, api_name: Option<&str>, ) -> Result<(), PermissionDeniedError> { let (result, prompted, is_allow_all) = self .query_desc(desc, AllowPartial::from(!assert_non_partial)) .check( TAllowDesc::QueryDesc::flag_name(), api_name, || desc.map(|d| d.display_name().to_string()), || desc.map(|d| format_display_name(d.display_name()).into_owned()), self.prompt, ); if prompted { if result.is_ok() { if is_allow_all { self.insert_granted(None); } else { self.insert_granted(desc); } } else { self.insert_prompt_denied(desc.map(|d| d.as_deny())); } } result } fn query_desc( &self, desc: Option<&TAllowDesc::QueryDesc<'_>>, allow_partial: AllowPartial, ) -> PermissionState { if let Some(state) = self.query_allowed_desc_for_exact_match(desc, allow_partial) { state } else if self.flag_ignored_global { PermissionState::Ignored } else if matches!(allow_partial, AllowPartial::TreatAsDenied) && self.is_partial_flag_denied(desc) { PermissionState::DeniedPartial } else if self.flag_denied_global || desc.is_none() && (self.prompt_denied_global || self.descriptors.has_prompt_denied()) { PermissionState::Denied } else if self.granted_global { self.query_allowed_desc(desc, allow_partial) } else { PermissionState::Prompt } } fn query_allowed_desc_for_exact_match( &self, desc: Option<&TAllowDesc::QueryDesc<'_>>, allow_partial: AllowPartial, ) -> Option<PermissionState> { let desc = desc?; for item in self.descriptors.iter() { match item { UnaryPermissionDesc::Granted(v) => { if desc.matches_allow(v) { return Some(self.query_allowed_desc(Some(desc), allow_partial)); } } UnaryPermissionDesc::FlagDenied(v) => { if desc.matches_deny(v) { return Some(PermissionState::Denied); } } UnaryPermissionDesc::FlagIgnored(v) => { if desc.matches_deny(v) { return Some(PermissionState::Ignored); } } UnaryPermissionDesc::PromptDenied(v) => { if desc.stronger_than_deny(v) { return Some(PermissionState::Denied); } } } } None } fn query_allowed_desc( &self, desc: Option<&TAllowDesc::QueryDesc<'_>>, allow_partial: AllowPartial, ) -> PermissionState { match allow_partial { AllowPartial::TreatAsGranted => PermissionState::Granted, AllowPartial::TreatAsDenied => { if self.is_partial_flag_denied(desc) { PermissionState::DeniedPartial } else { PermissionState::Granted } } AllowPartial::TreatAsPartialGranted => { if self.is_partial_flag_denied(desc) { PermissionState::GrantedPartial } else { PermissionState::Granted } } } } fn request_desc( &mut self, desc: Option<&TAllowDesc::QueryDesc<'_>>, ) -> PermissionState { let state = self.query_desc(desc, AllowPartial::TreatAsPartialGranted); if state == PermissionState::Granted { self.insert_granted(desc); return state; } if state != PermissionState::Prompt { return state; } if !self.prompt { return PermissionState::Denied; } let maybe_formatted_display_name = desc.map(|d| format_display_name(d.display_name())); let message = StringBuilder::<String>::build(|builder| { builder.append(TAllowDesc::QueryDesc::flag_name()); builder.append(" access"); if let Some(display_name) = &maybe_formatted_display_name { builder.append(" to "); builder.append(display_name) } }) .unwrap(); match permission_prompt( &message, TAllowDesc::QueryDesc::flag_name(), Some("Deno.permissions.request()"), true, ) { PromptResponse::Allow => { self.insert_granted(desc); PermissionState::Granted } PromptResponse::Deny => { self.insert_prompt_denied(desc.map(|d| d.as_deny())); PermissionState::Denied } PromptResponse::AllowAll => { self.insert_granted(None); PermissionState::Granted } } } fn revoke_desc( &mut self, desc: Option<&TAllowDesc::QueryDesc<'_>>, ) -> PermissionState { match desc { Some(desc) => { self.descriptors.revoke_granted(desc); } None => { self.granted_global = false; // Revoke global is a special case where the entire granted list is // cleared. It's inconsistent with the granular case where only // descriptors stronger than the revoked one are purged. self.descriptors.revoke_all_granted(); } } self.query_desc(desc, AllowPartial::TreatAsPartialGranted) } fn is_partial_flag_denied( &self, query: Option<&TAllowDesc::QueryDesc<'_>>, ) -> bool { match query { None => { self.descriptors.has_flag_denied || self.descriptors.has_flag_ignored } Some(query) => self.descriptors.iter().any(|desc| match desc { UnaryPermissionDesc::FlagIgnored(v) | UnaryPermissionDesc::FlagDenied(v) => query.overlaps_deny(v), UnaryPermissionDesc::Granted(_) | UnaryPermissionDesc::PromptDenied(_) => false, }), } } fn insert_granted( &mut self, query: Option<&TAllowDesc::QueryDesc<'_>>, ) -> bool { let desc = match query.map(|q| q.as_allow()) { Some(Some(allow_desc)) => Some(allow_desc), Some(None) => { // the user was prompted for this descriptor in order to not // expose anything about the system to the program, but the // descriptor wasn't valid so no permission was raised return false; } None => None, }; Self::list_insert( desc.map(UnaryPermissionDesc::Granted), &mut self.granted_global, &mut self.descriptors, ); true } fn insert_prompt_denied(&mut self, desc: Option<TDenyDesc>) { Self::list_insert( desc.map(UnaryPermissionDesc::PromptDenied), &mut self.prompt_denied_global, &mut self.descriptors, ); } fn list_insert( desc: Option<UnaryPermissionDesc<TAllowDesc>>, list_global: &mut bool, descriptors: &mut UnaryPermissionDescriptors<TAllowDesc>, ) { match desc { Some(desc) => { descriptors.insert(desc); } None => *list_global = true, } } fn create_child_permissions<E>( &mut self, flag: ChildUnaryPermissionArg, parse: impl Fn(&str) -> Result<Option<TAllowDesc>, E>, ) -> Result<UnaryPermission<TAllowDesc>, ChildPermissionError> where ChildPermissionError: From<E>, { let mut perms = Self::default(); match flag { ChildUnaryPermissionArg::Inherit => { perms.clone_from(self); } ChildUnaryPermissionArg::Granted => { if self.check_all_api(None).is_err() { return Err(ChildPermissionError::Escalation); } perms.granted_global = true; } ChildUnaryPermissionArg::NotGranted => {} ChildUnaryPermissionArg::GrantedList(granted_list) => { for result in granted_list.iter().filter_map(|i| parse(i).transpose()) { let desc = result?; if TAllowDesc::QueryDesc::from_allow(&desc) .check_in_permission(self, None) .is_err() { return Err(ChildPermissionError::Escalation); } perms.descriptors.insert(UnaryPermissionDesc::Granted(desc)); } } } perms.flag_denied_global = self.flag_denied_global; perms.prompt_denied_global = self.prompt_denied_global; perms.prompt = self.prompt; perms.flag_ignored_global = self.flag_ignored_global; for item in self.descriptors.iter() { match item { UnaryPermissionDesc::Granted(_) => { // ignore } UnaryPermissionDesc::FlagDenied(_) | UnaryPermissionDesc::FlagIgnored(_) | UnaryPermissionDesc::PromptDenied(_) => { perms.descriptors.insert(item.clone()); } } } Ok(perms) } } #[derive(Clone, Debug)] pub struct PathQueryDescriptor<'a> { path: Cow<'a, Path>,
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/permissions/ipc_pipe.rs
runtime/permissions/ipc_pipe.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ffi::OsStr; use std::io::Read; use std::io::Write; use std::io::{self}; pub struct IpcPipe(Inner); #[cfg(unix)] type Inner = std::os::unix::net::UnixStream; #[cfg(not(unix))] type Inner = std::fs::File; impl IpcPipe { /// Connect to a local IPC endpoint. /// - Unix: `addr` like `/tmp/deno.sock` /// - Windows: `addr` like `\\.\pipe\deno-permission-broker` pub fn connect(addr: impl AsRef<OsStr>) -> io::Result<Self> { Self::connect_impl(addr.as_ref()) } } #[cfg(unix)] impl IpcPipe { fn connect_impl(addr: &OsStr) -> io::Result<Self> { use std::os::unix::net::UnixStream; use std::path::Path; let s = UnixStream::connect(Path::new(addr))?; s.set_nonblocking(false)?; Ok(Self(s)) } } #[cfg(windows)] impl IpcPipe { fn connect_impl(addr: &OsStr) -> io::Result<Self> { use std::os::windows::ffi::OsStrExt; use std::os::windows::io::FromRawHandle; use windows_sys::Win32::Foundation::ERROR_PIPE_BUSY; use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; use windows_sys::Win32::Storage::FileSystem::CreateFileW; use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL; use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ; use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE; use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING; use windows_sys::Win32::System::Pipes::NMPWAIT_WAIT_FOREVER; use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE; use windows_sys::Win32::System::Pipes::SetNamedPipeHandleState; use windows_sys::Win32::System::Pipes::WaitNamedPipeW; // OsStr -> UTF-16 + NUL let mut wide: Vec<u16> = addr.encode_wide().collect(); wide.push(0); // Try to open; if the pipe is busy, wait and retry. let handle = loop { // SAFETY: WinAPI call let h = unsafe { CreateFileW( wide.as_ptr(), FILE_GENERIC_READ | FILE_GENERIC_WRITE, 0, // no sharing std::ptr::null(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, // blocking std::ptr::null_mut(), ) }; if h != INVALID_HANDLE_VALUE { break h; } let err = io::Error::last_os_error(); if err.raw_os_error() == Some(ERROR_PIPE_BUSY as i32) { // SAFETY: WinAPI call unsafe { WaitNamedPipeW(wide.as_ptr(), NMPWAIT_WAIT_FOREVER) }; continue; } else { return Err(err); } }; // Ensure byte mode to mirror Unix stream semantics. // SAFETY: WinAPI call unsafe { let _ = SetNamedPipeHandleState( handle, &PIPE_READMODE_BYTE, std::ptr::null_mut(), std::ptr::null_mut(), ); } // SAFETY: Passing WinAPI handle let file = unsafe { std::fs::File::from_raw_handle(handle as _) }; Ok(Self(file)) } } #[cfg(all(not(unix), not(windows)))] impl IpcPipe { fn connect_impl(_addr: &OsStr) -> io::Result<Self> { Err(io::Error::new( io::ErrorKind::Unsupported, "Platform not supported.", )) } } impl Read for IpcPipe { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl Write for IpcPipe { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { self.0.flush() } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/permissions/which.rs
runtime/permissions/which.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::ffi::OsStr; use std::ffi::OsString; use std::path::PathBuf; pub use which::Error; use which::sys::Sys; pub fn which_in( sys: impl WhichSys, binary_name: &str, path: Option<OsString>, cwd: PathBuf, ) -> Result<PathBuf, Error> { let sys = WhichSysAdapter(sys); let config = which::WhichConfig::new_with_sys(sys) .custom_cwd(cwd) .binary_name(OsString::from(binary_name)); let config = match path { Some(path) => config.custom_path_list(path), None => config, }; config.first_result() } #[sys_traits::auto_impl] pub trait WhichSys: sys_traits::EnvHomeDir + sys_traits::EnvCurrentDir + sys_traits::EnvVar + sys_traits::FsReadDir + sys_traits::FsMetadata + Clone + 'static { } #[derive(Clone)] pub struct WhichSysAdapter<TSys: WhichSys>(TSys); impl<TSys: WhichSys> Sys for WhichSysAdapter<TSys> { type ReadDirEntry = WhichReadDirEntrySysAdapter<TSys::ReadDirEntry>; type Metadata = WhichMetadataSysAdapter<TSys::Metadata>; fn is_windows(&self) -> bool { sys_traits::impls::is_windows() } fn current_dir(&self) -> std::io::Result<std::path::PathBuf> { self.0.env_current_dir() } fn home_dir(&self) -> Option<std::path::PathBuf> { self.0.env_home_dir() } fn env_split_paths(&self, paths: &OsStr) -> Vec<std::path::PathBuf> { if cfg!(target_arch = "wasm32") && self.is_windows() { // not perfect, but good enough paths .to_string_lossy() .split(";") .map(PathBuf::from) .collect() } else { std::env::split_paths(paths).collect() } } fn env_path(&self) -> Option<OsString> { self.0.env_var_os("PATH") } fn env_path_ext(&self) -> Option<OsString> { self.0.env_var_os("PATHEXT") } fn metadata( &self, path: &std::path::Path, ) -> std::io::Result<Self::Metadata> { self.0.fs_metadata(path).map(WhichMetadataSysAdapter) } fn symlink_metadata( &self, path: &std::path::Path, ) -> std::io::Result<Self::Metadata> { self .0 .fs_symlink_metadata(path) .map(WhichMetadataSysAdapter) } fn read_dir( &self, path: &std::path::Path, ) -> std::io::Result< Box<dyn Iterator<Item = std::io::Result<Self::ReadDirEntry>>>, > { let iter = self.0.fs_read_dir(path)?; let iter = Box::new( iter .into_iter() .map(|value| value.map(WhichReadDirEntrySysAdapter)), ); Ok(iter) } #[cfg(unix)] fn is_valid_executable( &self, path: &std::path::Path, ) -> std::io::Result<bool> { use nix::unistd::AccessFlags; use nix::unistd::access; match access(path, AccessFlags::X_OK) { Ok(()) => Ok(true), Err(nix::errno::Errno::ENOENT) => Ok(false), Err(e) => Err(std::io::Error::from_raw_os_error(e as i32)), } } #[cfg(target_arch = "wasm32")] fn is_valid_executable( &self, _path: &std::path::Path, ) -> std::io::Result<bool> { Ok(true) } #[cfg(windows)] fn is_valid_executable( &self, path: &std::path::Path, ) -> std::io::Result<bool> { use std::os::windows::ffi::OsStrExt; let name = path .as_os_str() .encode_wide() .chain(Some(0)) .collect::<Vec<u16>>(); let mut bt: u32 = 0; // SAFETY: winapi call unsafe { Ok( windows_sys::Win32::Storage::FileSystem::GetBinaryTypeW( name.as_ptr(), &mut bt, ) != 0, ) } } } pub struct WhichReadDirEntrySysAdapter<TFsDirEntry: sys_traits::FsDirEntry>( TFsDirEntry, ); impl<TFsDirEntry: sys_traits::FsDirEntry> which::sys::SysReadDirEntry for WhichReadDirEntrySysAdapter<TFsDirEntry> { fn file_name(&self) -> std::ffi::OsString { self.0.file_name().into_owned() } fn path(&self) -> std::path::PathBuf { self.0.path().into_owned() } } pub struct WhichMetadataSysAdapter<TMetadata: sys_traits::FsMetadataValue>( TMetadata, ); impl<TMetadata: sys_traits::FsMetadataValue> which::sys::SysMetadata for WhichMetadataSysAdapter<TMetadata> { fn is_symlink(&self) -> bool { self.0.file_type().is_symlink() } fn is_file(&self) -> bool { self.0.file_type().is_file() } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/permissions/prompter.rs
runtime/permissions/prompter.rs
// Copyright 2018-2025 the Deno authors. MIT license. use once_cell::sync::Lazy; use parking_lot::Mutex; /// Helper function to make control characters visible so users can see the underlying filename. #[cfg(not(target_arch = "wasm32"))] fn escape_control_characters(s: &str) -> std::borrow::Cow<'_, str> { use deno_terminal::colors; if !s.contains(|c: char| c.is_ascii_control() || c.is_control()) { return std::borrow::Cow::Borrowed(s); } let mut output = String::with_capacity(s.len() * 2); for c in s.chars() { match c { c if c.is_ascii_control() => output.push_str( &colors::white_bold_on_red(c.escape_debug().to_string()).to_string(), ), c if c.is_control() => output.push_str( &colors::white_bold_on_red(c.escape_debug().to_string()).to_string(), ), c => output.push(c), } } output.into() } pub const PERMISSION_EMOJI: &str = "⚠️"; #[derive(Debug, Eq, PartialEq)] pub enum PromptResponse { Allow, Deny, AllowAll, } #[cfg(not(target_arch = "wasm32"))] type DefaultPrompter = TtyPrompter; #[cfg(target_arch = "wasm32")] type DefaultPrompter = DeniedPrompter; static PERMISSION_PROMPTER: Lazy<Mutex<Box<dyn PermissionPrompter>>> = Lazy::new(|| Mutex::new(Box::new(DefaultPrompter::default()))); static MAYBE_BEFORE_PROMPT_CALLBACK: Lazy<Mutex<Option<PromptCallback>>> = Lazy::new(|| Mutex::new(None)); static MAYBE_AFTER_PROMPT_CALLBACK: Lazy<Mutex<Option<PromptCallback>>> = Lazy::new(|| Mutex::new(None)); pub(crate) static MAYBE_CURRENT_STACKTRACE: Lazy< Mutex<Option<GetFormattedStackFn>>, > = Lazy::new(|| Mutex::new(None)); pub fn set_current_stacktrace(get_stack: GetFormattedStackFn) { *MAYBE_CURRENT_STACKTRACE.lock() = Some(get_stack); } pub fn permission_prompt( message: &str, flag: &str, api_name: Option<&str>, is_unary: bool, ) -> PromptResponse { if let Some(before_callback) = MAYBE_BEFORE_PROMPT_CALLBACK.lock().as_mut() { before_callback(); } let stack = MAYBE_CURRENT_STACKTRACE.lock().take(); let r = PERMISSION_PROMPTER .lock() .prompt(message, flag, api_name, is_unary, stack); if let Some(after_callback) = MAYBE_AFTER_PROMPT_CALLBACK.lock().as_mut() { after_callback(); } r } pub fn set_prompt_callbacks( before_callback: PromptCallback, after_callback: PromptCallback, ) { *MAYBE_BEFORE_PROMPT_CALLBACK.lock() = Some(before_callback); *MAYBE_AFTER_PROMPT_CALLBACK.lock() = Some(after_callback); } pub fn set_prompter(prompter: Box<dyn PermissionPrompter>) { *PERMISSION_PROMPTER.lock() = prompter; } pub type PromptCallback = Box<dyn FnMut() + Send + Sync>; pub type GetFormattedStackFn = Box<dyn Fn() -> Vec<String> + Send + Sync>; pub trait PermissionPrompter: Send + Sync { fn prompt( &mut self, message: &str, name: &str, api_name: Option<&str>, is_unary: bool, get_stack: Option<GetFormattedStackFn>, ) -> PromptResponse; } #[derive(Default)] pub struct DeniedPrompter; impl PermissionPrompter for DeniedPrompter { fn prompt( &mut self, _message: &str, _name: &str, _api_name: Option<&str>, _is_unary: bool, _get_stack: Option<GetFormattedStackFn>, ) -> PromptResponse { PromptResponse::Deny } } #[cfg(unix)] fn clear_stdin( _stdin_lock: &mut std::io::StdinLock, _stderr_lock: &mut std::io::StderrLock, ) -> Result<(), std::io::Error> { use std::mem::MaybeUninit; const STDIN_FD: i32 = 0; // SAFETY: use libc to flush stdin unsafe { // Create fd_set for select let mut raw_fd_set = MaybeUninit::<libc::fd_set>::uninit(); libc::FD_ZERO(raw_fd_set.as_mut_ptr()); libc::FD_SET(STDIN_FD, raw_fd_set.as_mut_ptr()); loop { let r = libc::tcflush(STDIN_FD, libc::TCIFLUSH); if r != 0 { return Err(std::io::Error::other("clear_stdin failed (tcflush)")); } // Initialize timeout for select to be 100ms let mut timeout = libc::timeval { tv_sec: 0, tv_usec: 100_000, }; // Call select with the stdin file descriptor set let r = libc::select( STDIN_FD + 1, // nfds should be set to the highest-numbered file descriptor in any of the three sets, plus 1. raw_fd_set.as_mut_ptr(), std::ptr::null_mut(), std::ptr::null_mut(), &mut timeout, ); // Check if select returned an error if r < 0 { return Err(std::io::Error::other("clear_stdin failed (select)")); } // Check if select returned due to timeout (stdin is quiescent) if r == 0 { break; // Break out of the loop as stdin is quiescent } // If select returned due to data available on stdin, clear it by looping around to flush } } Ok(()) } #[cfg(all(not(unix), not(target_arch = "wasm32")))] fn clear_stdin( stdin_lock: &mut std::io::StdinLock, stderr_lock: &mut std::io::StderrLock, ) -> Result<(), std::io::Error> { use std::io::BufRead; use std::io::StdinLock; use std::io::Write as IoWrite; use winapi::shared::minwindef::TRUE; use winapi::shared::minwindef::UINT; use winapi::shared::minwindef::WORD; use winapi::shared::ntdef::WCHAR; use winapi::um::processenv::GetStdHandle; use winapi::um::winbase::STD_INPUT_HANDLE; use winapi::um::wincon::FlushConsoleInputBuffer; use winapi::um::wincon::PeekConsoleInputW; use winapi::um::wincon::WriteConsoleInputW; use winapi::um::wincontypes::INPUT_RECORD; use winapi::um::wincontypes::KEY_EVENT; use winapi::um::winnt::HANDLE; use winapi::um::winuser::MAPVK_VK_TO_VSC; use winapi::um::winuser::MapVirtualKeyW; use winapi::um::winuser::VK_RETURN; // SAFETY: winapi calls unsafe { let stdin = GetStdHandle(STD_INPUT_HANDLE); // emulate an enter key press to clear any line buffered console characters emulate_enter_key_press(stdin)?; // read the buffered line or enter key press read_stdin_line(stdin_lock)?; // check if our emulated key press was executed if is_input_buffer_empty(stdin)? { // if so, move the cursor up to prevent a blank line move_cursor_up(stderr_lock)?; } else { // the emulated key press is still pending, so a buffered line was read // and we can flush the emulated key press flush_input_buffer(stdin)?; } } return Ok(()); unsafe fn flush_input_buffer(stdin: HANDLE) -> Result<(), std::io::Error> { // SAFETY: winapi calls let success = unsafe { FlushConsoleInputBuffer(stdin) }; if success != TRUE { return Err(std::io::Error::other(format!( "Could not flush the console input buffer: {}", std::io::Error::last_os_error() ))); } Ok(()) } unsafe fn emulate_enter_key_press( stdin: HANDLE, ) -> Result<(), std::io::Error> { // SAFETY: winapi calls unsafe { // https://github.com/libuv/libuv/blob/a39009a5a9252a566ca0704d02df8dabc4ce328f/src/win/tty.c#L1121-L1131 let mut input_record: INPUT_RECORD = std::mem::zeroed(); input_record.EventType = KEY_EVENT; input_record.Event.KeyEvent_mut().bKeyDown = TRUE; input_record.Event.KeyEvent_mut().wRepeatCount = 1; input_record.Event.KeyEvent_mut().wVirtualKeyCode = VK_RETURN as WORD; input_record.Event.KeyEvent_mut().wVirtualScanCode = MapVirtualKeyW(VK_RETURN as UINT, MAPVK_VK_TO_VSC) as WORD; *input_record.Event.KeyEvent_mut().uChar.UnicodeChar_mut() = '\r' as WCHAR; let mut record_written = 0; let success = WriteConsoleInputW(stdin, &input_record, 1, &mut record_written); if success != TRUE { return Err(std::io::Error::other(format!( "Could not emulate enter key press: {}", std::io::Error::last_os_error() ))); } } Ok(()) } unsafe fn is_input_buffer_empty( stdin: HANDLE, ) -> Result<bool, std::io::Error> { let mut buffer = Vec::with_capacity(1); let mut events_read = 0; // SAFETY: winapi calls let success = unsafe { PeekConsoleInputW(stdin, buffer.as_mut_ptr(), 1, &mut events_read) }; if success != TRUE { return Err(std::io::Error::other(format!( "Could not peek the console input buffer: {}", std::io::Error::last_os_error() ))); } Ok(events_read == 0) } fn move_cursor_up( stderr_lock: &mut std::io::StderrLock, ) -> Result<(), std::io::Error> { write!(stderr_lock, "\x1B[1A") } fn read_stdin_line(stdin_lock: &mut StdinLock) -> Result<(), std::io::Error> { let mut input = String::new(); stdin_lock.read_line(&mut input)?; Ok(()) } } // Clear n-lines in terminal and move cursor to the beginning of the line. #[cfg(not(target_arch = "wasm32"))] fn clear_n_lines(stderr_lock: &mut std::io::StderrLock, n: usize) { use std::io::Write; write!(stderr_lock, "\x1B[{n}A\x1B[0J").unwrap(); } #[cfg(unix)] fn get_stdin_metadata() -> std::io::Result<std::fs::Metadata> { use std::os::fd::FromRawFd; use std::os::fd::IntoRawFd; // SAFETY: we don't know if fd 0 is valid but metadata() will return an error in this case (bad file descriptor) // and we can panic. unsafe { let stdin = std::fs::File::from_raw_fd(0); let metadata = stdin.metadata().unwrap(); let _ = stdin.into_raw_fd(); Ok(metadata) } } #[cfg(not(target_arch = "wasm32"))] #[derive(Default)] pub struct TtyPrompter; #[cfg(not(target_arch = "wasm32"))] impl PermissionPrompter for TtyPrompter { fn prompt( &mut self, message: &str, name: &str, api_name: Option<&str>, is_unary: bool, get_stack: Option<GetFormattedStackFn>, ) -> PromptResponse { use std::fmt::Write; use std::io::BufRead; use std::io::IsTerminal; use std::io::Write as IoWrite; use deno_terminal::colors; // 10kB of permission prompting should be enough for anyone const MAX_PERMISSION_PROMPT_LENGTH: usize = 10 * 1024; if !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal() { return PromptResponse::Deny; }; #[allow(clippy::print_stderr)] if message.len() > MAX_PERMISSION_PROMPT_LENGTH { eprintln!( "❌ Permission prompt length ({} bytes) was larger than the configured maximum length ({} bytes): denying request.", message.len(), MAX_PERMISSION_PROMPT_LENGTH ); eprintln!( "❌ WARNING: This may indicate that code is trying to bypass or hide permission check requests." ); eprintln!( "❌ Run again with --allow-{name} to bypass this check if this is really what you want to do." ); return PromptResponse::Deny; } #[cfg(unix)] let metadata_before = get_stdin_metadata().unwrap(); // Lock stdio streams, so no other output is written while the prompt is // displayed. let stdout_lock = std::io::stdout().lock(); let mut stderr_lock = std::io::stderr().lock(); let mut stdin_lock = std::io::stdin().lock(); // For security reasons we must consume everything in stdin so that previously // buffered data cannot affect the prompt. #[allow(clippy::print_stderr)] if let Err(err) = clear_stdin(&mut stdin_lock, &mut stderr_lock) { eprintln!("Error clearing stdin for permission prompt. {err:#}"); return PromptResponse::Deny; // don't grant permission if this fails } let message = escape_control_characters(message); let name = escape_control_characters(name); let api_name = api_name.map(escape_control_characters); // print to stderr so that if stdout is piped this is still displayed. let opts: String = if is_unary { format!( "[y/n/A] (y = yes, allow; n = no, deny; A = allow all {name} permissions)" ) } else { "[y/n] (y = yes, allow; n = no, deny)".to_string() }; // output everything in one shot to make the tests more reliable let stack_lines_count = { let mut output = String::new(); write!(&mut output, "┏ {PERMISSION_EMOJI} ").unwrap(); write!(&mut output, "{}", colors::bold("Deno requests ")).unwrap(); write!(&mut output, "{}", colors::bold(message.clone())).unwrap(); writeln!(&mut output, "{}", colors::bold(".")).unwrap(); if let Some(api_name) = api_name.clone() { writeln!( &mut output, "┠─ Requested by `{}` API.", colors::bold(api_name) ) .unwrap(); } let stack_lines_count = if let Some(get_stack) = get_stack { let stack = get_stack(); let len = stack.len(); for (idx, frame) in stack.into_iter().enumerate() { writeln!( &mut output, "┃ {} {}", colors::gray(if idx != len - 1 { "β”œβ”€" } else { "└─" }), colors::gray(frame), ) .unwrap(); } len } else { writeln!( &mut output, "┠─ To see a stack trace for this prompt, set the DENO_TRACE_PERMISSIONS environmental variable.", ).unwrap(); 1 }; let msg = format!( "Learn more at: {}", colors::cyan_with_underline(&format!( "https://docs.deno.com/go/--allow-{}", name )) ); writeln!(&mut output, "┠─ {}", colors::italic(&msg)).unwrap(); let msg = if crate::is_standalone() { format!( "Specify the required permissions during compile time using `deno compile --allow-{name}`." ) } else { format!("Run again with --allow-{name} to bypass this prompt.") }; writeln!(&mut output, "┠─ {}", colors::italic(&msg)).unwrap(); write!(&mut output, "β”— {}", colors::bold("Allow?")).unwrap(); write!(&mut output, " {opts} > ").unwrap(); stderr_lock.write_all(output.as_bytes()).unwrap(); stack_lines_count }; let value = loop { // Clear stdin each time we loop around in case the user accidentally pasted // multiple lines or otherwise did something silly to generate a torrent of // input. This doesn't work on Windows because `clear_stdin` has other side-effects. #[allow(clippy::print_stderr)] #[cfg(unix)] if let Err(err) = clear_stdin(&mut stdin_lock, &mut stderr_lock) { eprintln!("Error clearing stdin for permission prompt. {err:#}"); return PromptResponse::Deny; // don't grant permission if this fails } let mut input = String::new(); let result = stdin_lock.read_line(&mut input); let input = input.trim_end_matches(['\r', '\n']); if result.is_err() || input.len() != 1 { break PromptResponse::Deny; }; let clear_n = if api_name.is_some() { 5 } else { 4 } + stack_lines_count; match input.as_bytes()[0] as char { 'y' | 'Y' => { clear_n_lines(&mut stderr_lock, clear_n); let msg = format!("Granted {message}."); writeln!(stderr_lock, "βœ… {}", colors::bold(&msg)).unwrap(); break PromptResponse::Allow; } 'n' | 'N' | '\x1b' => { clear_n_lines(&mut stderr_lock, clear_n); let msg = format!("Denied {message}."); writeln!(stderr_lock, "❌ {}", colors::bold(&msg)).unwrap(); break PromptResponse::Deny; } 'A' if is_unary => { clear_n_lines(&mut stderr_lock, clear_n); let msg = format!("Granted all {name} access."); writeln!(stderr_lock, "βœ… {}", colors::bold(&msg)).unwrap(); break PromptResponse::AllowAll; } _ => { // If we don't get a recognized option try again. clear_n_lines(&mut stderr_lock, 1); write!( stderr_lock, "β”— {} {opts} > ", colors::bold("Unrecognized option. Allow?") ) .unwrap(); } }; }; drop(stdout_lock); drop(stderr_lock); drop(stdin_lock); // Ensure that stdin has not changed from the beginning to the end of the prompt. We consider // it sufficient to check a subset of stat calls. We do not consider the likelihood of a stdin // swap attack on Windows to be high enough to add this check for that platform. These checks will // terminate the runtime as they indicate something nefarious is going on. #[cfg(unix)] { use std::os::unix::fs::MetadataExt; let metadata_after = get_stdin_metadata().unwrap(); assert_eq!(metadata_before.dev(), metadata_after.dev()); assert_eq!(metadata_before.ino(), metadata_after.ino()); assert_eq!(metadata_before.rdev(), metadata_after.rdev()); assert_eq!(metadata_before.uid(), metadata_after.uid()); assert_eq!(metadata_before.gid(), metadata_after.gid()); assert_eq!(metadata_before.mode(), metadata_after.mode()); } // Ensure that stdin and stderr are still terminals before we yield the response. assert!(std::io::stdin().is_terminal() && std::io::stderr().is_terminal()); value } } #[cfg(test)] pub mod tests { use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use super::*; pub struct TestPrompter; impl PermissionPrompter for TestPrompter { fn prompt( &mut self, _message: &str, _name: &str, _api_name: Option<&str>, _is_unary: bool, _get_stack: Option<GetFormattedStackFn>, ) -> PromptResponse { if STUB_PROMPT_VALUE.load(Ordering::SeqCst) { PromptResponse::Allow } else { PromptResponse::Deny } } } static STUB_PROMPT_VALUE: AtomicBool = AtomicBool::new(true); pub static PERMISSION_PROMPT_STUB_VALUE_SETTER: Lazy< Mutex<PermissionPromptStubValueSetter>, > = Lazy::new(|| Mutex::new(PermissionPromptStubValueSetter)); pub struct PermissionPromptStubValueSetter; impl PermissionPromptStubValueSetter { pub fn set(&self, value: bool) { STUB_PROMPT_VALUE.store(value, Ordering::SeqCst); } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/permissions/runtime_descriptor_parser.rs
runtime/permissions/runtime_descriptor_parser.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::path::Path; use std::path::PathBuf; use crate::AllowRunDescriptor; use crate::AllowRunDescriptorParseResult; use crate::DenyRunDescriptor; use crate::EnvDescriptor; use crate::FfiDescriptor; use crate::ImportDescriptor; use crate::NetDescriptor; use crate::PathDescriptor; use crate::PathQueryDescriptor; use crate::PathResolveError; use crate::ReadDescriptor; use crate::RunDescriptorParseError; use crate::RunQueryDescriptor; use crate::SpecialFilePathQueryDescriptor; use crate::SysDescriptor; use crate::SysDescriptorParseError; use crate::WriteDescriptor; #[sys_traits::auto_impl] pub trait RuntimePermissionDescriptorParserSys: crate::which::WhichSys + sys_traits::FsCanonicalize + Send + Sync { } #[derive(Debug)] pub struct RuntimePermissionDescriptorParser< TSys: RuntimePermissionDescriptorParserSys, > { sys: TSys, } impl<TSys: RuntimePermissionDescriptorParserSys> RuntimePermissionDescriptorParser<TSys> { pub fn new(sys: TSys) -> Self { Self { sys } } fn resolve_cwd(&self) -> Result<PathBuf, PathResolveError> { self .sys .env_current_dir() .map_err(PathResolveError::CwdResolve) } fn parse_path_descriptor( &self, path: Cow<'_, Path>, ) -> Result<PathDescriptor, PathResolveError> { PathDescriptor::new(&self.sys, path) } } impl<TSys: RuntimePermissionDescriptorParserSys + std::fmt::Debug> crate::PermissionDescriptorParser for RuntimePermissionDescriptorParser<TSys> { fn parse_read_descriptor( &self, text: &str, ) -> Result<ReadDescriptor, PathResolveError> { Ok(ReadDescriptor( self.parse_path_descriptor(Cow::Borrowed(Path::new(text)))?, )) } fn parse_write_descriptor( &self, text: &str, ) -> Result<WriteDescriptor, PathResolveError> { Ok(WriteDescriptor( self.parse_path_descriptor(Cow::Borrowed(Path::new(text)))?, )) } fn parse_net_descriptor( &self, text: &str, ) -> Result<NetDescriptor, crate::NetDescriptorParseError> { NetDescriptor::parse_for_list(text) } fn parse_import_descriptor( &self, text: &str, ) -> Result<ImportDescriptor, crate::NetDescriptorParseError> { ImportDescriptor::parse_for_list(text) } fn parse_env_descriptor( &self, text: &str, ) -> Result<EnvDescriptor, crate::EnvDescriptorParseError> { if text.is_empty() { Err(crate::EnvDescriptorParseError) } else { Ok(EnvDescriptor::new(Cow::Borrowed(text))) } } fn parse_sys_descriptor( &self, text: &str, ) -> Result<SysDescriptor, SysDescriptorParseError> { if text.is_empty() { Err(SysDescriptorParseError::Empty) } else { Ok(SysDescriptor::parse(text.to_string())?) } } fn parse_allow_run_descriptor( &self, text: &str, ) -> Result<AllowRunDescriptorParseResult, RunDescriptorParseError> { Ok(AllowRunDescriptor::parse( text, &self.resolve_cwd()?, &self.sys, )?) } fn parse_deny_run_descriptor( &self, text: &str, ) -> Result<DenyRunDescriptor, PathResolveError> { Ok(DenyRunDescriptor::parse(text, &self.resolve_cwd()?)) } fn parse_ffi_descriptor( &self, text: &str, ) -> Result<FfiDescriptor, PathResolveError> { Ok(FfiDescriptor( self.parse_path_descriptor(Cow::Borrowed(Path::new(text)))?, )) } // queries fn parse_path_query<'a>( &self, path: Cow<'a, Path>, ) -> Result<PathQueryDescriptor<'a>, PathResolveError> { PathQueryDescriptor::new(&self.sys, path) } fn parse_special_file_descriptor<'a>( &self, path: PathQueryDescriptor<'a>, ) -> Result<SpecialFilePathQueryDescriptor<'a>, PathResolveError> { SpecialFilePathQueryDescriptor::parse(&self.sys, path) } fn parse_net_query( &self, text: &str, ) -> Result<NetDescriptor, crate::NetDescriptorParseError> { NetDescriptor::parse_for_query(text) } fn parse_run_query<'a>( &self, requested: &'a str, ) -> Result<RunQueryDescriptor<'a>, RunDescriptorParseError> { if requested.is_empty() { return Err(RunDescriptorParseError::EmptyRunQuery); } RunQueryDescriptor::parse(requested, &self.sys) .map_err(RunDescriptorParseError::PathResolve) } } #[cfg(test)] mod test { use super::*; use crate::PermissionDescriptorParser; #[test] fn test_handle_empty_value() { let parser = RuntimePermissionDescriptorParser::new(sys_traits::impls::RealSys); assert!(parser.parse_read_descriptor("").is_err()); assert!(parser.parse_write_descriptor("").is_err()); assert!(parser.parse_env_descriptor("").is_err()); assert!(parser.parse_net_descriptor("").is_err()); assert!(parser.parse_ffi_descriptor("").is_err()); assert!( parser .parse_path_query(Cow::Borrowed(Path::new(""))) .is_err() ); assert!(parser.parse_net_query("").is_err()); assert!(parser.parse_run_query("").is_err()); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/permissions/broker.rs
runtime/permissions/broker.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::io::BufRead; use std::io::BufReader; use std::io::Write; use std::path::PathBuf; use std::sync::OnceLock; use std::sync::atomic::AtomicU32; use parking_lot::Mutex; use super::BrokerResponse; use crate::ipc_pipe::IpcPipe; // TODO(bartlomieju): currently randomly selected exit code, it should // be documented static BROKER_EXIT_CODE: i32 = 87; static PERMISSION_BROKER: OnceLock<PermissionBroker> = OnceLock::new(); static PID: OnceLock<u32> = OnceLock::new(); pub fn set_broker(broker: PermissionBroker) { assert!(PERMISSION_BROKER.set(broker).is_ok()); assert!(PID.set(std::process::id()).is_ok()); } pub fn has_broker() -> bool { PERMISSION_BROKER.get().is_some() } #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] struct PermissionBrokerRequest<'a> { v: u32, pid: u32, id: u32, datetime: String, permission: &'a str, value: Option<String>, } #[derive(Debug, serde::Deserialize)] #[serde(rename_all = "camelCase")] struct PermissionBrokerResponse { id: u32, result: String, reason: Option<String>, } pub struct PermissionBroker { stream: Mutex<IpcPipe>, next_id: AtomicU32, } impl PermissionBroker { pub fn new(socket_path: impl Into<PathBuf>) -> Self { let socket_path = socket_path.into(); let stream = match IpcPipe::connect(&socket_path) { Ok(s) => s, Err(err) => { log::error!("Failed to create permission broker: {:?}", err); std::process::exit(BROKER_EXIT_CODE); } }; Self { stream: Mutex::new(stream), next_id: std::sync::atomic::AtomicU32::new(1), } } fn check( &self, permission: &str, stringified_value: Option<String>, ) -> std::io::Result<BrokerResponse> { let mut stream = self.stream.lock(); let id = self .next_id .fetch_add(1, std::sync::atomic::Ordering::Relaxed); let request = PermissionBrokerRequest { v: 1, pid: *PID.get().unwrap(), id, datetime: chrono::Utc::now().to_rfc3339(), permission, value: stringified_value, }; let msg = format!("{}\n", serde_json::to_string(&request).unwrap()); log::trace!("-> broker req {}", msg); stream.write_all(msg.as_bytes())?; // Read response using line reader let mut reader = BufReader::new(&mut *stream); let mut response_line = String::new(); reader.read_line(&mut response_line)?; let response = serde_json::from_str::<PermissionBrokerResponse>(response_line.trim()) .map_err(std::io::Error::other)?; log::trace!("<- broker resp {:?}", response); if response.id != id { return Err(std::io::Error::other( "Permission broker response ID mismatch", )); } let prompt_response = match response.result.as_str() { "allow" => BrokerResponse::Allow, "deny" => BrokerResponse::Deny { message: response.reason, }, _ => { return Err(std::io::Error::other( "Permission broker unknown result variant", )); } }; Ok(prompt_response) } } pub fn maybe_check_with_broker( name: &str, stringified_value_fn: impl Fn() -> Option<String>, ) -> Option<BrokerResponse> { let broker = PERMISSION_BROKER.get()?; let resp = match broker.check(name, stringified_value_fn()) { Ok(resp) => resp, Err(err) => { log::error!("{:?}", err); std::process::exit(BROKER_EXIT_CODE); } }; Some(resp) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/features/gen.rs
runtime/features/gen.rs
// Copyright 2018-2025 the Deno authors. MIT license. /// Don't modify this file manually. /// /// This file is auto-generated by the build script, modify `data.rs` instead. use crate::structs::UnstableFeatureDefinition; use crate::structs::UnstableFeatureKind; pub static UNSTABLE_FEATURES: &[UnstableFeatureDefinition] = &[ UnstableFeatureDefinition { name: "bare-node-builtins", flag_name: "unstable-bare-node-builtins", help_text: "Enable unstable bare node builtins feature", show_in_help: true, id: 0, kind: UnstableFeatureKind::Cli, }, UnstableFeatureDefinition { name: "broadcast-channel", flag_name: "unstable-broadcast-channel", help_text: "Enable unstable `BroadcastChannel` API", show_in_help: false, id: 1, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "bundle", flag_name: "unstable-bundle", help_text: "Enable unstable bundle runtime API", show_in_help: true, id: 2, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "byonm", flag_name: "unstable-byonm", help_text: "", show_in_help: false, id: 3, kind: UnstableFeatureKind::Cli, }, UnstableFeatureDefinition { name: "cron", flag_name: "unstable-cron", help_text: "Enable unstable `Deno.cron` API", show_in_help: true, id: 4, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "detect-cjs", flag_name: "unstable-detect-cjs", help_text: "Treats ambiguous .js, .jsx, .ts, .tsx files as CommonJS modules in more cases", show_in_help: true, id: 5, kind: UnstableFeatureKind::Cli, }, UnstableFeatureDefinition { name: "ffi", flag_name: "unstable-ffi", help_text: "Enable unstable FFI APIs", show_in_help: false, id: 6, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "fs", flag_name: "unstable-fs", help_text: "Enable unstable file system APIs", show_in_help: false, id: 7, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "http", flag_name: "unstable-http", help_text: "Enable unstable HTTP APIs", show_in_help: false, id: 8, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "kv", flag_name: "unstable-kv", help_text: "Enable unstable KV APIs", show_in_help: true, id: 9, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "lazy-dynamic-imports", flag_name: "unstable-lazy-dynamic-imports", help_text: "Lazily loads statically analyzable dynamic imports when not running with type checking. Warning: This may change the order of semver specifier resolution.", show_in_help: true, id: 10, kind: UnstableFeatureKind::Cli, }, UnstableFeatureDefinition { name: "lockfile-v5", flag_name: "unstable-lockfile-v5", help_text: "Enable unstable lockfile v5", show_in_help: true, id: 11, kind: UnstableFeatureKind::Cli, }, UnstableFeatureDefinition { name: "net", flag_name: "unstable-net", help_text: "enable unstable net APIs", show_in_help: true, id: 12, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "no-legacy-abort", flag_name: "unstable-no-legacy-abort", help_text: "Enable abort signal in Deno.serve without legacy behavior. This will not abort the server when the request is handled successfully.", show_in_help: true, id: 13, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "node-globals", flag_name: "unstable-node-globals", help_text: "Prefer Node.js globals over Deno globals - currently this refers to `setTimeout` and `setInterval` APIs.", show_in_help: true, id: 14, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "npm-lazy-caching", flag_name: "unstable-npm-lazy-caching", help_text: "Enable unstable lazy caching of npm dependencies, downloading them only as needed (disabled: all npm packages in package.json are installed on startup; enabled: only npm packages that are actually referenced in an import are installed", show_in_help: true, id: 15, kind: UnstableFeatureKind::Cli, }, UnstableFeatureDefinition { name: "otel", flag_name: "unstable-otel", help_text: "Enable unstable OpenTelemetry features", show_in_help: false, id: 16, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "process", flag_name: "unstable-process", help_text: "Enable unstable process APIs", show_in_help: false, id: 17, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "raw-imports", flag_name: "unstable-raw-imports", help_text: "Enable unstable 'bytes' and 'text' imports.", show_in_help: true, id: 18, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "sloppy-imports", flag_name: "unstable-sloppy-imports", help_text: "Enable unstable resolving of specifiers by extension probing, .js to .ts, and directory probing", show_in_help: true, id: 19, kind: UnstableFeatureKind::Cli, }, UnstableFeatureDefinition { name: "subdomain-wildcards", flag_name: "unstable-subdomain-wildcards", help_text: "Enable subdomain wildcards support for the `--allow-net` flag", show_in_help: false, id: 20, kind: UnstableFeatureKind::Cli, }, UnstableFeatureDefinition { name: "temporal", flag_name: "unstable-temporal", help_text: "Enable unstable Temporal API", show_in_help: true, id: 21, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "tsgo", flag_name: "unstable-tsgo", help_text: "Enable unstable TypeScript Go integration", show_in_help: true, id: 22, kind: UnstableFeatureKind::Cli, }, UnstableFeatureDefinition { name: "unsafe-proto", flag_name: "unstable-unsafe-proto", help_text: "Enable unsafe __proto__ support. This is a security risk.", show_in_help: true, id: 23, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "vsock", flag_name: "unstable-vsock", help_text: "Enable unstable VSOCK APIs", show_in_help: false, id: 24, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "webgpu", flag_name: "unstable-webgpu", help_text: "Enable unstable WebGPU APIs", show_in_help: true, id: 25, kind: UnstableFeatureKind::Runtime, }, UnstableFeatureDefinition { name: "worker-options", flag_name: "unstable-worker-options", help_text: "Enable unstable Web Worker APIs", show_in_help: true, id: 26, kind: UnstableFeatureKind::Runtime, }, ]; pub struct UnstableEnvVarNames { pub bare_node_builtins: &'static str, pub lazy_dynamic_imports: &'static str, pub lockfile_v5: &'static str, pub npm_lazy_caching: &'static str, pub raw_imports: &'static str, pub sloppy_imports: &'static str, pub subdomain_wildcards: &'static str, pub tsgo: &'static str, } pub static UNSTABLE_ENV_VAR_NAMES: UnstableEnvVarNames = UnstableEnvVarNames { bare_node_builtins: "DENO_UNSTABLE_BARE_NODE_BUILTINS", lazy_dynamic_imports: "DENO_UNSTABLE_LAZY_DYNAMIC_IMPORTS", lockfile_v5: "DENO_UNSTABLE_LOCKFILE_V5", npm_lazy_caching: "DENO_UNSTABLE_NPM_LAZY_CACHING", raw_imports: "DENO_UNSTABLE_RAW_IMPORTS", sloppy_imports: "DENO_UNSTABLE_SLOPPY_IMPORTS", subdomain_wildcards: "DENO_UNSTABLE_SUBDOMAIN_WILDCARDS", tsgo: "DENO_UNSTABLE_TSGO", };
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/features/lib.rs
runtime/features/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. mod r#gen; mod structs; use std::collections::BTreeSet; pub use r#gen::UNSTABLE_ENV_VAR_NAMES; pub use r#gen::UNSTABLE_FEATURES; pub use structs::UnstableFeatureKind; pub const JS_SOURCE: deno_core::FastStaticString = deno_core::ascii_str_include!("./gen.js"); pub type ExitCb = Box<dyn Fn(&str, &str) + Send + Sync>; #[allow(clippy::print_stderr)] #[allow(clippy::disallowed_methods)] fn exit(feature: &str, api_name: &str) { eprintln!("Feature '{feature}' for '{api_name}' was not specified, exiting."); std::process::exit(70); } pub struct FeatureChecker { features: BTreeSet<&'static str>, exit_cb: ExitCb, } impl Default for FeatureChecker { fn default() -> Self { Self { features: BTreeSet::new(), exit_cb: Box::new(exit), } } } impl FeatureChecker { #[inline(always)] pub fn check(&self, feature: &str) -> bool { self.features.contains(feature) } pub fn enable_feature(&mut self, feature: &'static str) { let inserted = self.features.insert(feature); assert!( inserted, "Trying to enable a feature that is already enabled: {feature}", ); } #[inline(always)] pub fn check_or_exit(&self, feature: &str, api_name: &str) { if !self.check(feature) { (self.exit_cb)(feature, api_name); } } pub fn set_exit_cb(&mut self, cb: ExitCb) { self.exit_cb = cb; } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/features/structs.rs
runtime/features/structs.rs
// Copyright 2018-2025 the Deno authors. MIT license. #[derive(Clone, Debug)] pub enum UnstableFeatureKind { Cli, Runtime, } #[derive(Debug)] #[allow(dead_code)] pub struct UnstableFeatureDefinition { pub name: &'static str, pub flag_name: &'static str, pub help_text: &'static str, pub show_in_help: bool, pub id: i32, pub kind: UnstableFeatureKind, }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/features/build.rs
runtime/features/build.rs
// Copyright 2018-2025 the Deno authors. MIT license. #![allow(clippy::disallowed_methods)] use std::path::Path; mod data; mod structs; fn main() { let crate_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); let mut js_list = String::from( "// Copyright 2018-2025 the Deno authors. MIT license. /** * Don't modify this file manually. * * This file is auto-generated by the build script, modify `data.rs` instead. */ export const unstableIds = { ", ); let mut rs_list = String::from( "// Copyright 2018-2025 the Deno authors. MIT license. /// Don't modify this file manually. /// /// This file is auto-generated by the build script, modify `data.rs` instead. use crate::structs::UnstableFeatureDefinition; use crate::structs::UnstableFeatureKind; pub static UNSTABLE_FEATURES: &[UnstableFeatureDefinition] = &[\n", ); let mut descriptions = data::FEATURE_DESCRIPTIONS.to_vec(); descriptions.sort_by_key(|desc| desc.name); for (id, feature) in descriptions.iter().enumerate() { let flag_name = format!("unstable-{}", feature.name); let feature_kind = match feature.kind { structs::UnstableFeatureKind::Cli => "UnstableFeatureKind::Cli", structs::UnstableFeatureKind::Runtime => "UnstableFeatureKind::Runtime", }; rs_list += &format!( r#" UnstableFeatureDefinition {{ name: "{}", flag_name: "{}", help_text: "{}", show_in_help: {}, id: {}, kind: {}, }}, "#, feature.name, flag_name, feature.help_text, feature.show_in_help, id, feature_kind ); if matches!(feature.kind, structs::UnstableFeatureKind::Runtime) { let camel = camel_case(feature.name); js_list += &format!(" {}: {},\n", camel, id); } } js_list += "};\n"; rs_list += "];\n"; let mut env_var_def = "pub struct UnstableEnvVarNames {\n".to_string(); let mut env_var_impl = "pub static UNSTABLE_ENV_VAR_NAMES: UnstableEnvVarNames = UnstableEnvVarNames {\n" .to_string(); for feature in &descriptions { let value = match feature.env_var { Some(v) => v, None => continue, }; let prop_name = feature.name.replace("-", "_"); env_var_def.push_str(&format!(" pub {}: &'static str,\n", prop_name)); env_var_impl.push_str(&format!(" {}: \"{}\",\n", prop_name, value)); } env_var_def.push_str("}\n"); env_var_impl.push_str("};\n"); rs_list.push_str(&env_var_def); rs_list.push_str(&env_var_impl); write_if_changed(&crate_dir.join("gen.js"), &js_list); write_if_changed(&crate_dir.join("gen.rs"), &rs_list); } fn write_if_changed(path: &Path, new_text: &str) { let current_text = std::fs::read_to_string(path).unwrap_or_default(); if current_text != new_text { std::fs::write(path, new_text).unwrap(); } } fn camel_case(name: &str) -> String { let mut output = String::new(); let mut upper = false; for c in name.chars() { if c == '-' { upper = true; } else if upper { upper = false; output.push(c.to_ascii_uppercase()); } else { output.push(c); } } output }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/features/data.rs
runtime/features/data.rs
// Copyright 2018-2025 the Deno authors. MIT license. // NOTE(bartlomieju): some fields are marked as never read, even though they are // actually used in the CLI. #![allow(dead_code)] use crate::structs::UnstableFeatureKind; #[derive(Clone, Debug)] pub struct UnstableFeatureDescription { pub name: &'static str, pub help_text: &'static str, // TODO(bartlomieju): is it needed? pub show_in_help: bool, pub kind: UnstableFeatureKind, pub env_var: Option<&'static str>, } pub static FEATURE_DESCRIPTIONS: &[UnstableFeatureDescription] = &[ UnstableFeatureDescription { name: "bare-node-builtins", help_text: "Enable unstable bare node builtins feature", show_in_help: true, kind: UnstableFeatureKind::Cli, env_var: Some("DENO_UNSTABLE_BARE_NODE_BUILTINS"), }, UnstableFeatureDescription { name: "broadcast-channel", help_text: "Enable unstable `BroadcastChannel` API", show_in_help: false, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "byonm", help_text: "", show_in_help: false, kind: UnstableFeatureKind::Cli, env_var: None, }, UnstableFeatureDescription { name: "cron", help_text: "Enable unstable `Deno.cron` API", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "detect-cjs", help_text: "Treats ambiguous .js, .jsx, .ts, .tsx files as CommonJS modules in more cases", show_in_help: true, kind: UnstableFeatureKind::Cli, env_var: None, }, UnstableFeatureDescription { name: "ffi", help_text: "Enable unstable FFI APIs", show_in_help: false, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "fs", help_text: "Enable unstable file system APIs", show_in_help: false, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "http", help_text: "Enable unstable HTTP APIs", show_in_help: false, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "kv", help_text: "Enable unstable KV APIs", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "lazy-dynamic-imports", help_text: "Lazily loads statically analyzable dynamic imports when not running with type checking. Warning: This may change the order of semver specifier resolution.", show_in_help: true, kind: UnstableFeatureKind::Cli, env_var: Some("DENO_UNSTABLE_LAZY_DYNAMIC_IMPORTS"), }, UnstableFeatureDescription { name: "lockfile-v5", help_text: "Enable unstable lockfile v5", show_in_help: true, kind: UnstableFeatureKind::Cli, env_var: Some("DENO_UNSTABLE_LOCKFILE_V5"), }, UnstableFeatureDescription { name: "net", help_text: "enable unstable net APIs", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "no-legacy-abort", help_text: "Enable abort signal in Deno.serve without legacy behavior. This will not abort the server when the request is handled successfully.", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "node-globals", help_text: "Prefer Node.js globals over Deno globals - currently this refers to `setTimeout` and `setInterval` APIs.", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "npm-lazy-caching", help_text: "Enable unstable lazy caching of npm dependencies, downloading them only as needed (disabled: all npm packages in package.json are installed on startup; enabled: only npm packages that are actually referenced in an import are installed", show_in_help: true, kind: UnstableFeatureKind::Cli, env_var: Some("DENO_UNSTABLE_NPM_LAZY_CACHING"), }, UnstableFeatureDescription { name: "otel", help_text: "Enable unstable OpenTelemetry features", show_in_help: false, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "process", help_text: "Enable unstable process APIs", show_in_help: false, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "raw-imports", help_text: "Enable unstable 'bytes' and 'text' imports.", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: Some("DENO_UNSTABLE_RAW_IMPORTS"), }, UnstableFeatureDescription { name: "sloppy-imports", help_text: "Enable unstable resolving of specifiers by extension probing, .js to .ts, and directory probing", show_in_help: true, kind: UnstableFeatureKind::Cli, env_var: Some("DENO_UNSTABLE_SLOPPY_IMPORTS"), }, UnstableFeatureDescription { name: "subdomain-wildcards", help_text: "Enable subdomain wildcards support for the `--allow-net` flag", show_in_help: false, kind: UnstableFeatureKind::Cli, env_var: Some("DENO_UNSTABLE_SUBDOMAIN_WILDCARDS"), }, UnstableFeatureDescription { name: "temporal", help_text: "Enable unstable Temporal API", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "unsafe-proto", help_text: "Enable unsafe __proto__ support. This is a security risk.", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "vsock", help_text: "Enable unstable VSOCK APIs", show_in_help: false, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "webgpu", help_text: "Enable unstable WebGPU APIs", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "worker-options", help_text: "Enable unstable Web Worker APIs", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "bundle", help_text: "Enable unstable bundle runtime API", show_in_help: true, kind: UnstableFeatureKind::Runtime, env_var: None, }, UnstableFeatureDescription { name: "tsgo", help_text: "Enable unstable TypeScript Go integration", show_in_help: true, kind: UnstableFeatureKind::Cli, env_var: Some("DENO_UNSTABLE_TSGO"), }, ];
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/ops/tty.rs
runtime/ops/tty.rs
// Copyright 2018-2025 the Deno authors. MIT license. #[cfg(unix)] use std::cell::RefCell; #[cfg(unix)] use std::collections::HashMap; use std::io::Error; #[cfg(windows)] use std::sync::Arc; use deno_core::OpState; #[cfg(unix)] use deno_core::ResourceId; use deno_core::op2; #[cfg(windows)] use deno_core::parking_lot::Mutex; use deno_error::JsErrorBox; use deno_error::JsErrorClass; use deno_error::builtin_classes::GENERIC_ERROR; #[cfg(windows)] use deno_io::WinTtyState; #[cfg(unix)] use nix::sys::termios; use rustyline::Cmd; use rustyline::Editor; use rustyline::KeyCode; use rustyline::KeyEvent; use rustyline::Modifiers; use rustyline::config::Configurer; use rustyline::error::ReadlineError; #[cfg(unix)] #[derive(Default, Clone)] struct TtyModeStore( std::rc::Rc<RefCell<HashMap<ResourceId, termios::Termios>>>, ); #[cfg(unix)] impl TtyModeStore { pub fn get(&self, id: ResourceId) -> Option<termios::Termios> { self.0.borrow().get(&id).map(ToOwned::to_owned) } pub fn take(&self, id: ResourceId) -> Option<termios::Termios> { self.0.borrow_mut().remove(&id) } pub fn set(&self, id: ResourceId, mode: termios::Termios) { self.0.borrow_mut().insert(id, mode); } } #[cfg(unix)] use deno_process::JsNixError; #[cfg(windows)] use winapi::shared::minwindef::DWORD; #[cfg(windows)] use winapi::um::wincon; deno_core::extension!( deno_tty, ops = [op_set_raw, op_console_size, op_read_line_prompt], state = |state| { #[cfg(unix)] state.put(TtyModeStore::default()); #[cfg(not(unix))] let _ = state; }, ); #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum TtyError { #[class(inherit)] #[error(transparent)] Resource( #[from] #[inherit] deno_core::error::ResourceError, ), #[class(inherit)] #[error("{0}")] Io( #[from] #[inherit] Error, ), #[cfg(unix)] #[class(inherit)] #[error(transparent)] Nix(#[inherit] JsNixError), #[class(inherit)] #[error(transparent)] Other(#[inherit] JsErrorBox), } // ref: <https://learn.microsoft.com/en-us/windows/console/setconsolemode> #[cfg(windows)] const COOKED_MODE: DWORD = // enable line-by-line input (returns input only after CR is read) wincon::ENABLE_LINE_INPUT // enables real-time character echo to console display (requires ENABLE_LINE_INPUT) | wincon::ENABLE_ECHO_INPUT // system handles CTRL-C (with ENABLE_LINE_INPUT, also handles BS, CR, and LF) and other control keys (when using `ReadFile` or `ReadConsole`) | wincon::ENABLE_PROCESSED_INPUT; #[cfg(windows)] fn mode_raw_input_on(original_mode: DWORD) -> DWORD { original_mode & !COOKED_MODE | wincon::ENABLE_VIRTUAL_TERMINAL_INPUT } #[cfg(windows)] fn mode_raw_input_off(original_mode: DWORD) -> DWORD { original_mode & !wincon::ENABLE_VIRTUAL_TERMINAL_INPUT | COOKED_MODE } #[op2(fast)] fn op_set_raw( state: &mut OpState, rid: u32, is_raw: bool, cbreak: bool, ) -> Result<(), TtyError> { let handle_or_fd = state.resource_table.get_fd(rid)?; // From https://github.com/kkawakam/rustyline/blob/master/src/tty/windows.rs // and https://github.com/kkawakam/rustyline/blob/master/src/tty/unix.rs // and https://github.com/crossterm-rs/crossterm/blob/e35d4d2c1cc4c919e36d242e014af75f6127ab50/src/terminal/sys/windows.rs // Copyright (c) 2015 Katsu Kawakami & Rustyline authors. MIT license. // Copyright (c) 2019 Timon. MIT license. #[cfg(windows)] { use deno_error::JsErrorBox; use winapi::shared::minwindef::FALSE; use winapi::um::consoleapi; let handle = handle_or_fd; if cbreak { return Err(TtyError::Other(JsErrorBox::not_supported())); } let mut original_mode: DWORD = 0; // SAFETY: winapi call if unsafe { consoleapi::GetConsoleMode(handle, &mut original_mode) } == FALSE { return Err(TtyError::Io(Error::last_os_error())); } let new_mode = if is_raw { mode_raw_input_on(original_mode) } else { mode_raw_input_off(original_mode) }; let stdin_state = state.borrow::<Arc<Mutex<WinTtyState>>>(); let mut stdin_state = stdin_state.lock(); if stdin_state.reading { let cvar = stdin_state.cvar.clone(); /* Trick to unblock an ongoing line-buffered read operation if not already pending. See https://github.com/libuv/libuv/pull/866 for prior art */ if original_mode & COOKED_MODE != 0 && !stdin_state.cancelled { // SAFETY: Write enter key event to force the console wait to return. let record = unsafe { let mut record: wincon::INPUT_RECORD = std::mem::zeroed(); record.EventType = wincon::KEY_EVENT; record.Event.KeyEvent_mut().wVirtualKeyCode = winapi::um::winuser::VK_RETURN as u16; record.Event.KeyEvent_mut().bKeyDown = 1; record.Event.KeyEvent_mut().wRepeatCount = 1; *record.Event.KeyEvent_mut().uChar.UnicodeChar_mut() = '\r' as u16; record.Event.KeyEvent_mut().dwControlKeyState = 0; record.Event.KeyEvent_mut().wVirtualScanCode = winapi::um::winuser::MapVirtualKeyW( winapi::um::winuser::VK_RETURN as u32, winapi::um::winuser::MAPVK_VK_TO_VSC, ) as u16; record }; stdin_state.cancelled = true; // SAFETY: winapi call to open conout$ and save screen state. let active_screen_buffer = unsafe { /* Save screen state before sending the VK_RETURN event */ let handle = winapi::um::fileapi::CreateFileW( "conout$" .encode_utf16() .chain(Some(0)) .collect::<Vec<_>>() .as_ptr(), winapi::um::winnt::GENERIC_READ | winapi::um::winnt::GENERIC_WRITE, winapi::um::winnt::FILE_SHARE_READ | winapi::um::winnt::FILE_SHARE_WRITE, std::ptr::null_mut(), winapi::um::fileapi::OPEN_EXISTING, 0, std::ptr::null_mut(), ); let mut active_screen_buffer = std::mem::zeroed(); winapi::um::wincon::GetConsoleScreenBufferInfo( handle, &mut active_screen_buffer, ); winapi::um::handleapi::CloseHandle(handle); active_screen_buffer }; stdin_state.screen_buffer_info = Some(active_screen_buffer); // SAFETY: winapi call to write the VK_RETURN event. if unsafe { winapi::um::wincon::WriteConsoleInputW(handle, &record, 1, &mut 0) } == FALSE { return Err(TtyError::Io(Error::last_os_error())); } /* Wait for read thread to acknowledge the cancellation to ensure that nothing interferes with the screen state. NOTE: `wait_while` automatically unlocks stdin_state */ cvar.wait_while(&mut stdin_state, |state: &mut WinTtyState| { state.cancelled }); } } // SAFETY: winapi call if unsafe { consoleapi::SetConsoleMode(handle, new_mode) } == FALSE { return Err(TtyError::Io(Error::last_os_error())); } Ok(()) } #[cfg(unix)] { fn prepare_stdio() { // SAFETY: Save current state of stdio and restore it when we exit. unsafe { use libc::atexit; use libc::tcgetattr; use libc::tcsetattr; use libc::termios; use once_cell::sync::OnceCell; // Only save original state once. static ORIG_TERMIOS: OnceCell<Option<termios>> = OnceCell::new(); ORIG_TERMIOS.get_or_init(|| { let mut termios = std::mem::zeroed::<termios>(); if tcgetattr(libc::STDIN_FILENO, &mut termios) == 0 { extern "C" fn reset_stdio() { // SAFETY: Reset the stdio state. unsafe { tcsetattr( libc::STDIN_FILENO, 0, &ORIG_TERMIOS.get().unwrap().unwrap(), ) }; } atexit(reset_stdio); return Some(termios); } None }); } } prepare_stdio(); let tty_mode_store = state.borrow::<TtyModeStore>().clone(); let previous_mode = tty_mode_store.get(rid); // SAFETY: Nix crate requires value to implement the AsFd trait let raw_fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(handle_or_fd) }; if is_raw { let mut raw = match previous_mode { Some(mode) => mode, None => { // Save original mode. let original_mode = termios::tcgetattr(raw_fd) .map_err(|e| TtyError::Nix(JsNixError(e)))?; tty_mode_store.set(rid, original_mode.clone()); original_mode } }; raw.input_flags &= !(termios::InputFlags::BRKINT | termios::InputFlags::ICRNL | termios::InputFlags::INPCK | termios::InputFlags::ISTRIP | termios::InputFlags::IXON); raw.control_flags |= termios::ControlFlags::CS8; raw.local_flags &= !(termios::LocalFlags::ECHO | termios::LocalFlags::ICANON | termios::LocalFlags::IEXTEN); if !cbreak { raw.local_flags &= !(termios::LocalFlags::ISIG); } raw.control_chars[termios::SpecialCharacterIndices::VMIN as usize] = 1; raw.control_chars[termios::SpecialCharacterIndices::VTIME as usize] = 0; termios::tcsetattr(raw_fd, termios::SetArg::TCSADRAIN, &raw) .map_err(|e| TtyError::Nix(JsNixError(e)))?; } else { // Try restore saved mode. if let Some(mode) = tty_mode_store.take(rid) { termios::tcsetattr(raw_fd, termios::SetArg::TCSADRAIN, &mode) .map_err(|e| TtyError::Nix(JsNixError(e)))?; } } Ok(()) } } #[op2(fast)] fn op_console_size( state: &mut OpState, #[buffer] result: &mut [u32], ) -> Result<(), TtyError> { fn check_console_size( state: &mut OpState, result: &mut [u32], rid: u32, ) -> Result<(), TtyError> { let fd = state.resource_table.get_fd(rid)?; let size = console_size_from_fd(fd)?; result[0] = size.cols; result[1] = size.rows; Ok(()) } let mut last_result = Ok(()); // Since stdio might be piped we try to get the size of the console for all // of them and return the first one that succeeds. for rid in [0, 1, 2] { last_result = check_console_size(state, result, rid); if last_result.is_ok() { return last_result; } } last_result } #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub struct ConsoleSize { pub cols: u32, pub rows: u32, } pub fn console_size( std_file: &std::fs::File, ) -> Result<ConsoleSize, std::io::Error> { #[cfg(windows)] { use std::os::windows::io::AsRawHandle; let handle = std_file.as_raw_handle(); console_size_from_fd(handle) } #[cfg(unix)] { use std::os::unix::io::AsRawFd; let fd = std_file.as_raw_fd(); console_size_from_fd(fd) } } #[cfg(windows)] fn console_size_from_fd( handle: std::os::windows::io::RawHandle, ) -> Result<ConsoleSize, std::io::Error> { // SAFETY: winapi calls unsafe { let mut bufinfo: winapi::um::wincon::CONSOLE_SCREEN_BUFFER_INFO = std::mem::zeroed(); if winapi::um::wincon::GetConsoleScreenBufferInfo(handle, &mut bufinfo) == 0 { return Err(Error::last_os_error()); } // calculate the size of the visible window // * use over/under-flow protections b/c MSDN docs only imply that srWindow components are all non-negative // * ref: <https://docs.microsoft.com/en-us/windows/console/console-screen-buffer-info-str> @@ <https://archive.is/sfjnm> let cols = std::cmp::max( bufinfo.srWindow.Right as i32 - bufinfo.srWindow.Left as i32 + 1, 0, ) as u32; let rows = std::cmp::max( bufinfo.srWindow.Bottom as i32 - bufinfo.srWindow.Top as i32 + 1, 0, ) as u32; Ok(ConsoleSize { cols, rows }) } } #[cfg(not(windows))] fn console_size_from_fd( fd: std::os::unix::prelude::RawFd, ) -> Result<ConsoleSize, std::io::Error> { // SAFETY: libc calls unsafe { let mut size: libc::winsize = std::mem::zeroed(); if libc::ioctl(fd, libc::TIOCGWINSZ, &mut size as *mut _) != 0 { return Err(Error::last_os_error()); } Ok(ConsoleSize { cols: size.ws_col as u32, rows: size.ws_row as u32, }) } } #[cfg(all(test, windows))] mod tests { #[test] fn test_winos_raw_mode_transitions() { use crate::ops::tty::mode_raw_input_off; use crate::ops::tty::mode_raw_input_on; let known_off_modes = [0xf7 /* Win10/CMD */, 0x1f7 /* Win10/WinTerm */]; let known_on_modes = [0x2f0 /* Win10/CMD */, 0x3f0 /* Win10/WinTerm */]; // assert known transitions assert_eq!(known_on_modes[0], mode_raw_input_on(known_off_modes[0])); assert_eq!(known_on_modes[1], mode_raw_input_on(known_off_modes[1])); // assert ON-OFF round-trip is neutral assert_eq!( known_off_modes[0], mode_raw_input_off(mode_raw_input_on(known_off_modes[0])) ); assert_eq!( known_off_modes[1], mode_raw_input_off(mode_raw_input_on(known_off_modes[1])) ); } } deno_error::js_error_wrapper!(ReadlineError, JsReadlineError, |err| { match err { ReadlineError::Io(e) => e.get_class(), ReadlineError::Eof => GENERIC_ERROR.into(), ReadlineError::Interrupted => GENERIC_ERROR.into(), #[cfg(unix)] ReadlineError::Errno(e) => JsNixError(*e).get_class(), ReadlineError::WindowResized => GENERIC_ERROR.into(), #[cfg(windows)] ReadlineError::Decode(_) => GENERIC_ERROR.into(), #[cfg(windows)] ReadlineError::SystemError(_) => GENERIC_ERROR.into(), _ => GENERIC_ERROR.into(), } }); #[op2] #[string] pub fn op_read_line_prompt( #[string] prompt_text: &str, #[string] default_value: &str, ) -> Result<Option<String>, JsReadlineError> { let mut editor = Editor::<(), rustyline::history::DefaultHistory>::new() .expect("Failed to create editor."); editor.set_keyseq_timeout(1); editor .bind_sequence(KeyEvent(KeyCode::Esc, Modifiers::empty()), Cmd::Interrupt); let read_result = editor.readline_with_initial(prompt_text, (default_value, "")); match read_result { Ok(line) => Ok(Some(line)), Err(ReadlineError::Interrupted) => { // SAFETY: Disable raw mode and raise SIGINT. unsafe { libc::raise(libc::SIGINT); } Ok(None) } Err(ReadlineError::Eof) => Ok(None), Err(err) => Err(JsReadlineError(err)), } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/ops/permissions.rs
runtime/ops/permissions.rs
// Copyright 2018-2025 the Deno authors. MIT license. use ::deno_permissions::PermissionState; use ::deno_permissions::PermissionsContainer; use deno_core::OpState; use deno_core::op2; use serde::Deserialize; use serde::Serialize; deno_core::extension!( deno_permissions, ops = [ op_query_permission, op_revoke_permission, op_request_permission, ], ); #[derive(Deserialize)] pub struct PermissionArgs { name: String, path: Option<String>, host: Option<String>, variable: Option<String>, kind: Option<String>, command: Option<String>, } #[derive(Serialize)] pub struct PermissionStatus { state: &'static str, partial: bool, } impl From<PermissionState> for PermissionStatus { fn from(state: PermissionState) -> Self { PermissionStatus { state: match state { PermissionState::Granted | PermissionState::GrantedPartial => "granted", PermissionState::Ignored | PermissionState::DeniedPartial | PermissionState::Denied => "denied", PermissionState::Prompt => "prompt", }, partial: state == PermissionState::GrantedPartial, } } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum PermissionError { #[class(reference)] #[error("No such permission name: {0}")] InvalidPermissionName(String), #[class(inherit)] #[error("{0}")] PathResolve(#[from] ::deno_permissions::PathResolveError), #[class(uri)] #[error("{0}")] NetDescriptorParse(#[from] ::deno_permissions::NetDescriptorParseError), #[class(inherit)] #[error("{0}")] SysDescriptorParse(#[from] ::deno_permissions::SysDescriptorParseError), #[class(inherit)] #[error("{0}")] RunDescriptorParse(#[from] ::deno_permissions::RunDescriptorParseError), } #[op2] #[serde] pub fn op_query_permission( state: &mut OpState, #[serde] args: PermissionArgs, ) -> Result<PermissionStatus, PermissionError> { let permissions = state.borrow::<PermissionsContainer>(); let perm = match args.name.as_ref() { "read" => permissions.query_read(args.path.as_deref())?, "write" => permissions.query_write(args.path.as_deref())?, "net" => permissions.query_net(args.host.as_deref())?, "env" => permissions.query_env(args.variable.as_deref()), "sys" => permissions.query_sys(args.kind.as_deref())?, "run" => permissions.query_run(args.command.as_deref())?, "ffi" => permissions.query_ffi(args.path.as_deref())?, "import" => permissions.query_import(args.host.as_deref())?, _ => return Err(PermissionError::InvalidPermissionName(args.name)), }; Ok(PermissionStatus::from(perm)) } #[op2] #[serde] pub fn op_revoke_permission( state: &mut OpState, #[serde] args: PermissionArgs, ) -> Result<PermissionStatus, PermissionError> { let permissions = state.borrow::<PermissionsContainer>(); let perm = match args.name.as_ref() { "read" => permissions.revoke_read(args.path.as_deref())?, "write" => permissions.revoke_write(args.path.as_deref())?, "net" => permissions.revoke_net(args.host.as_deref())?, "env" => permissions.revoke_env(args.variable.as_deref()), "sys" => permissions.revoke_sys(args.kind.as_deref())?, "run" => permissions.revoke_run(args.command.as_deref())?, "ffi" => permissions.revoke_ffi(args.path.as_deref())?, "import" => permissions.revoke_import(args.host.as_deref())?, _ => return Err(PermissionError::InvalidPermissionName(args.name)), }; Ok(PermissionStatus::from(perm)) } #[op2(stack_trace)] #[serde] pub fn op_request_permission( state: &mut OpState, #[serde] args: PermissionArgs, ) -> Result<PermissionStatus, PermissionError> { let permissions = state.borrow::<PermissionsContainer>(); let perm = match args.name.as_ref() { "read" => permissions.request_read(args.path.as_deref())?, "write" => permissions.request_write(args.path.as_deref())?, "net" => permissions.request_net(args.host.as_deref())?, "env" => permissions.request_env(args.variable.as_deref()), "sys" => permissions.request_sys(args.kind.as_deref())?, "run" => permissions.request_run(args.command.as_deref())?, "ffi" => permissions.request_ffi(args.path.as_deref())?, "import" => permissions.request_import(args.host.as_deref())?, _ => return Err(PermissionError::InvalidPermissionName(args.name)), }; Ok(PermissionStatus::from(perm)) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/ops/http.rs
runtime/ops/http.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::rc::Rc; use deno_core::OpState; use deno_core::ResourceId; use deno_core::error::ResourceError; use deno_core::op2; use deno_http::http_create_conn_resource; use deno_net::io::TcpStreamResource; use deno_net::ops_tls::TlsStreamResource; pub const UNSTABLE_FEATURE_NAME: &str = "http"; deno_core::extension!(deno_http_runtime, ops = [op_http_start],); #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum HttpStartError { #[class("Busy")] #[error("TCP stream is currently in use")] TcpStreamInUse, #[class("Busy")] #[error("TLS stream is currently in use")] TlsStreamInUse, #[class("Busy")] #[error("Unix socket is currently in use")] UnixSocketInUse, #[class(generic)] #[error(transparent)] ReuniteTcp(#[from] tokio::net::tcp::ReuniteError), #[cfg(unix)] #[class(generic)] #[error(transparent)] ReuniteUnix(#[from] tokio::net::unix::ReuniteError), #[class(inherit)] #[error("{0}")] Io( #[from] #[inherit] std::io::Error, ), #[class(inherit)] #[error(transparent)] Resource(#[inherit] ResourceError), } #[op2(fast)] #[smi] fn op_http_start( state: &mut OpState, #[smi] tcp_stream_rid: ResourceId, ) -> Result<ResourceId, HttpStartError> { if let Ok(resource_rc) = state .resource_table .take::<TcpStreamResource>(tcp_stream_rid) { // This TCP connection might be used somewhere else. If it's the case, we cannot proceed with the // process of starting a HTTP server on top of this TCP connection, so we just return a Busy error. // See also: https://github.com/denoland/deno/pull/16242 let resource = Rc::try_unwrap(resource_rc) .map_err(|_| HttpStartError::TcpStreamInUse)?; let (read_half, write_half) = resource.into_inner(); let tcp_stream = read_half.reunite(write_half)?; let addr = tcp_stream.local_addr()?; return Ok(http_create_conn_resource(state, tcp_stream, addr, "http")); } if let Ok(resource_rc) = state .resource_table .take::<TlsStreamResource>(tcp_stream_rid) { // This TLS connection might be used somewhere else. If it's the case, we cannot proceed with the // process of starting a HTTP server on top of this TLS connection, so we just return a Busy error. // See also: https://github.com/denoland/deno/pull/16242 let resource = Rc::try_unwrap(resource_rc) .map_err(|_| HttpStartError::TlsStreamInUse)?; let tls_stream = resource.into_tls_stream(); let addr = tls_stream.local_addr()?; return Ok(http_create_conn_resource(state, tls_stream, addr, "https")); } #[cfg(unix)] if let Ok(resource_rc) = state .resource_table .take::<deno_net::io::UnixStreamResource>(tcp_stream_rid) { // This UNIX socket might be used somewhere else. If it's the case, we cannot proceed with the // process of starting a HTTP server on top of this UNIX socket, so we just return a Busy error. // See also: https://github.com/denoland/deno/pull/16242 let resource = Rc::try_unwrap(resource_rc) .map_err(|_| HttpStartError::UnixSocketInUse)?; let (read_half, write_half) = resource.into_inner(); let unix_stream = read_half.reunite(write_half)?; let addr = unix_stream.local_addr()?; return Ok(http_create_conn_resource( state, unix_stream, addr, "http+unix", )); } Err(HttpStartError::Resource(ResourceError::BadResourceId)) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/ops/runtime.rs
runtime/ops/runtime.rs
// Copyright 2018-2025 the Deno authors. MIT license. use deno_core::ModuleSpecifier; use deno_core::OpState; use deno_core::op2; deno_core::extension!( deno_runtime, ops = [op_main_module, op_ppid, op_internal_log], options = { main_module: ModuleSpecifier }, state = |state, options| { state.put::<ModuleSpecifier>(options.main_module); }, ); #[op2] #[string] fn op_main_module(state: &mut OpState) -> String { let main_url = state.borrow::<ModuleSpecifier>(); main_url.to_string() } /// This is an op instead of being done at initialization time because /// it's expensive to retrieve the ppid on Windows. #[op2(fast)] #[number] pub fn op_ppid() -> i64 { #[cfg(windows)] { // Adopted from rustup: // https://github.com/rust-lang/rustup/blob/1.21.1/src/cli/self_update.rs#L1036 // Copyright Diggory Blake, the Mozilla Corporation, and rustup contributors. // Licensed under either of // - Apache License, Version 2.0 // - MIT license use std::mem; use winapi::shared::minwindef::DWORD; use winapi::um::handleapi::CloseHandle; use winapi::um::handleapi::INVALID_HANDLE_VALUE; use winapi::um::processthreadsapi::GetCurrentProcessId; use winapi::um::tlhelp32::CreateToolhelp32Snapshot; use winapi::um::tlhelp32::PROCESSENTRY32; use winapi::um::tlhelp32::Process32First; use winapi::um::tlhelp32::Process32Next; use winapi::um::tlhelp32::TH32CS_SNAPPROCESS; // SAFETY: winapi calls unsafe { // Take a snapshot of system processes, one of which is ours // and contains our parent's pid let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if snapshot == INVALID_HANDLE_VALUE { return -1; } let mut entry: PROCESSENTRY32 = mem::zeroed(); entry.dwSize = mem::size_of::<PROCESSENTRY32>() as DWORD; // Iterate over system processes looking for ours let success = Process32First(snapshot, &mut entry); if success == 0 { CloseHandle(snapshot); return -1; } let this_pid = GetCurrentProcessId(); while entry.th32ProcessID != this_pid { let success = Process32Next(snapshot, &mut entry); if success == 0 { CloseHandle(snapshot); return -1; } } CloseHandle(snapshot); // FIXME: Using the process ID exposes a race condition // wherein the parent process already exited and the OS // reassigned its ID. let parent_id = entry.th32ParentProcessID; parent_id.into() } } #[cfg(not(windows))] { use std::os::unix::process::parent_id; parent_id().into() } } #[allow(clippy::match_single_binding)] // needed for temporary lifetime #[op2(fast)] fn op_internal_log( #[string] url: &str, #[smi] level: u32, #[string] message: &str, ) { let level = match level { 1 => log::Level::Error, 2 => log::Level::Warn, 3 => log::Level::Info, 4 => log::Level::Debug, 5 => log::Level::Trace, _ => unreachable!(), }; let target = url.replace('/', "::"); match format_args!("{message}") { args => { let record = log::Record::builder() .file(Some(url)) .module_path(Some(url)) .target(&target) .level(level) .args(args) .build(); log::logger().log(&record); } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/ops/mod.rs
runtime/ops/mod.rs
// Copyright 2018-2025 the Deno authors. MIT license. pub mod bootstrap; pub mod fs_events; pub mod http; pub mod permissions; pub mod runtime; pub mod tty; pub mod web_worker; pub mod worker_host; use std::sync::Arc; use deno_core::OpState; use deno_features::FeatureChecker; /// Helper for checking unstable features. Used for sync ops. pub fn check_unstable(state: &OpState, feature: &str, api_name: &str) { state .borrow::<Arc<FeatureChecker>>() .check_or_exit(feature, api_name); } pub struct TestingFeaturesEnabled(pub bool);
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/ops/worker_host.rs
runtime/ops/worker_host.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; use deno_core::CancelFuture; use deno_core::CancelHandle; use deno_core::ModuleSpecifier; use deno_core::OpState; use deno_core::op2; use deno_core::serde::Deserialize; use deno_permissions::ChildPermissionsArg; use deno_permissions::PermissionsContainer; use deno_web::JsMessageData; use deno_web::MessagePortError; use deno_web::deserialize_js_transferables; use log::debug; use crate::ops::TestingFeaturesEnabled; use crate::tokio_util::create_and_run_current_thread; use crate::web_worker::SendableWebWorkerHandle; use crate::web_worker::WebWorker; use crate::web_worker::WebWorkerHandle; use crate::web_worker::WorkerControlEvent; use crate::web_worker::WorkerId; use crate::web_worker::WorkerMetadata; use crate::web_worker::WorkerThreadType; use crate::web_worker::run_web_worker; use crate::worker::FormatJsErrorFn; pub const UNSTABLE_FEATURE_NAME: &str = "worker-options"; pub struct CreateWebWorkerArgs { pub name: String, pub worker_id: WorkerId, pub parent_permissions: PermissionsContainer, pub permissions: PermissionsContainer, pub main_module: ModuleSpecifier, pub worker_type: WorkerThreadType, pub close_on_idle: bool, pub maybe_worker_metadata: Option<WorkerMetadata>, } pub type CreateWebWorkerCb = dyn Fn(CreateWebWorkerArgs) -> (WebWorker, SendableWebWorkerHandle) + Sync + Send; /// A holder for callback that is used to create a new /// WebWorker. It's a struct instead of a type alias /// because `GothamState` used in `OpState` overrides /// value if type aliases have the same underlying type #[derive(Clone)] struct CreateWebWorkerCbHolder(Arc<CreateWebWorkerCb>); #[derive(Clone)] struct FormatJsErrorFnHolder(Option<Arc<FormatJsErrorFn>>); pub struct WorkerThread { worker_handle: WebWorkerHandle, cancel_handle: Rc<CancelHandle>, // A WorkerThread that hasn't been explicitly terminated can only be removed // from the WorkersTable once close messages have been received for both the // control and message channels. See `close_channel`. ctrl_closed: bool, message_closed: bool, } impl WorkerThread { fn terminate(self) { // Cancel recv ops when terminating the worker, so they don't show up as // pending ops. self.cancel_handle.cancel(); } } impl Drop for WorkerThread { fn drop(&mut self) { self.worker_handle.clone().terminate(); } } pub type WorkersTable = HashMap<WorkerId, WorkerThread>; deno_core::extension!( deno_worker_host, ops = [ op_create_worker, op_host_terminate_worker, op_host_post_message, op_host_recv_ctrl, op_host_recv_message, ], options = { create_web_worker_cb: Arc<CreateWebWorkerCb>, format_js_error_fn: Option<Arc<FormatJsErrorFn>>, }, state = |state, options| { state.put::<WorkersTable>(WorkersTable::default()); let create_web_worker_cb_holder = CreateWebWorkerCbHolder(options.create_web_worker_cb); state.put::<CreateWebWorkerCbHolder>(create_web_worker_cb_holder); let format_js_error_fn_holder = FormatJsErrorFnHolder(options.format_js_error_fn); state.put::<FormatJsErrorFnHolder>(format_js_error_fn_holder); }, ); #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct CreateWorkerArgs { has_source_code: bool, name: Option<String>, permissions: Option<ChildPermissionsArg>, source_code: String, specifier: String, worker_type: WorkerThreadType, close_on_idle: bool, } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum CreateWorkerError { #[class("DOMExceptionNotSupportedError")] #[error("Classic workers are not supported.")] ClassicWorkers, #[class(inherit)] #[error(transparent)] Permission(deno_permissions::ChildPermissionError), #[class(inherit)] #[error(transparent)] ModuleResolution(#[from] deno_core::ModuleResolutionError), #[class(inherit)] #[error(transparent)] MessagePort(#[from] MessagePortError), #[class(inherit)] #[error("{0}")] Io(#[from] std::io::Error), } /// Create worker as the host #[op2(stack_trace)] #[serde] fn op_create_worker( state: &mut OpState, #[serde] args: CreateWorkerArgs, #[serde] maybe_worker_metadata: Option<JsMessageData>, ) -> Result<WorkerId, CreateWorkerError> { let specifier = args.specifier.clone(); let maybe_source_code = if args.has_source_code { Some(args.source_code.clone()) } else { None }; let args_name = args.name; let worker_type = args.worker_type; if let WorkerThreadType::Classic = worker_type && let TestingFeaturesEnabled(false) = state.borrow() { return Err(CreateWorkerError::ClassicWorkers); } if args.permissions.is_some() { super::check_unstable( state, UNSTABLE_FEATURE_NAME, "Worker.deno.permissions", ); } let parent_permissions = state.borrow_mut::<PermissionsContainer>(); let worker_permissions = if let Some(child_permissions_arg) = args.permissions { parent_permissions .create_child_permissions(child_permissions_arg) .map_err(CreateWorkerError::Permission)? } else { parent_permissions.clone() }; let parent_permissions = parent_permissions.clone(); let create_web_worker_cb = state.borrow::<CreateWebWorkerCbHolder>().clone(); let format_js_error_fn = state.borrow::<FormatJsErrorFnHolder>().clone(); let worker_id = WorkerId::new(); let module_specifier = deno_core::resolve_url(&specifier)?; let worker_name = args_name.unwrap_or_default(); let (handle_sender, handle_receiver) = std::sync::mpsc::sync_channel::<SendableWebWorkerHandle>(1); // Setup new thread let thread_builder = std::thread::Builder::new().name(format!("{worker_id}")); let maybe_worker_metadata = if let Some(data) = maybe_worker_metadata { let transferables = deserialize_js_transferables(state, data.transferables)?; Some(WorkerMetadata { buffer: data.data, transferables, }) } else { None }; // Spawn it thread_builder.spawn(move || { // Any error inside this block is terminal: // - JS worker is useless - meaning it throws an exception and can't do anything else, // all action done upon it should be noops // - newly spawned thread exits let fut = async move { let (worker, external_handle) = (create_web_worker_cb.0)(CreateWebWorkerArgs { name: worker_name, worker_id, parent_permissions, permissions: worker_permissions, main_module: module_specifier.clone(), worker_type, close_on_idle: args.close_on_idle, maybe_worker_metadata, }); // Send thread safe handle from newly created worker to host thread handle_sender.send(external_handle).unwrap(); drop(handle_sender); // At this point the only method of communication with host // is using `worker.internal_channels`. // // Host can already push messages and interact with worker. run_web_worker( worker, module_specifier, maybe_source_code, format_js_error_fn.0, ) .await }; create_and_run_current_thread(fut) })?; // Receive WebWorkerHandle from newly created worker let worker_handle = handle_receiver.recv().unwrap(); let worker_thread = WorkerThread { worker_handle: worker_handle.into(), cancel_handle: CancelHandle::new_rc(), ctrl_closed: false, message_closed: false, }; // At this point all interactions with worker happen using thread // safe handler returned from previous function calls state .borrow_mut::<WorkersTable>() .insert(worker_id, worker_thread); Ok(worker_id) } #[op2] fn op_host_terminate_worker(state: &mut OpState, #[serde] id: WorkerId) { match state.borrow_mut::<WorkersTable>().remove(&id) { Some(worker_thread) => { worker_thread.terminate(); } _ => { debug!("tried to terminate non-existent worker {}", id); } } } enum WorkerChannel { Ctrl, Messages, } /// Close a worker's channel. If this results in both of a worker's channels /// being closed, the worker will be removed from the workers table. fn close_channel( state: Rc<RefCell<OpState>>, id: WorkerId, channel: WorkerChannel, ) { use std::collections::hash_map::Entry; let mut s = state.borrow_mut(); let workers = s.borrow_mut::<WorkersTable>(); // `Worker.terminate()` might have been called already, meaning that we won't // find the worker in the table - in that case ignore. if let Entry::Occupied(mut entry) = workers.entry(id) { let terminate = { let worker_thread = entry.get_mut(); match channel { WorkerChannel::Ctrl => { worker_thread.ctrl_closed = true; worker_thread.message_closed } WorkerChannel::Messages => { worker_thread.message_closed = true; worker_thread.ctrl_closed } } }; if terminate { entry.remove().terminate(); } } } /// Get control event from guest worker as host #[op2(async)] #[serde] async fn op_host_recv_ctrl( state: Rc<RefCell<OpState>>, #[serde] id: WorkerId, ) -> WorkerControlEvent { let (worker_handle, cancel_handle) = { let state = state.borrow(); let workers_table = state.borrow::<WorkersTable>(); let maybe_handle = workers_table.get(&id); if let Some(handle) = maybe_handle { (handle.worker_handle.clone(), handle.cancel_handle.clone()) } else { // If handle was not found it means worker has already shutdown return WorkerControlEvent::Close; } }; let maybe_event = worker_handle .get_control_event() .or_cancel(cancel_handle) .await; match maybe_event { Ok(Some(event)) => { // Terminal error means that worker should be removed from worker table. if let WorkerControlEvent::TerminalError(_) = &event { close_channel(state, id, WorkerChannel::Ctrl); } event } Ok(None) => { // If there was no event from worker it means it has already been closed. close_channel(state, id, WorkerChannel::Ctrl); WorkerControlEvent::Close } Err(_) => { // The worker was terminated. WorkerControlEvent::Close } } } #[op2(async)] #[serde] async fn op_host_recv_message( state: Rc<RefCell<OpState>>, #[serde] id: WorkerId, ) -> Result<Option<JsMessageData>, MessagePortError> { let (worker_handle, cancel_handle) = { let s = state.borrow(); let workers_table = s.borrow::<WorkersTable>(); let maybe_handle = workers_table.get(&id); if let Some(handle) = maybe_handle { (handle.worker_handle.clone(), handle.cancel_handle.clone()) } else { // If handle was not found it means worker has already shutdown return Ok(None); } }; let ret = worker_handle .port .recv(state.clone()) .or_cancel(cancel_handle) .await; match ret { Ok(Ok(ret)) => { if ret.is_none() { close_channel(state, id, WorkerChannel::Messages); } Ok(ret) } Ok(Err(err)) => Err(err), Err(_) => { // The worker was terminated. Ok(None) } } } /// Post message to guest worker as host #[op2] fn op_host_post_message( state: &mut OpState, #[serde] id: WorkerId, #[serde] data: JsMessageData, ) -> Result<(), MessagePortError> { if let Some(worker_thread) = state.borrow::<WorkersTable>().get(&id) { debug!("post message to worker {}", id); let worker_handle = worker_thread.worker_handle.clone(); worker_handle.port.send(state, data)?; } else { debug!("tried to post message to non-existent worker {}", id); } Ok(()) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/ops/bootstrap.rs
runtime/ops/bootstrap.rs
// Copyright 2018-2025 the Deno authors. MIT license. use deno_core::OpState; use deno_core::op2; use deno_terminal::colors::ColorLevel; use serde::Serialize; use crate::BootstrapOptions; deno_core::extension!( deno_bootstrap, ops = [ op_bootstrap_args, op_bootstrap_pid, op_bootstrap_numcpus, op_bootstrap_user_agent, op_bootstrap_language, op_bootstrap_log_level, op_bootstrap_color_depth, op_bootstrap_no_color, op_bootstrap_stdout_no_color, op_bootstrap_stderr_no_color, op_bootstrap_unstable_args, op_bootstrap_is_from_unconfigured_runtime, op_snapshot_options, ], options = { snapshot_options: Option<SnapshotOptions>, is_from_unconfigured_runtime: bool, }, state = |state, options| { if let Some(snapshot_options) = options.snapshot_options { state.put::<SnapshotOptions>(snapshot_options); } state.put(IsFromUnconfiguredRuntime(options.is_from_unconfigured_runtime)); }, ); #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct SnapshotOptions { pub ts_version: String, pub v8_version: &'static str, pub target: String, } struct IsFromUnconfiguredRuntime(bool); impl Default for SnapshotOptions { fn default() -> Self { let arch = std::env::consts::ARCH; let platform = std::env::consts::OS; let target = match platform { "macos" => format!("{}-apple-darwin", arch), "linux" => format!("{}-unknown-linux-gnu", arch), "windows" => format!("{}-pc-windows-msvc", arch), rest => format!("{}-{}", arch, rest), }; Self { ts_version: "n/a".to_owned(), v8_version: deno_core::v8::VERSION_STRING, target, } } } // Note: Called at snapshot time, op perf is not a concern. #[op2] #[serde] pub fn op_snapshot_options(state: &mut OpState) -> SnapshotOptions { #[cfg(feature = "hmr")] { state.try_take::<SnapshotOptions>().unwrap_or_default() } #[cfg(not(feature = "hmr"))] { state.take::<SnapshotOptions>() } } #[op2] #[serde] pub fn op_bootstrap_args(state: &mut OpState) -> Vec<String> { state.borrow::<BootstrapOptions>().args.clone() } #[op2(fast)] #[smi] pub fn op_bootstrap_pid() -> u32 { std::process::id() } #[op2(fast)] #[smi] pub fn op_bootstrap_numcpus(state: &mut OpState) -> u32 { state.borrow::<BootstrapOptions>().cpu_count as u32 } #[op2] #[string] pub fn op_bootstrap_user_agent(state: &mut OpState) -> String { state.borrow::<BootstrapOptions>().user_agent.clone() } #[op2] #[serde] pub fn op_bootstrap_unstable_args(state: &mut OpState) -> Vec<String> { let options = state.borrow::<BootstrapOptions>(); let mut flags = Vec::with_capacity(options.unstable_features.len()); for unstable_feature in &options.unstable_features { if let Some(granular_flag) = deno_features::UNSTABLE_FEATURES.get((*unstable_feature) as usize) { flags.push(format!("--unstable-{}", granular_flag.name)); } } flags } #[op2] #[string] pub fn op_bootstrap_language(state: &mut OpState) -> String { state.borrow::<BootstrapOptions>().locale.clone() } #[op2(fast)] #[smi] pub fn op_bootstrap_log_level(state: &mut OpState) -> i32 { state.borrow::<BootstrapOptions>().log_level as i32 } #[op2(fast)] pub fn op_bootstrap_color_depth(state: &mut OpState) -> i32 { let options = state.borrow::<BootstrapOptions>(); match options.color_level { ColorLevel::None => 1, ColorLevel::Ansi => 4, ColorLevel::Ansi256 => 8, ColorLevel::TrueColor => 24, } } #[op2(fast)] pub fn op_bootstrap_no_color(_state: &mut OpState) -> bool { !deno_terminal::colors::use_color() } #[op2(fast)] pub fn op_bootstrap_stdout_no_color(_state: &mut OpState) -> bool { if deno_terminal::colors::force_color() { return false; } !deno_terminal::is_stdout_tty() || !deno_terminal::colors::use_color() } #[op2(fast)] pub fn op_bootstrap_stderr_no_color(_state: &mut OpState) -> bool { if deno_terminal::colors::force_color() { return false; } !deno_terminal::is_stderr_tty() || !deno_terminal::colors::use_color() } #[op2(fast)] pub fn op_bootstrap_is_from_unconfigured_runtime(state: &mut OpState) -> bool { state.borrow::<IsFromUnconfiguredRuntime>().0 }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/ops/fs_events.rs
runtime/ops/fs_events.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::convert::From; use std::path::Path; use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; use deno_core::AsyncRefCell; use deno_core::CancelFuture; use deno_core::CancelHandle; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::op2; use deno_core::parking_lot::Mutex; use deno_error::JsErrorClass; use deno_error::builtin_classes::GENERIC_ERROR; use deno_permissions::PermissionsContainer; use notify::Error as NotifyError; use notify::EventKind; use notify::RecommendedWatcher; use notify::RecursiveMode; use notify::Watcher; use notify::event::Event as NotifyEvent; use notify::event::ModifyKind; use serde::Serialize; use tokio::sync::mpsc; deno_core::extension!( deno_fs_events, ops = [op_fs_events_open, op_fs_events_poll], ); struct FsEventsResource { receiver: AsyncRefCell<mpsc::Receiver<Result<FsEvent, NotifyError>>>, cancel: CancelHandle, } impl Resource for FsEventsResource { fn name(&self) -> Cow<'_, str> { "fsEvents".into() } fn close(self: Rc<Self>) { self.cancel.cancel(); } } /// Represents a file system event. /// /// We do not use the event directly from the notify crate. We flatten /// the structure into this simpler structure. We want to only make it more /// complex as needed. /// /// Feel free to expand this struct as long as you can add tests to demonstrate /// the complexity. #[derive(Serialize, Debug, Clone)] struct FsEvent { kind: &'static str, paths: Vec<PathBuf>, flag: Option<&'static str>, } impl From<NotifyEvent> for FsEvent { fn from(e: NotifyEvent) -> Self { let kind = match e.kind { EventKind::Any => "any", EventKind::Access(_) => "access", EventKind::Create(_) => "create", EventKind::Modify(modify_kind) => match modify_kind { ModifyKind::Name(_) => "rename", ModifyKind::Any | ModifyKind::Data(_) | ModifyKind::Metadata(_) | ModifyKind::Other => "modify", }, EventKind::Remove(_) => "remove", EventKind::Other => "other", }; let flag = e.flag().map(|f| match f { notify::event::Flag::Rescan => "rescan", }); FsEvent { kind, paths: e.paths, flag, } } } type WatchSender = (Vec<PathBuf>, mpsc::Sender<Result<FsEvent, NotifyError>>); struct WatcherState { senders: Arc<Mutex<Vec<WatchSender>>>, watcher: RecommendedWatcher, } fn starts_with_canonicalized(path: &Path, prefix: &Path) -> bool { #[allow(clippy::disallowed_methods)] let path = path.canonicalize().ok(); #[allow(clippy::disallowed_methods)] let prefix = std::fs::canonicalize(prefix).ok(); match (path, prefix) { (Some(path), Some(prefix)) => path.starts_with(prefix), _ => false, } } fn is_file_removed(event_path: &PathBuf) -> bool { let exists_path = std::fs::exists(event_path); match exists_path { Ok(res) => !res, Err(_) => false, } } deno_error::js_error_wrapper!(NotifyError, JsNotifyError, |err| { match &err.kind { notify::ErrorKind::Generic(_) => GENERIC_ERROR.into(), notify::ErrorKind::Io(e) => e.get_class(), notify::ErrorKind::PathNotFound => "NotFound".into(), notify::ErrorKind::WatchNotFound => "NotFound".into(), notify::ErrorKind::InvalidConfig(_) => "InvalidData".into(), notify::ErrorKind::MaxFilesWatch => GENERIC_ERROR.into(), } }); #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum FsEventsError { #[class(inherit)] #[error(transparent)] Resource(#[from] deno_core::error::ResourceError), #[class(inherit)] #[error(transparent)] Permission(#[from] deno_permissions::PermissionCheckError), #[class(inherit)] #[error(transparent)] Notify(JsNotifyError), #[class(inherit)] #[error(transparent)] Canceled(#[from] deno_core::Canceled), } fn start_watcher( state: &mut OpState, paths: Vec<PathBuf>, sender: mpsc::Sender<Result<FsEvent, NotifyError>>, ) -> Result<(), FsEventsError> { if let Some(watcher) = state.try_borrow_mut::<WatcherState>() { watcher.senders.lock().push((paths, sender)); return Ok(()); } let senders = Arc::new(Mutex::new(vec![(paths, sender)])); let sender_clone = senders.clone(); let watcher: RecommendedWatcher = Watcher::new( move |res: Result<NotifyEvent, NotifyError>| { let res2 = res .map(FsEvent::from) .map_err(|e| FsEventsError::Notify(JsNotifyError(e))); for (paths, sender) in sender_clone.lock().iter() { // Ignore result, if send failed it means that watcher was already closed, // but not all messages have been flushed. // Only send the event if the path matches one of the paths that the user is watching if let Ok(event) = &res2 { if paths.iter().any(|path| { event.paths.iter().any(|event_path| { same_file::is_same_file(event_path, path).unwrap_or(false) || starts_with_canonicalized(event_path, path) }) }) { let _ = sender.try_send(Ok(event.clone())); } else if event.paths.iter().any(is_file_removed) { let remove_event = FsEvent { kind: "remove", paths: event.paths.clone(), flag: None, }; let _ = sender.try_send(Ok(remove_event)); } } } }, Default::default(), ) .map_err(|e| FsEventsError::Notify(JsNotifyError(e)))?; state.put::<WatcherState>(WatcherState { watcher, senders }); Ok(()) } #[op2(stack_trace)] #[smi] fn op_fs_events_open( state: &mut OpState, recursive: bool, #[serde] paths: Vec<String>, ) -> Result<ResourceId, FsEventsError> { let mut resolved_paths = Vec::with_capacity(paths.len()); { let permissions_container = state.borrow_mut::<PermissionsContainer>(); for path in paths { resolved_paths.push( permissions_container .check_open( Cow::Owned(PathBuf::from(path)), deno_permissions::OpenAccessKind::ReadNoFollow, Some("Deno.watchFs()"), )? .into_owned_path(), ); } } let (sender, receiver) = mpsc::channel::<Result<FsEvent, NotifyError>>(16); start_watcher(state, resolved_paths.clone(), sender)?; let recursive_mode = if recursive { RecursiveMode::Recursive } else { RecursiveMode::NonRecursive }; for path in &resolved_paths { let watcher = state.borrow_mut::<WatcherState>(); watcher .watcher .watch(path, recursive_mode) .map_err(|e| FsEventsError::Notify(JsNotifyError(e)))?; } let resource = FsEventsResource { receiver: AsyncRefCell::new(receiver), cancel: Default::default(), }; let rid = state.resource_table.add(resource); Ok(rid) } #[op2(async)] #[serde] async fn op_fs_events_poll( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<Option<FsEvent>, FsEventsError> { let resource = state.borrow().resource_table.get::<FsEventsResource>(rid)?; let mut receiver = RcRef::map(&resource, |r| &r.receiver).borrow_mut().await; let cancel = RcRef::map(resource, |r| &r.cancel); let maybe_result = receiver.recv().or_cancel(cancel).await?; match maybe_result { Some(Ok(value)) => Ok(Some(value)), Some(Err(err)) => Err(FsEventsError::Notify(JsNotifyError(err))), None => Ok(None), } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/ops/web_worker.rs
runtime/ops/web_worker.rs
// Copyright 2018-2025 the Deno authors. MIT license. mod sync_fetch; use std::cell::RefCell; use std::rc::Rc; use deno_core::CancelFuture; use deno_core::OpState; use deno_core::op2; use deno_web::JsMessageData; use deno_web::MessagePortError; pub use sync_fetch::SyncFetchError; use self::sync_fetch::op_worker_sync_fetch; use crate::web_worker::WebWorkerInternalHandle; use crate::web_worker::WorkerThreadType; deno_core::extension!( deno_web_worker, ops = [ op_worker_post_message, op_worker_recv_message, // Notify host that guest worker closes. op_worker_close, op_worker_get_type, op_worker_sync_fetch, ], ); #[op2] fn op_worker_post_message( state: &mut OpState, #[serde] data: JsMessageData, ) -> Result<(), MessagePortError> { let handle = state.borrow::<WebWorkerInternalHandle>().clone(); handle.port.send(state, data) } #[op2(async(lazy), fast)] #[serde] async fn op_worker_recv_message( state: Rc<RefCell<OpState>>, ) -> Result<Option<JsMessageData>, MessagePortError> { let handle = { let state = state.borrow(); state.borrow::<WebWorkerInternalHandle>().clone() }; handle .port .recv(state.clone()) .or_cancel(handle.cancel) .await? } #[op2(fast)] fn op_worker_close(state: &mut OpState) { // Notify parent that we're finished let mut handle = state.borrow_mut::<WebWorkerInternalHandle>().clone(); handle.terminate(); } #[op2] #[serde] fn op_worker_get_type(state: &mut OpState) -> WorkerThreadType { let handle = state.borrow::<WebWorkerInternalHandle>().clone(); handle.worker_type }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/runtime/ops/web_worker/sync_fetch.rs
runtime/ops/web_worker/sync_fetch.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::sync::Arc; use deno_core::OpState; use deno_core::futures::StreamExt; use deno_core::op2; use deno_core::url::Url; use deno_fetch::FetchError; use deno_fetch::data_url::DataUrl; use deno_web::BlobStore; use http_body_util::BodyExt; use hyper::body::Bytes; use serde::Deserialize; use serde::Serialize; use crate::web_worker::WebWorkerInternalHandle; use crate::web_worker::WorkerThreadType; // TODO(andreubotella) Properly parse the MIME type fn mime_type_essence(mime_type: &str) -> String { let essence = match mime_type.split_once(';') { Some((essence, _)) => essence, None => mime_type, }; essence.trim().to_ascii_lowercase() } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum SyncFetchError { #[class(type)] #[error("Blob URLs are not supported in this context.")] BlobUrlsNotSupportedInContext, #[class(inherit)] #[error("{0}")] Io( #[from] #[inherit] std::io::Error, ), #[class(type)] #[error("Invalid script URL")] InvalidScriptUrl, #[class(type)] #[error("http status error: {0}")] InvalidStatusCode(http::StatusCode), #[class(type)] #[error("Classic scripts with scheme {0}: are not supported in workers")] ClassicScriptSchemeUnsupportedInWorkers(String), #[class(generic)] #[error("{0}")] InvalidUri(#[from] http::uri::InvalidUri), #[class("DOMExceptionNetworkError")] #[error("Invalid MIME type {0:?}.")] InvalidMimeType(String), #[class("DOMExceptionNetworkError")] #[error("Missing MIME type.")] MissingMimeType, #[class(inherit)] #[error(transparent)] Fetch( #[from] #[inherit] FetchError, ), #[class(inherit)] #[error(transparent)] Join( #[from] #[inherit] tokio::task::JoinError, ), #[class(inherit)] #[error(transparent)] Other(#[inherit] deno_error::JsErrorBox), } #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SyncFetchScript { url: String, script: String, } #[op2] #[serde] #[allow(clippy::result_large_err)] pub fn op_worker_sync_fetch( state: &mut OpState, #[serde] scripts: Vec<String>, loose_mime_checks: bool, ) -> Result<Vec<SyncFetchScript>, SyncFetchError> { let handle = state.borrow::<WebWorkerInternalHandle>().clone(); assert_eq!(handle.worker_type, WorkerThreadType::Classic); let client = deno_fetch::get_or_create_client_from_state(state) .map_err(FetchError::ClientCreate)?; // TODO(andreubotella) It's not good to throw an exception related to blob // URLs when none of the script URLs use the blob scheme. // Also, in which contexts are blob URLs not supported? let blob_store = state .try_borrow::<Arc<BlobStore>>() .ok_or(SyncFetchError::BlobUrlsNotSupportedInContext)? .clone(); // TODO(andreubotella): make the below thread into a resource that can be // re-used. This would allow parallel fetching of multiple scripts. let thread = std::thread::spawn(move || { let runtime = tokio::runtime::Builder::new_current_thread() .enable_io() .enable_time() .build()?; runtime.block_on(async move { let mut futures = scripts .into_iter() .map(|script| { let client = client.clone(); let blob_store = blob_store.clone(); deno_core::unsync::spawn(async move { let script_url = Url::parse(&script) .map_err(|_| SyncFetchError::InvalidScriptUrl)?; let mut loose_mime_checks = loose_mime_checks; let (body, mime_type, res_url) = match script_url.scheme() { "http" | "https" => { let mut req = http::Request::new(deno_fetch::ReqBody::empty()); *req.uri_mut() = script_url.as_str().parse()?; let resp = client.send(req).await.map_err(FetchError::ClientSend)?; if resp.status().is_client_error() || resp.status().is_server_error() { return Err(SyncFetchError::InvalidStatusCode(resp.status())); } // TODO(andreubotella) Properly run fetch's "extract a MIME type". let mime_type = resp .headers() .get("Content-Type") .and_then(|v| v.to_str().ok()) .map(mime_type_essence); // Always check the MIME type with HTTP(S). loose_mime_checks = false; let body = resp .collect() .await .map_err(SyncFetchError::Other)? .to_bytes(); (body, mime_type, script) } "data" => { let data_url = DataUrl::process(&script).map_err(FetchError::DataUrl)?; let mime_type = { let mime = data_url.mime_type(); format!("{}/{}", mime.type_, mime.subtype) }; let (body, _) = data_url.decode_to_vec().map_err(FetchError::Base64)?; (Bytes::from(body), Some(mime_type), script) } "blob" => { let blob = blob_store .get_object_url(script_url) .ok_or(FetchError::BlobNotFound)?; let mime_type = mime_type_essence(&blob.media_type); let body = blob.read_all().await; (Bytes::from(body), Some(mime_type), script) } _ => { return Err( SyncFetchError::ClassicScriptSchemeUnsupportedInWorkers( script_url.scheme().to_string(), ), ); } }; if !loose_mime_checks { // TODO(andreubotella) Check properly for a Javascript MIME type. match mime_type.as_deref() { Some("application/javascript" | "text/javascript") => {} Some(mime_type) => { return Err(SyncFetchError::InvalidMimeType( mime_type.to_string(), )); } None => return Err(SyncFetchError::MissingMimeType), } } let (text, _) = encoding_rs::UTF_8.decode_with_bom_removal(&body); Ok(SyncFetchScript { url: res_url, script: text.into_owned(), }) }) }) .collect::<deno_core::futures::stream::FuturesUnordered<_>>(); let mut ret = Vec::with_capacity(futures.len()); while let Some(result) = futures.next().await { let script = result??; ret.push(script); } Ok(ret) }) }); thread.join().unwrap() }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/rt_helper/lib.rs
ext/rt_helper/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::fs::File; use std::hash::Hash; use std::hash::Hasher; use std::io::BufReader; use std::io::Read; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum LoadError { #[class(generic)] #[error("Failed to write native addon (Deno FFI/Node API) '{0}' to '{1}' because the file system was readonly. This is a limitation of native addons with deno compile.", executable_path.display(), real_path.display())] ReadOnlyFilesystem { real_path: PathBuf, executable_path: PathBuf, }, #[class(generic)] #[error("Failed to write native addon (Deno FFI/Node API) '{0}' to '{1}'.", executable_path.display(), real_path.display())] FailedWriting { real_path: PathBuf, executable_path: PathBuf, #[source] source: std::io::Error, }, } pub type DenoRtNativeAddonLoaderRc = Arc<dyn DenoRtNativeAddonLoader>; /// Loads native addons in `deno compile`. /// /// The implementation should provide the bytes from the binary /// of the native file. pub trait DenoRtNativeAddonLoader: Send + Sync { fn load_if_in_vfs(&self, path: &Path) -> Option<Cow<'static, [u8]>>; fn load_and_resolve_path<'a>( &self, path: &'a Path, ) -> Result<Cow<'a, Path>, LoadError> { match self.load_if_in_vfs(path) { Some(bytes) => { let exe_name = std::env::current_exe().ok(); let exe_name = exe_name .as_ref() .and_then(|p| p.file_stem()) .map(|s| s.to_string_lossy()) .unwrap_or("denort".into()); let real_path = resolve_temp_file_name(&exe_name, path, &bytes); if let Err(err) = deno_path_util::fs::atomic_write_file( &sys_traits::impls::RealSys, &real_path, &bytes, 0o644, ) { if err.kind() == std::io::ErrorKind::ReadOnlyFilesystem { return Err(LoadError::ReadOnlyFilesystem { real_path, executable_path: path.to_path_buf(), }); } // another process might be using it... so only surface // the error if the files aren't equivalent if !file_matches_bytes(&real_path, &bytes) { return Err(LoadError::FailedWriting { executable_path: path.to_path_buf(), real_path, source: err, }); } } Ok(Cow::Owned(real_path)) } None => Ok(Cow::Borrowed(path)), } } } fn file_matches_bytes(path: &Path, expected_bytes: &[u8]) -> bool { let file = match File::open(path) { Ok(f) => f, Err(_) => return false, }; let len_on_disk = match file.metadata() { Ok(m) => m.len(), Err(_) => return false, }; if len_on_disk as usize != expected_bytes.len() { return false; // bail early } // Stream‑compare in fixed‑size chunks. const CHUNK: usize = 8 * 1024; let mut reader = BufReader::with_capacity(CHUNK, file); let mut buf = [0u8; CHUNK]; let mut offset = 0; loop { match reader.read(&mut buf) { Ok(0) => return offset == expected_bytes.len(), Ok(n) => { let next_offset = offset + n; if next_offset > expected_bytes.len() || buf[..n] != expected_bytes[offset..next_offset] { return false; } offset = next_offset; } Err(_) => return false, } } } fn resolve_temp_file_name( current_exe_name: &str, path: &Path, bytes: &[u8], ) -> PathBuf { // should be deterministic let path_hash = { let mut hasher = twox_hash::XxHash64::default(); path.hash(&mut hasher); hasher.finish() }; let bytes_hash = { let mut hasher = twox_hash::XxHash64::default(); bytes.hash(&mut hasher); hasher.finish() }; let mut file_name = format!("{}{}{}", current_exe_name, path_hash, bytes_hash); if let Some(ext) = path.extension() { file_name.push('.'); file_name.push_str(&ext.to_string_lossy()); } std::env::temp_dir().join(&file_name) } #[cfg(test)] mod test { use super::*; #[test] fn test_file_matches_bytes() { let tempdir = tempfile::TempDir::new().unwrap(); let path = tempdir.path().join("file.txt"); let mut bytes = vec![0u8; 17892]; for (i, byte) in bytes.iter_mut().enumerate() { *byte = i as u8; } std::fs::write(&path, &bytes).unwrap(); assert!(file_matches_bytes(&path, &bytes)); bytes[17192] = 9; assert!(!file_matches_bytes(&path, &bytes)); } #[test] fn test_resolve_temp_file_name() { let file_path = PathBuf::from("/test/test.node"); let bytes: [u8; 3] = [1, 2, 3]; let temp_file = resolve_temp_file_name("exe_name", &file_path, &bytes); assert_eq!( temp_file, std::env::temp_dir() .join("exe_name1805603793990095570513255480333703631005.node") ); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/process/lib.rs
ext/process/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; use std::ffi::OsString; use std::io::Write; #[cfg(unix)] use std::os::unix::prelude::ExitStatusExt; #[cfg(unix)] use std::os::unix::process::CommandExt; use std::path::Path; use std::path::PathBuf; #[cfg(unix)] use std::process::Command; use std::process::ExitStatus; #[cfg(unix)] use std::process::Stdio as StdStdio; use std::rc::Rc; use deno_core::AsyncMutFuture; use deno_core::AsyncRefCell; use deno_core::JsBuffer; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::ToJsBuffer; use deno_core::op2; use deno_core::serde_json; use deno_error::JsErrorBox; use deno_io::ChildStderrResource; use deno_io::ChildStdinResource; use deno_io::ChildStdoutResource; use deno_io::IntoRawIoHandle; use deno_io::fs::FileResource; use deno_os::SignalError; use deno_permissions::PathQueryDescriptor; use deno_permissions::PermissionsContainer; use deno_permissions::RunQueryDescriptor; #[cfg(windows)] use deno_subprocess_windows::Child as AsyncChild; #[cfg(windows)] use deno_subprocess_windows::Command; #[cfg(windows)] use deno_subprocess_windows::Stdio as StdStdio; use serde::Deserialize; use serde::Serialize; #[cfg(unix)] use tokio::process::Child as AsyncChild; pub mod ipc; use ipc::IpcAdvancedStreamResource; use ipc::IpcJsonStreamResource; use ipc::IpcRefTracker; pub const UNSTABLE_FEATURE_NAME: &str = "process"; #[derive(Copy, Clone, Eq, PartialEq, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Stdio { Inherit, Piped, Null, IpcForInternalUse, } impl Stdio { pub fn as_stdio(&self) -> StdStdio { match &self { Stdio::Inherit => StdStdio::inherit(), Stdio::Piped => StdStdio::piped(), Stdio::Null => StdStdio::null(), _ => unreachable!(), } } } #[derive(Copy, Clone, Eq, PartialEq)] pub enum StdioOrRid { Stdio(Stdio), Rid(ResourceId), } impl<'de> Deserialize<'de> for StdioOrRid { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { use serde_json::Value; let value = Value::deserialize(deserializer)?; match value { Value::String(val) => match val.as_str() { "inherit" => Ok(StdioOrRid::Stdio(Stdio::Inherit)), "piped" => Ok(StdioOrRid::Stdio(Stdio::Piped)), "null" => Ok(StdioOrRid::Stdio(Stdio::Null)), "ipc_for_internal_use" => { Ok(StdioOrRid::Stdio(Stdio::IpcForInternalUse)) } val => Err(serde::de::Error::unknown_variant( val, &["inherit", "piped", "null"], )), }, Value::Number(val) => match val.as_u64() { Some(val) if val <= ResourceId::MAX as u64 => { Ok(StdioOrRid::Rid(val as ResourceId)) } _ => Err(serde::de::Error::custom("Expected a positive integer")), }, _ => Err(serde::de::Error::custom( r#"Expected a resource id, "inherit", "piped", or "null""#, )), } } } impl StdioOrRid { pub fn as_stdio( &self, state: &mut OpState, ) -> Result<StdStdio, ProcessError> { match &self { StdioOrRid::Stdio(val) => Ok(val.as_stdio()), StdioOrRid::Rid(rid) => { Ok(FileResource::with_file(state, *rid, |file| { file.as_stdio().map_err(deno_error::JsErrorBox::from_err) })?) } } } pub fn is_ipc(&self) -> bool { matches!(self, StdioOrRid::Stdio(Stdio::IpcForInternalUse)) } } #[allow(clippy::disallowed_types)] pub type NpmProcessStateProviderRc = deno_fs::sync::MaybeArc<dyn NpmProcessStateProvider>; pub trait NpmProcessStateProvider: std::fmt::Debug + deno_fs::sync::MaybeSend + deno_fs::sync::MaybeSync { /// Gets a string containing the serialized npm state of the process. /// /// This will be set on the `DENO_DONT_USE_INTERNAL_NODE_COMPAT_STATE` environment /// variable when doing a `child_process.fork`. The implementor can then check this environment /// variable on startup to repopulate the internal npm state. fn get_npm_process_state(&self) -> String { // This method is only used in the CLI. String::new() } } #[derive(Debug)] pub struct EmptyNpmProcessStateProvider; impl NpmProcessStateProvider for EmptyNpmProcessStateProvider {} deno_core::extension!( deno_process, ops = [ op_spawn_child, op_spawn_wait, op_spawn_sync, op_spawn_kill, deprecated::op_run, deprecated::op_run_status, deprecated::op_kill, ], esm = ["40_process.js"], options = { get_npm_process_state: Option<NpmProcessStateProviderRc> }, state = |state, options| { state.put::<NpmProcessStateProviderRc>(options.get_npm_process_state.unwrap_or(deno_fs::sync::MaybeArc::new(EmptyNpmProcessStateProvider))); }, ); /// Second member stores the pid separately from the RefCell. It's needed for /// `op_spawn_kill`, where the RefCell is borrowed mutably by `op_spawn_wait`. struct ChildResource(RefCell<AsyncChild>, u32); impl Resource for ChildResource { fn name(&self) -> Cow<'_, str> { "child".into() } } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct SpawnArgs { cmd: String, args: Vec<String>, cwd: Option<String>, clear_env: bool, env: Vec<(String, String)>, #[cfg(unix)] gid: Option<u32>, #[cfg(unix)] uid: Option<u32>, #[cfg(windows)] windows_raw_arguments: bool, ipc: Option<i32>, serialization: Option<ChildIpcSerialization>, #[serde(flatten)] stdio: ChildStdio, input: Option<JsBuffer>, extra_stdio: Vec<Stdio>, detached: bool, needs_npm_process_state: bool, } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub enum ChildIpcSerialization { Json, Advanced, } impl std::fmt::Display for ChildIpcSerialization { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { ChildIpcSerialization::Json => "json", ChildIpcSerialization::Advanced => "advanced", } ) } } #[cfg(unix)] deno_error::js_error_wrapper!(nix::Error, JsNixError, |err| { match err { nix::Error::ECHILD => "NotFound", nix::Error::EINVAL => "TypeError", nix::Error::ENOENT => "NotFound", nix::Error::ENOTTY => "BadResource", nix::Error::EPERM => "PermissionDenied", nix::Error::ESRCH => "NotFound", nix::Error::ELOOP => "FilesystemLoop", nix::Error::ENOTDIR => "NotADirectory", nix::Error::ENETUNREACH => "NetworkUnreachable", nix::Error::EISDIR => "IsADirectory", nix::Error::UnknownErrno => "Error", &nix::Error::ENOTSUP => unreachable!(), _ => "Error", } }); #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum ProcessError { #[class(inherit)] #[error("Failed to spawn '{command}': {error}")] SpawnFailed { command: String, #[source] #[inherit] error: Box<ProcessError>, }, #[class(inherit)] #[error("{0}")] Io(#[from] std::io::Error), #[cfg(unix)] #[class(inherit)] #[error(transparent)] Nix(JsNixError), #[class(inherit)] #[error("failed resolving cwd: {0}")] FailedResolvingCwd(#[source] std::io::Error), #[class(inherit)] #[error(transparent)] Permission(#[from] deno_permissions::PermissionCheckError), #[class(inherit)] #[error(transparent)] RunPermission(#[from] CheckRunPermissionError), #[class(inherit)] #[error(transparent)] Resource(deno_core::error::ResourceError), #[class(generic)] #[error(transparent)] BorrowMut(std::cell::BorrowMutError), #[class(generic)] #[error(transparent)] Which(deno_permissions::which::Error), #[class(type)] #[error("Child process has already terminated.")] ChildProcessAlreadyTerminated, #[class(type)] #[error("Invalid pid")] InvalidPid, #[class(inherit)] #[error(transparent)] Signal(#[from] SignalError), #[class(inherit)] #[error(transparent)] Other(#[from] JsErrorBox), #[class(type)] #[error("Missing cmd")] MissingCmd, // only for Deno.run } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct ChildStdio { stdin: StdioOrRid, stdout: StdioOrRid, stderr: StdioOrRid, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct ChildStatus { success: bool, code: i32, signal: Option<String>, } impl TryFrom<ExitStatus> for ChildStatus { type Error = SignalError; fn try_from(status: ExitStatus) -> Result<Self, Self::Error> { let code = status.code(); #[cfg(unix)] let signal = status.signal(); #[cfg(not(unix))] let signal: Option<i32> = None; let status = if let Some(signal) = signal { ChildStatus { success: false, code: 128 + signal, #[cfg(unix)] signal: Some(deno_signals::signal_int_to_str(signal)?.to_string()), #[cfg(not(unix))] signal: None, } } else { let code = code.expect("Should have either an exit code or a signal."); ChildStatus { success: code == 0, code, signal: None, } }; Ok(status) } } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct SpawnOutput { status: ChildStatus, stdout: Option<ToJsBuffer>, stderr: Option<ToJsBuffer>, } type CreateCommand = ( Command, Option<ResourceId>, Vec<Option<ResourceId>>, Vec<deno_io::RawBiPipeHandle>, ); pub fn npm_process_state_tempfile( contents: &[u8], ) -> Result<deno_io::RawIoHandle, std::io::Error> { let mut temp_file = tempfile::tempfile()?; temp_file.write_all(contents)?; let handle = temp_file.into_raw_io_handle(); #[cfg(windows)] { use windows_sys::Win32::Foundation::HANDLE_FLAG_INHERIT; // make the handle inheritable // SAFETY: winapi call, handle is valid unsafe { windows_sys::Win32::Foundation::SetHandleInformation( handle as _, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT, ); } Ok(handle) } #[cfg(unix)] { // SAFETY: libc call, fd is valid let inheritable = unsafe { // duplicate the FD to get a new one that doesn't have the CLOEXEC flag set // so it can be inherited by the child process libc::dup(handle) }; // SAFETY: libc call, fd is valid unsafe { // close the old one libc::close(handle); } Ok(inheritable) } } pub const NPM_RESOLUTION_STATE_FD_ENV_VAR_NAME: &str = "DENO_DONT_USE_INTERNAL_NODE_COMPAT_STATE_FD"; fn create_command( state: &mut OpState, mut args: SpawnArgs, api_name: &str, ) -> Result<CreateCommand, ProcessError> { let maybe_npm_process_state = if args.needs_npm_process_state { let provider = state.borrow::<NpmProcessStateProviderRc>(); let process_state = provider.get_npm_process_state(); let fd = npm_process_state_tempfile(process_state.as_bytes())?; args.env.push(( NPM_RESOLUTION_STATE_FD_ENV_VAR_NAME.to_string(), (fd as usize).to_string(), )); Some(fd) } else { None }; let (cmd, run_env) = compute_run_cmd_and_check_permissions( &args.cmd, args.cwd.as_deref(), &args.env, args.clear_env, state, api_name, )?; let mut command = Command::new(cmd); #[cfg(windows)] { if args.detached { command.detached(); } if args.windows_raw_arguments { command.verbatim_arguments(true); } command.args(args.args); } #[cfg(not(windows))] command.args(args.args); command.current_dir(run_env.cwd); command.env_clear(); command.envs(run_env.envs.into_iter().map(|(k, v)| (k.into_inner(), v))); #[cfg(unix)] if let Some(gid) = args.gid { command.gid(gid); } #[cfg(unix)] if let Some(uid) = args.uid { command.uid(uid); } if args.stdio.stdin.is_ipc() { args.ipc = Some(0); } else if args.input.is_some() { command.stdin(StdStdio::piped()); } else { command.stdin(args.stdio.stdin.as_stdio(state)?); } command.stdout(match args.stdio.stdout { StdioOrRid::Stdio(Stdio::Inherit) => StdioOrRid::Rid(1).as_stdio(state)?, value => value.as_stdio(state)?, }); command.stderr(match args.stdio.stderr { StdioOrRid::Stdio(Stdio::Inherit) => StdioOrRid::Rid(2).as_stdio(state)?, value => value.as_stdio(state)?, }); #[cfg(unix)] // TODO(bartlomieju): #[allow(clippy::undocumented_unsafe_blocks)] unsafe { let mut extra_pipe_rids = Vec::new(); let mut fds_to_dup = Vec::new(); let mut fds_to_close = Vec::new(); let mut ipc_rid = None; if let Some(fd) = maybe_npm_process_state { fds_to_close.push(fd); } if let Some(ipc) = args.ipc && ipc >= 0 { let (ipc_fd1, ipc_fd2) = deno_io::bi_pipe_pair_raw()?; fds_to_dup.push((ipc_fd2, ipc)); fds_to_close.push(ipc_fd2); /* One end returned to parent process (this) */ let pipe_rid = match args.serialization { Some(ChildIpcSerialization::Json) | None => { state.resource_table.add(IpcJsonStreamResource::new( ipc_fd1 as _, IpcRefTracker::new(state.external_ops_tracker.clone()), )?) } Some(ChildIpcSerialization::Advanced) => { state.resource_table.add(IpcAdvancedStreamResource::new( ipc_fd1 as _, IpcRefTracker::new(state.external_ops_tracker.clone()), )?) } }; /* The other end passed to child process via NODE_CHANNEL_FD */ command.env("NODE_CHANNEL_FD", format!("{}", ipc)); command.env( "NODE_CHANNEL_SERIALIZATION_MODE", args .serialization .unwrap_or(ChildIpcSerialization::Json) .to_string(), ); ipc_rid = Some(pipe_rid); } for (i, stdio) in args.extra_stdio.into_iter().enumerate() { // index 0 in `extra_stdio` actually refers to fd 3 // because we handle stdin,stdout,stderr specially let fd = (i + 3) as i32; // TODO(nathanwhit): handle inherited, but this relies on the parent process having // fds open already. since we don't generally support dealing with raw fds, // we can't properly support this if matches!(stdio, Stdio::Piped) { let (fd1, fd2) = deno_io::bi_pipe_pair_raw()?; fds_to_dup.push((fd2, fd)); fds_to_close.push(fd2); let rid = state.resource_table.add( match deno_io::BiPipeResource::from_raw_handle(fd1) { Ok(v) => v, Err(e) => { log::warn!("Failed to open bidirectional pipe for fd {fd}: {e}"); extra_pipe_rids.push(None); continue; } }, ); extra_pipe_rids.push(Some(rid)); } else { extra_pipe_rids.push(None); } } let detached = args.detached; if detached || !fds_to_dup.is_empty() || args.gid.is_some() { command.pre_exec(move || { if detached { libc::setsid(); } for &(src, dst) in &fds_to_dup { if src >= 0 && dst >= 0 { let _fd = libc::dup2(src, dst); libc::close(src); } } libc::setgroups(0, std::ptr::null()); Ok(()) }); } Ok((command, ipc_rid, extra_pipe_rids, fds_to_close)) } #[cfg(windows)] { let mut extra_pipe_rids = Vec::with_capacity(args.extra_stdio.len()); let mut ipc_rid = None; let mut handles_to_close = Vec::with_capacity(1); if let Some(handle) = maybe_npm_process_state { handles_to_close.push(handle); } if let Some(ipc) = args.ipc && ipc >= 0 { let (hd1, hd2) = deno_io::bi_pipe_pair_raw()?; /* One end returned to parent process (this) */ let pipe_rid = match args.serialization { Some(ChildIpcSerialization::Json) | None => { state.resource_table.add(IpcJsonStreamResource::new( hd1 as _, IpcRefTracker::new(state.external_ops_tracker.clone()), )?) } Some(ChildIpcSerialization::Advanced) => { state.resource_table.add(IpcAdvancedStreamResource::new( hd1 as _, IpcRefTracker::new(state.external_ops_tracker.clone()), )?) } }; /* The other end passed to child process via NODE_CHANNEL_FD */ command.env("NODE_CHANNEL_FD", format!("{}", hd2 as i64)); command.env( "NODE_CHANNEL_SERIALIZATION_MODE", args .serialization .unwrap_or(ChildIpcSerialization::Json) .to_string(), ); handles_to_close.push(hd2); ipc_rid = Some(pipe_rid); } for (i, stdio) in args.extra_stdio.into_iter().enumerate() { // index 0 in `extra_stdio` actually refers to fd 3 // because we handle stdin,stdout,stderr specially let fd = (i + 3) as i32; // TODO(nathanwhit): handle inherited, but this relies on the parent process having // fds open already. since we don't generally support dealing with raw fds, // we can't properly support this if matches!(stdio, Stdio::Piped) { let (fd1, fd2) = deno_io::bi_pipe_pair_raw()?; handles_to_close.push(fd2); let rid = state.resource_table.add( match deno_io::BiPipeResource::from_raw_handle(fd1) { Ok(v) => v, Err(e) => { log::warn!("Failed to open bidirectional pipe for fd {fd}: {e}"); extra_pipe_rids.push(None); continue; } }, ); command.extra_handle(Some(fd2)); extra_pipe_rids.push(Some(rid)); } else { // no handle, push an empty handle so we need get the right fds for following handles command.extra_handle(None); extra_pipe_rids.push(None); } } Ok((command, ipc_rid, extra_pipe_rids, handles_to_close)) } } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct Child { rid: ResourceId, pid: u32, stdin_rid: Option<ResourceId>, stdout_rid: Option<ResourceId>, stderr_rid: Option<ResourceId>, ipc_pipe_rid: Option<ResourceId>, extra_pipe_rids: Vec<Option<ResourceId>>, } fn spawn_child( state: &mut OpState, command: Command, ipc_pipe_rid: Option<ResourceId>, extra_pipe_rids: Vec<Option<ResourceId>>, detached: bool, ) -> Result<Child, ProcessError> { #[cfg(windows)] let mut command = command; #[cfg(not(windows))] let mut command = tokio::process::Command::from(command); // TODO(@crowlkats): allow detaching processes. // currently deno will orphan a process when exiting with an error or Deno.exit() // We want to kill child when it's closed if !detached { command.kill_on_drop(true); } let mut child = match command.spawn() { Ok(child) => child, Err(err) => { #[cfg(not(windows))] let command = command.as_std(); let command_name = command.get_program().to_string_lossy(); if let Some(cwd) = command.get_current_dir() { // launching a sub process always depends on the real // file system so using these methods directly is ok #[allow(clippy::disallowed_methods)] if !cwd.exists() { return Err( std::io::Error::new( std::io::ErrorKind::NotFound, format!( "Failed to spawn '{}': No such cwd '{}'", command_name, cwd.to_string_lossy() ), ) .into(), ); } #[allow(clippy::disallowed_methods)] if !cwd.is_dir() { return Err( std::io::Error::new( std::io::ErrorKind::NotFound, format!( "Failed to spawn '{}': cwd is not a directory '{}'", command_name, cwd.to_string_lossy() ), ) .into(), ); } } return Err(ProcessError::SpawnFailed { command: command.get_program().to_string_lossy().into_owned(), error: Box::new(err.into()), }); } }; let pid = child.id().expect("Process ID should be set."); #[cfg(not(windows))] let stdin_rid = child .stdin .take() .map(|stdin| state.resource_table.add(ChildStdinResource::from(stdin))); #[cfg(windows)] let stdin_rid = child .stdin .take() .map(tokio::process::ChildStdin::from_std) .transpose()? .map(|stdin| state.resource_table.add(ChildStdinResource::from(stdin))); #[cfg(not(windows))] let stdout_rid = child .stdout .take() .map(|stdout| state.resource_table.add(ChildStdoutResource::from(stdout))); #[cfg(windows)] let stdout_rid = child .stdout .take() .map(tokio::process::ChildStdout::from_std) .transpose()? .map(|stdout| state.resource_table.add(ChildStdoutResource::from(stdout))); #[cfg(not(windows))] let stderr_rid = child .stderr .take() .map(|stderr| state.resource_table.add(ChildStderrResource::from(stderr))); #[cfg(windows)] let stderr_rid = child .stderr .take() .map(tokio::process::ChildStderr::from_std) .transpose()? .map(|stderr| state.resource_table.add(ChildStderrResource::from(stderr))); let child_rid = state .resource_table .add(ChildResource(RefCell::new(child), pid)); Ok(Child { rid: child_rid, pid, stdin_rid, stdout_rid, stderr_rid, ipc_pipe_rid, extra_pipe_rids, }) } fn compute_run_cmd_and_check_permissions( arg_cmd: &str, arg_cwd: Option<&str>, arg_envs: &[(String, String)], arg_clear_env: bool, state: &mut OpState, api_name: &str, ) -> Result<(PathBuf, RunEnv), ProcessError> { let run_env = compute_run_env(arg_cwd, arg_envs, arg_clear_env).map_err(|e| { ProcessError::SpawnFailed { command: arg_cmd.to_string(), error: Box::new(e), } })?; let cmd = resolve_cmd(arg_cmd, &run_env).map_err(|e| ProcessError::SpawnFailed { command: arg_cmd.to_string(), error: Box::new(e), })?; check_run_permission( state, &RunQueryDescriptor::Path( PathQueryDescriptor::new_known_absolute(Cow::Borrowed(&cmd)) .with_requested(arg_cmd.to_string()), ), &run_env, api_name, )?; Ok((cmd, run_env)) } #[derive(Debug)] struct EnvVarKey { inner: OsString, // Windows treats env vars as case insensitive, so use // a normalized value for comparisons instead of the raw // case sensitive value #[cfg(windows)] normalized: OsString, } impl EnvVarKey { pub fn new(value: OsString) -> Self { Self { #[cfg(windows)] normalized: value.to_ascii_uppercase(), inner: value, } } pub fn from_str(value: &str) -> Self { Self::new(OsString::from(value)) } pub fn into_inner(self) -> OsString { self.inner } pub fn comparison_value(&self) -> &OsString { #[cfg(windows)] { &self.normalized } #[cfg(not(windows))] { &self.inner } } } impl std::hash::Hash for EnvVarKey { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.comparison_value().hash(state); } } impl std::cmp::Eq for EnvVarKey {} impl std::cmp::PartialEq for EnvVarKey { fn eq(&self, other: &Self) -> bool { self.comparison_value() == other.comparison_value() } } struct RunEnv { envs: HashMap<EnvVarKey, OsString>, cwd: PathBuf, } /// Computes the current environment, which will then be used to inform /// permissions and finally spawning. This is very important to compute /// ahead of time so that the environment used to verify permissions is /// the same environment used to spawn the sub command. This protects against /// someone doing timing attacks by changing the environment on a worker. fn compute_run_env( arg_cwd: Option<&str>, arg_envs: &[(String, String)], arg_clear_env: bool, ) -> Result<RunEnv, ProcessError> { #[allow(clippy::disallowed_methods)] let cwd = std::env::current_dir().map_err(ProcessError::FailedResolvingCwd)?; let cwd = arg_cwd .map(|cwd_arg| resolve_path(cwd_arg, &cwd)) .unwrap_or(cwd); let envs = if arg_clear_env { arg_envs .iter() .map(|(k, v)| (EnvVarKey::from_str(k), OsString::from(v))) .collect() } else { let mut envs = std::env::vars_os() .map(|(k, v)| (EnvVarKey::new(k), v)) .collect::<HashMap<_, _>>(); for (key, value) in arg_envs { envs.insert(EnvVarKey::from_str(key), OsString::from(value)); } envs }; Ok(RunEnv { envs, cwd }) } fn resolve_cmd(cmd: &str, env: &RunEnv) -> Result<PathBuf, ProcessError> { let is_path = cmd.contains('/'); #[cfg(windows)] let is_path = is_path || cmd.contains('\\') || Path::new(&cmd).is_absolute(); if is_path { Ok(resolve_path(cmd, &env.cwd)) } else { let path = env.envs.get(&EnvVarKey::new(OsString::from("PATH"))); match deno_permissions::which::which_in( sys_traits::impls::RealSys, cmd, path.cloned(), env.cwd.clone(), ) { Ok(cmd) => Ok(cmd), Err(deno_permissions::which::Error::CannotFindBinaryPath) => { Err(std::io::Error::from(std::io::ErrorKind::NotFound).into()) } Err(err) => Err(ProcessError::Which(err)), } } } fn resolve_path(path: &str, cwd: &Path) -> PathBuf { deno_path_util::normalize_path(Cow::Owned(cwd.join(path))).into_owned() } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum CheckRunPermissionError { #[class(inherit)] #[error(transparent)] Permission(#[from] deno_permissions::PermissionCheckError), #[class(inherit)] #[error("{0}")] Other(JsErrorBox), } fn check_run_permission( state: &mut OpState, cmd: &RunQueryDescriptor, run_env: &RunEnv, api_name: &str, ) -> Result<(), CheckRunPermissionError> { let permissions = state.borrow_mut::<PermissionsContainer>(); if !permissions.query_run_all(api_name) { // error the same on all platforms let env_var_names = get_requires_allow_all_env_vars(run_env); if !env_var_names.is_empty() { // we don't allow users to launch subprocesses with any LD_ or DYLD_* // env vars set because this allows executing code (ex. LD_PRELOAD) return Err(CheckRunPermissionError::Other(JsErrorBox::new( "NotCapable", format!( "Requires --allow-run permissions to spawn subprocess with {0} environment variable{1}. Alternatively, spawn with {2} environment variable{1} unset.", env_var_names.join(", "), if env_var_names.len() != 1 { "s" } else { "" }, if env_var_names.len() != 1 { "these" } else { "the" } ), ))); } permissions.check_run(cmd, api_name)?; } Ok(()) } fn get_requires_allow_all_env_vars(env: &RunEnv) -> Vec<&str> { fn requires_allow_all(key: &str) -> bool { fn starts_with_ignore_case(key: &str, search_value: &str) -> bool { if let Some((key, _)) = key.split_at_checked(search_value.len()) { search_value.eq_ignore_ascii_case(key) } else { false } } let key = key.trim(); // we could be more targted here, but there are quite a lot of // LD_* and DYLD_* env variables starts_with_ignore_case(key, "LD_") || starts_with_ignore_case(key, "DYLD_") } fn is_empty(value: &OsString) -> bool { value.is_empty() || value.to_str().map(|v| v.trim().is_empty()).unwrap_or(false) } let mut found_envs = env .envs .iter() .filter_map(|(k, v)| { let key = k.comparison_value().to_str()?; if requires_allow_all(key) && !is_empty(v) { Some(key) } else { None } }) .collect::<Vec<_>>(); found_envs.sort(); found_envs } #[op2(stack_trace)] #[serde] fn op_spawn_child( state: &mut OpState, #[serde] args: SpawnArgs, #[string] api_name: String, ) -> Result<Child, ProcessError> { let detached = args.detached; let (command, pipe_rid, extra_pipe_rids, handles_to_close) = create_command(state, args, &api_name)?; let child = spawn_child(state, command, pipe_rid, extra_pipe_rids, detached); for handle in handles_to_close { deno_io::close_raw_handle(handle); } child } #[op2(async)] #[allow(clippy::await_holding_refcell_ref)] #[serde] async fn op_spawn_wait( state: Rc<RefCell<OpState>>, #[smi] rid: ResourceId, ) -> Result<ChildStatus, ProcessError> { let resource = state .borrow_mut() .resource_table .get::<ChildResource>(rid) .map_err(ProcessError::Resource)?; let result = resource .0 .try_borrow_mut() .map_err(ProcessError::BorrowMut)? .wait() .await? .try_into()?; if let Ok(resource) = state.borrow_mut().resource_table.take_any(rid) { resource.close(); } Ok(result) } #[op2(stack_trace)] #[serde] fn op_spawn_sync( state: &mut OpState, #[serde] args: SpawnArgs, ) -> Result<SpawnOutput, ProcessError> { let stdout = matches!(args.stdio.stdout, StdioOrRid::Stdio(Stdio::Piped)); let stderr = matches!(args.stdio.stderr, StdioOrRid::Stdio(Stdio::Piped)); let input = args.input.clone(); let (mut command, _, _, _) = create_command(state, args, "Deno.Command().outputSync()")?; let mut child = command.spawn().map_err(|e| ProcessError::SpawnFailed { command: command.get_program().to_string_lossy().into_owned(), error: Box::new(e.into()), })?; if let Some(input) = input { let mut stdin = child.stdin.take().ok_or_else(|| { ProcessError::Io(std::io::Error::other("stdin is not available")) })?; stdin.write_all(&input)?; stdin.flush()?; } let output = child .wait_with_output() .map_err(|e| ProcessError::SpawnFailed { command: command.get_program().to_string_lossy().into_owned(), error: Box::new(e.into()), })?; Ok(SpawnOutput { status: output.status.try_into()?, stdout: if stdout { Some(output.stdout.into()) } else { None }, stderr: if stderr { Some(output.stderr.into()) } else { None }, }) } #[derive(serde::Deserialize)] #[serde(untagged)] enum SignalArg { String(String), Int(i32), } #[op2(stack_trace)] fn op_spawn_kill( state: &mut OpState, #[smi] rid: ResourceId, #[serde] signal: SignalArg, ) -> Result<(), ProcessError> { if let Ok(child_resource) = state.resource_table.get::<ChildResource>(rid) { deprecated::kill(child_resource.1 as i32, &signal)?; return Ok(()); } Err(ProcessError::ChildProcessAlreadyTerminated) } mod deprecated { #[cfg(windows)] use deno_subprocess_windows::Child; #[cfg(not(windows))] use tokio::process::Child; use super::*; #[derive(Deserialize)] #[serde(rename_all = "camelCase")] pub struct RunArgs { cmd: Vec<String>, cwd: Option<String>, env: Vec<(String, String)>, stdin: StdioOrRid, stdout: StdioOrRid, stderr: StdioOrRid, } struct ChildResource { child: AsyncRefCell<Child>, } impl Resource for ChildResource { fn name(&self) -> Cow<'_, str> { "child".into() } } impl ChildResource { fn borrow_mut(self: Rc<Self>) -> AsyncMutFuture<Child> { RcRef::map(self, |r| &r.child).borrow_mut() } } #[derive(Serialize)] #[serde(rename_all = "camelCase")] // TODO(@AaronO): maybe find a more descriptive name or a convention for return structs pub struct RunInfo { rid: ResourceId, pid: Option<u32>, stdin_rid: Option<ResourceId>, stdout_rid: Option<ResourceId>, stderr_rid: Option<ResourceId>, } #[op2(stack_trace)] #[serde] pub fn op_run( state: &mut OpState, #[serde] run_args: RunArgs, ) -> Result<RunInfo, ProcessError> { let args = run_args.cmd; let cmd = args.first().ok_or(ProcessError::MissingCmd)?; let (cmd, run_env) = compute_run_cmd_and_check_permissions( cmd, run_args.cwd.as_deref(), &run_args.env, /* clear env */ false, state, "Deno.run()", )?; #[cfg(windows)] let mut c = Command::new(cmd); #[cfg(not(windows))] let mut c = tokio::process::Command::new(cmd); for arg in args.iter().skip(1) { c.arg(arg); } c.current_dir(run_env.cwd); c.env_clear(); for (key, value) in run_env.envs { c.env(key.inner, value); } #[cfg(unix)] // TODO(bartlomieju): #[allow(clippy::undocumented_unsafe_blocks)] unsafe { c.pre_exec(|| { libc::setgroups(0, std::ptr::null()); Ok(()) }); } // TODO: make this work with other resources, eg. sockets c.stdin(run_args.stdin.as_stdio(state)?); c.stdout( match run_args.stdout { StdioOrRid::Stdio(Stdio::Inherit) => StdioOrRid::Rid(1),
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
true
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/process/ipc.rs
ext/process/ipc.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::future::Future; use std::io; use std::mem; use std::pin::Pin; use std::rc::Rc; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicUsize; use std::task::Context; use std::task::Poll; use std::task::ready; use deno_core::AsyncRefCell; use deno_core::CancelHandle; use deno_core::ExternalOpsTracker; use deno_core::RcRef; use deno_core::serde_json; use deno_io::BiPipe; use deno_io::BiPipeRead; use deno_io::BiPipeWrite; use memchr::memchr; use pin_project_lite::pin_project; use tokio::io::AsyncRead; use tokio::io::AsyncWriteExt; use tokio::io::ReadBuf; /// Tracks whether the IPC resources is currently /// refed, and allows refing/unrefing it. pub struct IpcRefTracker { refed: AtomicBool, tracker: OpsTracker, } /// A little wrapper so we don't have to get an /// `ExternalOpsTracker` for tests. When we aren't /// cfg(test), this will get optimized out. enum OpsTracker { External(ExternalOpsTracker), #[cfg(test)] Test, } impl OpsTracker { fn ref_(&self) { match self { Self::External(tracker) => tracker.ref_op(), #[cfg(test)] Self::Test => {} } } fn unref(&self) { match self { Self::External(tracker) => tracker.unref_op(), #[cfg(test)] Self::Test => {} } } } impl IpcRefTracker { pub fn new(tracker: ExternalOpsTracker) -> Self { Self { refed: AtomicBool::new(false), tracker: OpsTracker::External(tracker), } } #[cfg(test)] fn new_test() -> Self { Self { refed: AtomicBool::new(false), tracker: OpsTracker::Test, } } pub fn ref_(&self) { if !self.refed.swap(true, std::sync::atomic::Ordering::AcqRel) { self.tracker.ref_(); } } pub fn unref(&self) { if self.refed.swap(false, std::sync::atomic::Ordering::AcqRel) { self.tracker.unref(); } } } pub struct IpcJsonStreamResource { pub read_half: AsyncRefCell<IpcJsonStream>, pub write_half: AsyncRefCell<BiPipeWrite>, pub cancel: Rc<CancelHandle>, pub queued_bytes: AtomicUsize, pub ref_tracker: IpcRefTracker, } impl deno_core::Resource for IpcJsonStreamResource { fn close(self: Rc<Self>) { self.cancel.cancel(); } } impl IpcJsonStreamResource { pub fn new( stream: i64, ref_tracker: IpcRefTracker, ) -> Result<Self, std::io::Error> { let (read_half, write_half) = BiPipe::from_raw(stream as _)?.split(); Ok(Self { read_half: AsyncRefCell::new(IpcJsonStream::new(read_half)), write_half: AsyncRefCell::new(write_half), cancel: Default::default(), queued_bytes: Default::default(), ref_tracker, }) } #[cfg(all(unix, test))] pub fn from_stream( stream: tokio::net::UnixStream, ref_tracker: IpcRefTracker, ) -> Self { let (read_half, write_half) = stream.into_split(); Self { read_half: AsyncRefCell::new(IpcJsonStream::new(read_half.into())), write_half: AsyncRefCell::new(write_half.into()), cancel: Default::default(), queued_bytes: Default::default(), ref_tracker, } } #[cfg(all(windows, test))] pub fn from_stream( pipe: tokio::net::windows::named_pipe::NamedPipeClient, ref_tracker: IpcRefTracker, ) -> Self { let (read_half, write_half) = tokio::io::split(pipe); Self { read_half: AsyncRefCell::new(IpcJsonStream::new(read_half.into())), write_half: AsyncRefCell::new(write_half.into()), cancel: Default::default(), queued_bytes: Default::default(), ref_tracker, } } /// writes _newline terminated_ JSON message to the IPC pipe. pub async fn write_msg_bytes( self: Rc<Self>, msg: &[u8], ) -> Result<(), io::Error> { let mut write_half = RcRef::map(self, |r| &r.write_half).borrow_mut().await; write_half.write_all(msg).await?; Ok(()) } } // Initial capacity of the buffered reader and the JSON backing buffer. // // This is a tradeoff between memory usage and performance on large messages. // // 64kb has been chosen after benchmarking 64 to 66536 << 6 - 1 bytes per message. pub const INITIAL_CAPACITY: usize = 1024 * 64; /// A buffer for reading from the IPC pipe. /// Similar to the internal buffer of `tokio::io::BufReader`. /// /// This exists to provide buffered reading while granting mutable access /// to the internal buffer (which isn't exposed through `tokio::io::BufReader` /// or the `AsyncBufRead` trait). `simd_json` requires mutable access to an input /// buffer for parsing, so this allows us to use the read buffer directly as the /// input buffer without a copy (provided the message fits). struct ReadBuffer { buffer: Box<[u8]>, pos: usize, cap: usize, } impl ReadBuffer { fn new() -> Self { Self { buffer: vec![0; INITIAL_CAPACITY].into_boxed_slice(), pos: 0, cap: 0, } } fn get_mut(&mut self) -> &mut [u8] { &mut self.buffer } fn available_mut(&mut self) -> &mut [u8] { &mut self.buffer[self.pos..self.cap] } fn consume(&mut self, n: usize) { self.pos = std::cmp::min(self.pos + n, self.cap); } fn needs_fill(&self) -> bool { self.pos >= self.cap } } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum IpcJsonStreamError { #[class(inherit)] #[error("{0}")] Io(#[source] std::io::Error), #[class(generic)] #[error("{0}")] SimdJson(#[source] simd_json::Error), } #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum IpcAdvancedStreamError { #[class(inherit)] #[error("{0}")] Io(#[source] std::io::Error), } pub struct IpcAdvancedStream { pipe: BiPipeRead, read_buffer: ReadBuffer, } struct MessageLengthBuffer { buffer: [u8; 4], pos: u8, value: u32, } impl MessageLengthBuffer { fn new() -> Self { Self { buffer: [0; 4], pos: 0, value: 0, } } fn message_len(&mut self) -> Option<usize> { if self.pos == 4 { self.value = u32::from_be_bytes(self.buffer); self.pos = 5; Some(self.value as usize) } else if self.pos == 5 { Some(self.value as usize) } else { None } } fn update_pos_by(&mut self, num: usize) { self.pos = (self.pos + num as u8).min(4); } fn available_mut(&mut self) -> &mut [u8] { &mut self.buffer[self.pos as usize..4] } } pin_project! { #[must_use = "futures do nothing unless you `.await` or poll them"] struct ReadMsgBytesInner<'a, R: ?Sized> { length_buffer: &'a mut MessageLengthBuffer, reader: &'a mut R, out_buf: &'a mut Vec<u8>, // The number of bytes appended to buf. This can be less than buf.len() if // the buffer was not empty when the operation was started. read: usize, read_buffer: &'a mut ReadBuffer, } } fn read_msg_bytes_inner<'a, R: AsyncRead + ?Sized + Unpin>( reader: &'a mut R, length_buffer: &'a mut MessageLengthBuffer, out_buf: &'a mut Vec<u8>, read: usize, read_buffer: &'a mut ReadBuffer, ) -> ReadMsgBytesInner<'a, R> { ReadMsgBytesInner { length_buffer, reader, out_buf, read, read_buffer, } } impl IpcAdvancedStream { fn new(pipe: BiPipeRead) -> Self { Self { pipe, read_buffer: ReadBuffer::new(), } } pub async fn read_msg_bytes( &mut self, ) -> Result<Option<Vec<u8>>, IpcAdvancedStreamError> { let mut length_buffer = MessageLengthBuffer::new(); let mut out_buf = Vec::with_capacity(32); let nread = read_msg_bytes_inner( &mut self.pipe, &mut length_buffer, &mut out_buf, 0, &mut self.read_buffer, ) .await .map_err(IpcAdvancedStreamError::Io)?; if nread == 0 { return Ok(None); } Ok(Some(std::mem::take(&mut out_buf))) } } impl<R: AsyncRead + ?Sized + Unpin> Future for ReadMsgBytesInner<'_, R> { type Output = io::Result<usize>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let me = self.project(); read_advanced_msg_bytes_internal( Pin::new(me.reader), cx, me.length_buffer, me.read_buffer, me.out_buf, me.read, ) } } pub struct IpcAdvancedStreamResource { pub read_half: AsyncRefCell<IpcAdvancedStream>, pub write_half: AsyncRefCell<BiPipeWrite>, pub cancel: Rc<CancelHandle>, pub queued_bytes: AtomicUsize, pub ref_tracker: IpcRefTracker, } impl IpcAdvancedStreamResource { pub fn new( stream: i64, ref_tracker: IpcRefTracker, ) -> Result<Self, std::io::Error> { let (read_half, write_half) = BiPipe::from_raw(stream as _)?.split(); Ok(Self { read_half: AsyncRefCell::new(IpcAdvancedStream::new(read_half)), write_half: AsyncRefCell::new(write_half), cancel: Default::default(), queued_bytes: Default::default(), ref_tracker, }) } /// writes serialized message to the IPC pipe. the first 4 bytes must be the length of the following message. pub async fn write_msg_bytes( self: Rc<Self>, msg: &[u8], ) -> Result<(), io::Error> { let mut write_half = RcRef::map(self, |r| &r.write_half).borrow_mut().await; write_half.write_all(msg).await?; Ok(()) } } impl deno_core::Resource for IpcAdvancedStreamResource { fn close(self: Rc<Self>) { self.cancel.cancel(); } } fn read_advanced_msg_bytes_internal<R: AsyncRead + ?Sized>( mut reader: Pin<&mut R>, cx: &mut Context<'_>, length_buffer: &mut MessageLengthBuffer, read_buffer: &mut ReadBuffer, out_buffer: &mut Vec<u8>, read: &mut usize, ) -> Poll<io::Result<usize>> { loop { if read_buffer.needs_fill() { let mut read_buf = ReadBuf::new(read_buffer.get_mut()); ready!(reader.as_mut().poll_read(cx, &mut read_buf))?; read_buffer.cap = read_buf.filled().len(); read_buffer.pos = 0; } let available = read_buffer.available_mut(); let msg_len = length_buffer.message_len(); let (done, used) = if let Some(msg_len) = msg_len { if out_buffer.len() >= msg_len { (true, 0) } else if available.is_empty() { if *read == 0 { return Poll::Ready(Ok(0)); } else { return Poll::Ready(Err(io::Error::new( io::ErrorKind::UnexpectedEof, "ipc stream closed while reading message", ))); } } else { let remaining = msg_len - out_buffer.len(); out_buffer.reserve(remaining); let to_copy = available.len().min(remaining); out_buffer.extend_from_slice(&available[..to_copy]); (out_buffer.len() == msg_len, to_copy) } } else { if available.is_empty() { if *read == 0 { return Poll::Ready(Ok(0)); } else { return Poll::Ready(Err(io::Error::new( io::ErrorKind::UnexpectedEof, "ipc stream closed before message length", ))); } } let len_avail = length_buffer.available_mut(); let to_copy = available.len().min(len_avail.len()); len_avail[..to_copy].copy_from_slice(&available[..to_copy]); length_buffer.update_pos_by(to_copy); (false, to_copy) }; read_buffer.consume(used); *read += used; if done || *read == 0 { return Poll::Ready(Ok(mem::replace(read, 0))); } } } // JSON serialization stream over IPC pipe. // // `\n` is used as a delimiter between messages. pub struct IpcJsonStream { pipe: BiPipeRead, buffer: Vec<u8>, read_buffer: ReadBuffer, } impl IpcJsonStream { fn new(pipe: BiPipeRead) -> Self { Self { pipe, buffer: Vec::with_capacity(INITIAL_CAPACITY), read_buffer: ReadBuffer::new(), } } pub async fn read_msg( &mut self, ) -> Result<Option<serde_json::Value>, IpcJsonStreamError> { let mut json = None; let nread = read_msg_inner( &mut self.pipe, &mut self.buffer, &mut json, &mut self.read_buffer, ) .await .map_err(IpcJsonStreamError::Io)?; if nread == 0 { // EOF. return Ok(None); } let json = match json { Some(v) => v, None => { // Took more than a single read and some buffering. simd_json::from_slice(&mut self.buffer[..nread]) .map_err(IpcJsonStreamError::SimdJson)? } }; // Safety: Same as `Vec::clear` but without the `drop_in_place` for // each element (nop for u8). Capacity remains the same. unsafe { self.buffer.set_len(0); } Ok(Some(json)) } } pin_project! { #[must_use = "futures do nothing unless you `.await` or poll them"] struct ReadMsgInner<'a, R: ?Sized> { reader: &'a mut R, buf: &'a mut Vec<u8>, json: &'a mut Option<serde_json::Value>, // The number of bytes appended to buf. This can be less than buf.len() if // the buffer was not empty when the operation was started. read: usize, read_buffer: &'a mut ReadBuffer, } } fn read_msg_inner<'a, R>( reader: &'a mut R, buf: &'a mut Vec<u8>, json: &'a mut Option<serde_json::Value>, read_buffer: &'a mut ReadBuffer, ) -> ReadMsgInner<'a, R> where R: AsyncRead + ?Sized + Unpin, { ReadMsgInner { reader, buf, json, read: 0, read_buffer, } } fn read_json_msg_internal<R: AsyncRead + ?Sized>( mut reader: Pin<&mut R>, cx: &mut Context<'_>, buf: &mut Vec<u8>, read_buffer: &mut ReadBuffer, json: &mut Option<serde_json::Value>, read: &mut usize, ) -> Poll<io::Result<usize>> { loop { let (done, used) = { // effectively a tiny `poll_fill_buf`, but allows us to get a mutable reference to the buffer. if read_buffer.needs_fill() { let mut read_buf = ReadBuf::new(read_buffer.get_mut()); ready!(reader.as_mut().poll_read(cx, &mut read_buf))?; read_buffer.cap = read_buf.filled().len(); read_buffer.pos = 0; } let available = read_buffer.available_mut(); if let Some(i) = memchr(b'\n', available) { if *read == 0 { // Fast path: parse and put into the json slot directly. json.replace( simd_json::from_slice(&mut available[..i + 1]) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?, ); } else { // This is not the first read, so we have to copy the data // to make it contiguous. buf.extend_from_slice(&available[..=i]); } (true, i + 1) } else { buf.extend_from_slice(available); (false, available.len()) } }; read_buffer.consume(used); *read += used; if done || used == 0 { return Poll::Ready(Ok(mem::replace(read, 0))); } } } impl<R: AsyncRead + ?Sized + Unpin> Future for ReadMsgInner<'_, R> { type Output = io::Result<usize>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let me = self.project(); read_json_msg_internal( Pin::new(*me.reader), cx, me.buf, me.read_buffer, me.json, me.read, ) } } #[cfg(test)] mod tests { use std::rc::Rc; use deno_core::RcRef; use deno_core::serde_json::json; use super::IpcJsonStreamResource; #[allow(clippy::unused_async)] #[cfg(unix)] pub async fn pair() -> (Rc<IpcJsonStreamResource>, tokio::net::UnixStream) { let (a, b) = tokio::net::UnixStream::pair().unwrap(); /* Similar to how ops would use the resource */ let a = Rc::new(IpcJsonStreamResource::from_stream( a, super::IpcRefTracker::new_test(), )); (a, b) } #[cfg(windows)] pub async fn pair() -> ( Rc<IpcJsonStreamResource>, tokio::net::windows::named_pipe::NamedPipeServer, ) { use tokio::net::windows::named_pipe::ClientOptions; use tokio::net::windows::named_pipe::ServerOptions; let name = format!(r"\\.\pipe\deno-named-pipe-test-{}", rand::random::<u32>()); let server = ServerOptions::new().create(name.clone()).unwrap(); let client = ClientOptions::new().open(name).unwrap(); server.connect().await.unwrap(); /* Similar to how ops would use the resource */ let client = Rc::new(IpcJsonStreamResource::from_stream( client, super::IpcRefTracker::new_test(), )); (client, server) } #[allow(clippy::print_stdout)] #[tokio::test] async fn bench_ipc() -> Result<(), Box<dyn std::error::Error>> { // A simple round trip benchmark for quick dev feedback. // // Only ran when the env var is set. if std::env::var_os("BENCH_IPC_DENO").is_none() { return Ok(()); } let (ipc, mut fd2) = pair().await; let child = tokio::spawn(async move { use tokio::io::AsyncWriteExt; let size = 1024 * 1024; let stri = "x".repeat(size); let data = format!("\"{}\"\n", stri); for _ in 0..100 { fd2.write_all(data.as_bytes()).await?; } Ok::<_, std::io::Error>(()) }); let start = std::time::Instant::now(); let mut bytes = 0; let mut ipc = RcRef::map(ipc, |r| &r.read_half).borrow_mut().await; loop { let Some(msgs) = ipc.read_msg().await? else { break; }; bytes += msgs.as_str().unwrap().len(); if start.elapsed().as_secs() > 5 { break; } } let elapsed = start.elapsed(); let mb = bytes as f64 / 1024.0 / 1024.0; println!("{} mb/s", mb / elapsed.as_secs_f64()); child.await??; Ok(()) } #[tokio::test] async fn unix_ipc_json() -> Result<(), Box<dyn std::error::Error>> { let (ipc, mut fd2) = pair().await; let child = tokio::spawn(async move { use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; const EXPECTED: &[u8] = b"\"hello\"\n"; let mut buf = [0u8; EXPECTED.len()]; let n = fd2.read_exact(&mut buf).await?; assert_eq!(&buf[..n], EXPECTED); fd2.write_all(b"\"world\"\n").await?; Ok::<_, std::io::Error>(()) }); ipc .clone() .write_msg_bytes(&json_to_bytes(json!("hello"))) .await?; let mut ipc = RcRef::map(ipc, |r| &r.read_half).borrow_mut().await; let msgs = ipc.read_msg().await?.unwrap(); assert_eq!(msgs, json!("world")); child.await??; Ok(()) } fn json_to_bytes(v: deno_core::serde_json::Value) -> Vec<u8> { let mut buf = deno_core::serde_json::to_vec(&v).unwrap(); buf.push(b'\n'); buf } #[tokio::test] async fn unix_ipc_json_multi() -> Result<(), Box<dyn std::error::Error>> { let (ipc, mut fd2) = pair().await; let child = tokio::spawn(async move { use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; const EXPECTED: &[u8] = b"\"hello\"\n\"world\"\n"; let mut buf = [0u8; EXPECTED.len()]; let n = fd2.read_exact(&mut buf).await?; assert_eq!(&buf[..n], EXPECTED); fd2.write_all(b"\"foo\"\n\"bar\"\n").await?; Ok::<_, std::io::Error>(()) }); ipc .clone() .write_msg_bytes(&json_to_bytes(json!("hello"))) .await?; ipc .clone() .write_msg_bytes(&json_to_bytes(json!("world"))) .await?; let mut ipc = RcRef::map(ipc, |r| &r.read_half).borrow_mut().await; let msgs = ipc.read_msg().await?.unwrap(); assert_eq!(msgs, json!("foo")); child.await??; Ok(()) } #[tokio::test] async fn unix_ipc_json_invalid() -> Result<(), Box<dyn std::error::Error>> { let (ipc, mut fd2) = pair().await; let child = tokio::spawn(async move { tokio::io::AsyncWriteExt::write_all(&mut fd2, b"\n\n").await?; Ok::<_, std::io::Error>(()) }); let mut ipc = RcRef::map(ipc, |r| &r.read_half).borrow_mut().await; let _err = ipc.read_msg().await.unwrap_err(); child.await??; Ok(()) } #[test] fn memchr() { let str = b"hello world"; assert_eq!(super::memchr(b'h', str), Some(0)); assert_eq!(super::memchr(b'w', str), Some(6)); assert_eq!(super::memchr(b'd', str), Some(10)); assert_eq!(super::memchr(b'x', str), None); let empty = b""; assert_eq!(super::memchr(b'\n', empty), None); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/tls/lib.rs
ext/tls/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::io::BufRead; use std::io::BufReader; use std::io::Cursor; use std::net::IpAddr; use std::sync::Arc; use deno_error::JsErrorBox; pub use deno_native_certs; pub use rustls; use rustls::ClientConfig; use rustls::DigitallySignedStruct; use rustls::RootCertStore; use rustls::client::WebPkiServerVerifier; use rustls::client::danger::HandshakeSignatureValid; use rustls::client::danger::ServerCertVerified; use rustls::client::danger::ServerCertVerifier; use rustls::pki_types::CertificateDer; use rustls::pki_types::PrivateKeyDer; use rustls::pki_types::ServerName; pub use rustls_pemfile; use rustls_pemfile::certs; use rustls_pemfile::ec_private_keys; use rustls_pemfile::pkcs8_private_keys; use rustls_pemfile::rsa_private_keys; pub use rustls_tokio_stream::*; use serde::Deserialize; pub use webpki; pub use webpki_roots; mod tls_key; pub use tls_key::*; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum TlsError { #[class(generic)] #[error(transparent)] Rustls(#[from] rustls::Error), #[class(inherit)] #[error("Unable to add pem file to certificate store: {0}")] UnableAddPemFileToCert(std::io::Error), #[class("InvalidData")] #[error("Unable to decode certificate")] CertInvalid, #[class("InvalidData")] #[error("No certificates found in certificate data")] CertsNotFound, #[class("InvalidData")] #[error("No keys found in key data")] KeysNotFound, #[class("InvalidData")] #[error("Unable to decode key")] KeyDecode, } /// Lazily resolves the root cert store. /// /// This was done because the root cert store is not needed in all cases /// and takes a bit of time to initialize. pub trait RootCertStoreProvider: Send + Sync { fn get_or_try_init(&self) -> Result<&RootCertStore, JsErrorBox>; } // This extension has no runtime apis, it only exports some shared native functions. deno_core::extension!(deno_tls); #[derive(Debug)] pub struct NoCertificateVerification { pub ic_allowlist: Vec<String>, default_verifier: Arc<WebPkiServerVerifier>, } impl NoCertificateVerification { pub fn new(ic_allowlist: Vec<String>) -> Self { Self { ic_allowlist, default_verifier: WebPkiServerVerifier::builder( create_default_root_cert_store().into(), ) .build() .unwrap(), } } } impl ServerCertVerifier for NoCertificateVerification { fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> { self.default_verifier.supported_verify_schemes() } fn verify_server_cert( &self, end_entity: &rustls::pki_types::CertificateDer<'_>, intermediates: &[rustls::pki_types::CertificateDer<'_>], server_name: &rustls::pki_types::ServerName<'_>, ocsp_response: &[u8], now: rustls::pki_types::UnixTime, ) -> Result<ServerCertVerified, rustls::Error> { if self.ic_allowlist.is_empty() { return Ok(ServerCertVerified::assertion()); } let dns_name_or_ip_address = match server_name { ServerName::DnsName(dns_name) => dns_name.as_ref().to_owned(), ServerName::IpAddress(ip_address) => { Into::<IpAddr>::into(*ip_address).to_string() } _ => { // NOTE(bartlomieju): `ServerName` is a non-exhaustive enum // so we have this catch all errors here. return Err(rustls::Error::General( "Unknown `ServerName` variant".to_string(), )); } }; if self.ic_allowlist.contains(&dns_name_or_ip_address) { Ok(ServerCertVerified::assertion()) } else { self.default_verifier.verify_server_cert( end_entity, intermediates, server_name, ocsp_response, now, ) } } fn verify_tls12_signature( &self, message: &[u8], cert: &rustls::pki_types::CertificateDer, dss: &DigitallySignedStruct, ) -> Result<HandshakeSignatureValid, rustls::Error> { if self.ic_allowlist.is_empty() { return Ok(HandshakeSignatureValid::assertion()); } filter_invalid_encoding_err( self .default_verifier .verify_tls12_signature(message, cert, dss), ) } fn verify_tls13_signature( &self, message: &[u8], cert: &rustls::pki_types::CertificateDer, dss: &DigitallySignedStruct, ) -> Result<HandshakeSignatureValid, rustls::Error> { if self.ic_allowlist.is_empty() { return Ok(HandshakeSignatureValid::assertion()); } filter_invalid_encoding_err( self .default_verifier .verify_tls13_signature(message, cert, dss), ) } } #[derive(Debug)] pub struct NoServerNameVerification { inner: Arc<WebPkiServerVerifier>, } impl NoServerNameVerification { pub fn new(inner: Arc<WebPkiServerVerifier>) -> Self { Self { inner } } } impl ServerCertVerifier for NoServerNameVerification { fn verify_server_cert( &self, end_entity: &CertificateDer<'_>, intermediates: &[CertificateDer<'_>], server_name: &ServerName<'_>, ocsp: &[u8], now: rustls::pki_types::UnixTime, ) -> Result<ServerCertVerified, rustls::Error> { match self.inner.verify_server_cert( end_entity, intermediates, server_name, ocsp, now, ) { Ok(scv) => Ok(scv), Err(rustls::Error::InvalidCertificate(cert_error)) => { if matches!( cert_error, rustls::CertificateError::NotValidForName | rustls::CertificateError::NotValidForNameContext { .. } ) { Ok(ServerCertVerified::assertion()) } else { Err(rustls::Error::InvalidCertificate(cert_error)) } } Err(e) => Err(e), } } fn verify_tls12_signature( &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct, ) -> Result<HandshakeSignatureValid, rustls::Error> { self.inner.verify_tls12_signature(message, cert, dss) } fn verify_tls13_signature( &self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct, ) -> Result<HandshakeSignatureValid, rustls::Error> { self.inner.verify_tls13_signature(message, cert, dss) } fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> { self.inner.supported_verify_schemes() } } #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase", tag = "transport")] pub enum Proxy { #[serde(rename_all = "camelCase")] Http { url: String, basic_auth: Option<BasicAuth>, }, Tcp { hostname: String, port: u16, }, Unix { path: String, }, Vsock { cid: u32, port: u32, }, } #[derive(Deserialize, Default, Debug, Clone)] #[serde(default)] pub struct BasicAuth { pub username: String, pub password: String, } pub fn create_default_root_cert_store() -> RootCertStore { let root_cert_store = rustls::RootCertStore { roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(), }; debug_assert!(!root_cert_store.is_empty()); root_cert_store } #[derive(Default)] pub enum SocketUse { /// General SSL: No ALPN #[default] GeneralSsl, /// HTTP: h1 and h2 Http, /// http/1.1 only Http1Only, /// http/2 only Http2Only, } #[derive(Default)] pub struct TlsClientConfigOptions { pub root_cert_store: Option<RootCertStore>, pub ca_certs: Vec<Vec<u8>>, pub unsafely_ignore_certificate_errors: Option<Vec<String>>, pub unsafely_disable_hostname_verification: bool, pub cert_chain_and_key: TlsKeys, pub socket_use: SocketUse, } pub fn create_client_config( options: TlsClientConfigOptions, ) -> Result<ClientConfig, TlsError> { let TlsClientConfigOptions { root_cert_store, ca_certs, unsafely_ignore_certificate_errors, unsafely_disable_hostname_verification, cert_chain_and_key: maybe_cert_chain_and_key, socket_use, } = options; if let Some(ic_allowlist) = unsafely_ignore_certificate_errors { let client_config = ClientConfig::builder() .dangerous() .with_custom_certificate_verifier(Arc::new( NoCertificateVerification::new(ic_allowlist), )); // NOTE(bartlomieju): this if/else is duplicated at the end of the body of this function. // However it's not really feasible to deduplicate it as the `client_config` instances // are not type-compatible - one wants "client cert", the other wants "transparency policy // or client cert". let mut client = match maybe_cert_chain_and_key { TlsKeys::Static(TlsKey(cert_chain, private_key)) => client_config .with_client_auth_cert(cert_chain, private_key.clone_key()) .expect("invalid client key or certificate"), TlsKeys::Null => client_config.with_no_client_auth(), TlsKeys::Resolver(_) => unimplemented!(), }; add_alpn(&mut client, socket_use); return Ok(client); } let mut root_cert_store = root_cert_store.unwrap_or_else(create_default_root_cert_store); // If custom certs are specified, add them to the store for cert in ca_certs { let reader = &mut BufReader::new(Cursor::new(cert)); // This function does not return specific errors, if it fails give a generic message. for r in rustls_pemfile::certs(reader) { match r { Ok(cert) => { root_cert_store.add(cert)?; } Err(e) => { return Err(TlsError::UnableAddPemFileToCert(e)); } } } } let client_config = ClientConfig::builder().with_root_certificates(root_cert_store.clone()); let mut client = match maybe_cert_chain_and_key { TlsKeys::Static(TlsKey(cert_chain, private_key)) => client_config .with_client_auth_cert(cert_chain, private_key.clone_key()) .expect("invalid client key or certificate"), TlsKeys::Null => client_config.with_no_client_auth(), TlsKeys::Resolver(_) => unimplemented!(), }; add_alpn(&mut client, socket_use); if unsafely_disable_hostname_verification { let inner = rustls::client::WebPkiServerVerifier::builder(Arc::new(root_cert_store)) .build() .expect("Failed to create WebPkiServerVerifier"); let verifier = Arc::new(NoServerNameVerification::new(inner)); client.dangerous().set_certificate_verifier(verifier); } Ok(client) } fn add_alpn(client: &mut ClientConfig, socket_use: SocketUse) { match socket_use { SocketUse::Http1Only => { client.alpn_protocols = vec!["http/1.1".into()]; } SocketUse::Http2Only => { client.alpn_protocols = vec!["h2".into()]; } SocketUse::Http => { client.alpn_protocols = vec!["h2".into(), "http/1.1".into()]; } SocketUse::GeneralSsl => {} }; } pub fn load_certs( reader: &mut dyn BufRead, ) -> Result<Vec<CertificateDer<'static>>, TlsError> { let certs: Result<Vec<_>, _> = certs(reader).collect(); let certs = certs.map_err(|_| TlsError::CertInvalid)?; if certs.is_empty() { return Err(TlsError::CertsNotFound); } Ok(certs) } /// Starts with -----BEGIN RSA PRIVATE KEY----- fn load_rsa_keys( mut bytes: &[u8], ) -> Result<Vec<PrivateKeyDer<'static>>, TlsError> { let keys: Result<Vec<_>, _> = rsa_private_keys(&mut bytes).collect(); let keys = keys.map_err(|_| TlsError::KeyDecode)?; Ok(keys.into_iter().map(PrivateKeyDer::Pkcs1).collect()) } /// Starts with -----BEGIN EC PRIVATE KEY----- fn load_ec_keys( mut bytes: &[u8], ) -> Result<Vec<PrivateKeyDer<'static>>, TlsError> { let keys: Result<Vec<_>, std::io::Error> = ec_private_keys(&mut bytes).collect(); let keys2 = keys.map_err(|_| TlsError::KeyDecode)?; Ok(keys2.into_iter().map(PrivateKeyDer::Sec1).collect()) } /// Starts with -----BEGIN PRIVATE KEY----- fn load_pkcs8_keys( mut bytes: &[u8], ) -> Result<Vec<PrivateKeyDer<'static>>, TlsError> { let keys: Result<Vec<_>, std::io::Error> = pkcs8_private_keys(&mut bytes).collect(); let keys2 = keys.map_err(|_| TlsError::KeyDecode)?; Ok(keys2.into_iter().map(PrivateKeyDer::Pkcs8).collect()) } fn filter_invalid_encoding_err( to_be_filtered: Result<HandshakeSignatureValid, rustls::Error>, ) -> Result<HandshakeSignatureValid, rustls::Error> { match to_be_filtered { Err(rustls::Error::InvalidCertificate( rustls::CertificateError::BadEncoding, )) => Ok(HandshakeSignatureValid::assertion()), res => res, } } pub fn load_private_keys( bytes: &[u8], ) -> Result<Vec<PrivateKeyDer<'static>>, TlsError> { let mut keys = load_rsa_keys(bytes)?; if keys.is_empty() { keys = load_pkcs8_keys(bytes)?; } if keys.is_empty() { keys = load_ec_keys(bytes)?; } if keys.is_empty() { return Err(TlsError::KeysNotFound); } Ok(keys) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/tls/tls_key.rs
ext/tls/tls_key.rs
// Copyright 2018-2025 the Deno authors. MIT license. //! These represent the various types of TLS keys we support for both client and server //! connections. //! //! A TLS key will most often be static, and will loaded from a certificate and key file //! or string. These are represented by `TlsKey`, which is stored in `TlsKeys::Static`. //! //! In more complex cases, you may need a `TlsKeyResolver`/`TlsKeyLookup` pair, which //! requires polling of the `TlsKeyLookup` lookup queue. The underlying channels that used for //! key lookup can handle closing one end of the pair, in which case they will just //! attempt to clean up the associated resources. use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Debug; use std::future::Future; use std::future::poll_fn; use std::future::ready; use std::io::ErrorKind; use std::rc::Rc; use std::sync::Arc; use deno_core::futures::FutureExt; use deno_core::futures::future::Either; use deno_core::unsync::spawn; use rustls::ServerConfig; use rustls_tokio_stream::ServerConfigProvider; use tokio::sync::broadcast; use tokio::sync::mpsc; use tokio::sync::oneshot; use webpki::types::CertificateDer; use webpki::types::PrivateKeyDer; #[derive(Debug, thiserror::Error)] pub enum TlsKeyError { #[error(transparent)] Rustls(#[from] rustls::Error), #[error("Failed: {0}")] Failed(ErrorType), #[error(transparent)] JoinError(#[from] tokio::task::JoinError), #[error(transparent)] RecvError(#[from] tokio::sync::broadcast::error::RecvError), } type ErrorType = Arc<Box<str>>; /// A TLS certificate/private key pair. /// see https://docs.rs/rustls-pki-types/latest/rustls_pki_types/#cloning-private-keys #[derive(Debug, PartialEq, Eq)] pub struct TlsKey(pub Vec<CertificateDer<'static>>, pub PrivateKeyDer<'static>); impl Clone for TlsKey { fn clone(&self) -> Self { Self(self.0.clone(), self.1.clone_key()) } } #[derive(Clone, Debug, Default)] pub enum TlsKeys { // TODO(mmastrac): We need Option<&T> for cppgc -- this is a workaround #[default] Null, Static(TlsKey), Resolver(TlsKeyResolver), } pub struct TlsKeysHolder(RefCell<TlsKeys>); // SAFETY: we're sure `TlsKeysHolder` can be GCed unsafe impl deno_core::GarbageCollected for TlsKeysHolder { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"TlsKeyHolder" } } impl TlsKeysHolder { pub fn take(&self) -> TlsKeys { std::mem::take(&mut *self.0.borrow_mut()) } } impl From<TlsKeys> for TlsKeysHolder { fn from(value: TlsKeys) -> Self { TlsKeysHolder(RefCell::new(value)) } } impl TryInto<Option<TlsKey>> for TlsKeys { type Error = Self; fn try_into(self) -> Result<Option<TlsKey>, Self::Error> { match self { Self::Null => Ok(None), Self::Static(key) => Ok(Some(key)), Self::Resolver(_) => Err(self), } } } impl From<Option<TlsKey>> for TlsKeys { fn from(value: Option<TlsKey>) -> Self { match value { None => TlsKeys::Null, Some(key) => TlsKeys::Static(key), } } } enum TlsKeyState { Resolving(broadcast::Receiver<Result<TlsKey, ErrorType>>), Resolved(Result<TlsKey, ErrorType>), } struct TlsKeyResolverInner { resolution_tx: mpsc::UnboundedSender<( String, broadcast::Sender<Result<TlsKey, ErrorType>>, )>, cache: RefCell<HashMap<String, TlsKeyState>>, } #[derive(Clone)] pub struct TlsKeyResolver { inner: Rc<TlsKeyResolverInner>, } impl TlsKeyResolver { async fn resolve_internal( &self, sni: String, alpn: Vec<Vec<u8>>, ) -> Result<Arc<ServerConfig>, TlsKeyError> { let key = self.resolve(sni).await?; let mut tls_config = ServerConfig::builder() .with_no_client_auth() .with_single_cert(key.0, key.1.clone_key())?; tls_config.alpn_protocols = alpn; Ok(tls_config.into()) } pub fn into_server_config_provider( self, alpn: Vec<Vec<u8>>, ) -> ServerConfigProvider { let (tx, mut rx) = mpsc::unbounded_channel::<(_, oneshot::Sender<_>)>(); // We don't want to make the resolver multi-threaded, but the `ServerConfigProvider` is // required to be wrapped in an Arc. To fix this, we spawn a task in our current runtime // to respond to the requests. spawn(async move { while let Some((sni, txr)) = rx.recv().await { _ = txr.send(self.resolve_internal(sni, alpn.clone()).await); } }); Arc::new(move |hello| { // Take ownership of the SNI information let sni = hello.server_name().unwrap_or_default().to_owned(); let (txr, rxr) = tokio::sync::oneshot::channel::<_>(); _ = tx.send((sni, txr)); rxr .map(|res| match res { Err(e) => Err(std::io::Error::new(ErrorKind::InvalidData, e)), Ok(Err(e)) => Err(std::io::Error::new(ErrorKind::InvalidData, e)), Ok(Ok(res)) => Ok(res), }) .boxed() }) } } impl Debug for TlsKeyResolver { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("TlsKeyResolver").finish() } } pub fn new_resolver() -> (TlsKeyResolver, TlsKeyLookup) { let (resolution_tx, resolution_rx) = mpsc::unbounded_channel(); ( TlsKeyResolver { inner: Rc::new(TlsKeyResolverInner { resolution_tx, cache: Default::default(), }), }, TlsKeyLookup { resolution_rx: RefCell::new(resolution_rx), pending: Default::default(), }, ) } impl TlsKeyResolver { /// Resolve the certificate and key for a given host. This immediately spawns a task in the /// background and is therefore cancellation-safe. pub fn resolve( &self, sni: String, ) -> impl Future<Output = Result<TlsKey, TlsKeyError>> + use<> { let mut cache = self.inner.cache.borrow_mut(); let mut recv = match cache.get(&sni) { None => { let (tx, rx) = broadcast::channel(1); cache.insert(sni.clone(), TlsKeyState::Resolving(rx.resubscribe())); _ = self.inner.resolution_tx.send((sni.clone(), tx)); rx } Some(TlsKeyState::Resolving(recv)) => recv.resubscribe(), Some(TlsKeyState::Resolved(res)) => { return Either::Left(ready(res.clone().map_err(TlsKeyError::Failed))); } }; drop(cache); // Make this cancellation safe let inner = self.inner.clone(); let handle = spawn(async move { let res = recv.recv().await?; let mut cache = inner.cache.borrow_mut(); match cache.get(&sni) { None | Some(TlsKeyState::Resolving(..)) => { cache.insert(sni, TlsKeyState::Resolved(res.clone())); } Some(TlsKeyState::Resolved(..)) => { // Someone beat us to it } } res.map_err(TlsKeyError::Failed) }); Either::Right(async move { handle.await? }) } } pub struct TlsKeyLookup { #[allow(clippy::type_complexity)] resolution_rx: RefCell< mpsc::UnboundedReceiver<( String, broadcast::Sender<Result<TlsKey, ErrorType>>, )>, >, pending: RefCell<HashMap<String, broadcast::Sender<Result<TlsKey, ErrorType>>>>, } // SAFETY: we're sure `TlsKeyLookup` can be GCed unsafe impl deno_core::GarbageCollected for TlsKeyLookup { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"TlsKeyLookup" } } impl TlsKeyLookup { /// Multiple `poll` calls are safe, but this method is not starvation-safe. Generally /// only one `poll`er should be active at any time. pub async fn poll(&self) -> Option<String> { match poll_fn(|cx| self.resolution_rx.borrow_mut().poll_recv(cx)).await { Some((sni, sender)) => { self.pending.borrow_mut().insert(sni.clone(), sender); Some(sni) } _ => None, } } /// Resolve a previously polled item. pub fn resolve(&self, sni: String, res: Result<TlsKey, String>) { _ = self .pending .borrow_mut() .remove(&sni) .unwrap() .send(res.map_err(|e| Arc::new(e.into_boxed_str()))); } } #[cfg(test)] pub mod tests { use deno_core::unsync::spawn; use super::*; fn tls_key_for_test(sni: &str) -> TlsKey { let manifest_dir = std::path::PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap()); let sni = sni.replace(".com", ""); let cert_file = manifest_dir.join(format!("testdata/{}_cert.der", sni)); let prikey_file = manifest_dir.join(format!("testdata/{}_prikey.der", sni)); let cert = std::fs::read(cert_file).unwrap(); let prikey = std::fs::read(prikey_file).unwrap(); let cert = CertificateDer::from(cert); let prikey = PrivateKeyDer::try_from(prikey).unwrap(); TlsKey(vec![cert], prikey) } #[tokio::test] async fn test_resolve_once() { let (resolver, lookup) = new_resolver(); let task = spawn(async move { while let Some(sni) = lookup.poll().await { lookup.resolve(sni.clone(), Ok(tls_key_for_test(&sni))); } }); let key = resolver.resolve("example1.com".to_owned()).await.unwrap(); assert_eq!(tls_key_for_test("example1.com"), key); drop(resolver); task.await.unwrap(); } #[tokio::test] async fn test_resolve_concurrent() { let (resolver, lookup) = new_resolver(); let task = spawn(async move { while let Some(sni) = lookup.poll().await { lookup.resolve(sni.clone(), Ok(tls_key_for_test(&sni))); } }); let f1 = resolver.resolve("example1.com".to_owned()); let f2 = resolver.resolve("example1.com".to_owned()); let key = f1.await.unwrap(); assert_eq!(tls_key_for_test("example1.com"), key); let key = f2.await.unwrap(); assert_eq!(tls_key_for_test("example1.com"), key); drop(resolver); task.await.unwrap(); } #[tokio::test] async fn test_resolve_multiple_concurrent() { let (resolver, lookup) = new_resolver(); let task = spawn(async move { while let Some(sni) = lookup.poll().await { lookup.resolve(sni.clone(), Ok(tls_key_for_test(&sni))); } }); let f1 = resolver.resolve("example1.com".to_owned()); let f2 = resolver.resolve("example2.com".to_owned()); let key = f1.await.unwrap(); assert_eq!(tls_key_for_test("example1.com"), key); let key = f2.await.unwrap(); assert_eq!(tls_key_for_test("example2.com"), key); drop(resolver); task.await.unwrap(); } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/webstorage/lib.rs
ext/webstorage/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. // NOTE to all: use **cached** prepared statements when interfacing with SQLite. use std::path::PathBuf; use deno_core::GarbageCollected; use deno_core::OpState; use deno_core::op2; pub use rusqlite; use rusqlite::Connection; use rusqlite::OptionalExtension; use rusqlite::params; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum WebStorageError { #[class("DOMExceptionNotSupportedError")] #[error("LocalStorage is not supported in this context.")] ContextNotSupported, #[class(generic)] #[error(transparent)] Sqlite(#[from] rusqlite::Error), #[class(inherit)] #[error(transparent)] Io(std::io::Error), #[class("DOMExceptionQuotaExceededError")] #[error("Exceeded maximum storage size")] StorageExceeded, } #[derive(Clone)] struct OriginStorageDir(PathBuf); const MAX_STORAGE_BYTES: usize = 10 * 1024 * 1024; deno_core::extension!(deno_webstorage, deps = [ deno_webidl ], ops = [ op_webstorage_iterate_keys, ], objects = [ Storage ], esm = [ "01_webstorage.js" ], options = { origin_storage_dir: Option<PathBuf> }, state = |state, options| { if let Some(origin_storage_dir) = options.origin_storage_dir { state.put(OriginStorageDir(origin_storage_dir)); } }, ); struct LocalStorage(Connection); struct SessionStorage(Connection); fn get_webstorage( state: &mut OpState, persistent: bool, ) -> Result<&Connection, WebStorageError> { let conn = if persistent { if state.try_borrow::<LocalStorage>().is_none() { let path = state .try_borrow::<OriginStorageDir>() .ok_or(WebStorageError::ContextNotSupported)?; std::fs::create_dir_all(&path.0).map_err(WebStorageError::Io)?; let conn = Connection::open(path.0.join("local_storage"))?; // Enable write-ahead-logging and tweak some other stuff. let initial_pragmas = " -- enable write-ahead-logging mode PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA temp_store=memory; PRAGMA page_size=4096; PRAGMA mmap_size=6000000; PRAGMA optimize; "; conn.execute_batch(initial_pragmas)?; conn.set_prepared_statement_cache_capacity(128); { let mut stmt = conn.prepare_cached( "CREATE TABLE IF NOT EXISTS data (key VARCHAR UNIQUE, value VARCHAR)", )?; stmt.execute(params![])?; } state.put(LocalStorage(conn)); } &state.borrow::<LocalStorage>().0 } else { if state.try_borrow::<SessionStorage>().is_none() { let conn = Connection::open_in_memory()?; { let mut stmt = conn.prepare_cached( "CREATE TABLE data (key VARCHAR UNIQUE, value VARCHAR)", )?; stmt.execute(params![])?; } state.put(SessionStorage(conn)); } &state.borrow::<SessionStorage>().0 }; Ok(conn) } #[inline] fn size_check(input: usize) -> Result<(), WebStorageError> { if input >= MAX_STORAGE_BYTES { return Err(WebStorageError::StorageExceeded); } Ok(()) } struct Storage { persistent: bool, } // SAFETY: we're sure this can be GCed unsafe impl GarbageCollected for Storage { fn trace(&self, _visitor: &mut deno_core::v8::cppgc::Visitor) {} fn get_name(&self) -> &'static std::ffi::CStr { c"Storage" } } #[op2] impl Storage { #[constructor] #[cppgc] fn new(persistent: bool) -> Storage { Storage { persistent } } #[getter] #[smi] fn length(&self, state: &mut OpState) -> Result<u32, WebStorageError> { let conn = get_webstorage(state, self.persistent)?; let mut stmt = conn.prepare_cached("SELECT COUNT(*) FROM data")?; let length: u32 = stmt.query_row(params![], |row| row.get(0))?; Ok(length) } #[required(1)] #[string] fn key( &self, state: &mut OpState, #[smi] index: u32, ) -> Result<Option<String>, WebStorageError> { let conn = get_webstorage(state, self.persistent)?; let mut stmt = conn.prepare_cached("SELECT key FROM data LIMIT 1 OFFSET ?")?; let key: Option<String> = stmt .query_row(params![index], |row| row.get(0)) .optional()?; Ok(key) } #[fast] #[required(2)] fn set_item( &self, state: &mut OpState, #[string] key: &str, #[string] value: &str, ) -> Result<(), WebStorageError> { let conn = get_webstorage(state, self.persistent)?; size_check(key.len() + value.len())?; let mut stmt = conn .prepare_cached("SELECT SUM(pgsize) FROM dbstat WHERE name = 'data'")?; let size: u32 = stmt.query_row(params![], |row| row.get(0))?; size_check(size as usize)?; let mut stmt = conn.prepare_cached( "INSERT OR REPLACE INTO data (key, value) VALUES (?, ?)", )?; stmt.execute(params![key, value])?; Ok(()) } #[required(1)] #[string] fn get_item( &self, state: &mut OpState, #[string] key: &str, ) -> Result<Option<String>, WebStorageError> { let conn = get_webstorage(state, self.persistent)?; let mut stmt = conn.prepare_cached("SELECT value FROM data WHERE key = ?")?; let val = stmt.query_row(params![key], |row| row.get(0)).optional()?; Ok(val) } #[fast] #[required(1)] fn remove_item( &self, state: &mut OpState, #[string] key: &str, ) -> Result<(), WebStorageError> { let conn = get_webstorage(state, self.persistent)?; let mut stmt = conn.prepare_cached("DELETE FROM data WHERE key = ?")?; stmt.execute(params![key])?; Ok(()) } #[fast] fn clear(&self, state: &mut OpState) -> Result<(), WebStorageError> { let conn = get_webstorage(state, self.persistent)?; let mut stmt = conn.prepare_cached("DELETE FROM data")?; stmt.execute(params![])?; Ok(()) } } #[op2] #[serde] fn op_webstorage_iterate_keys( #[cppgc] storage: &Storage, state: &mut OpState, ) -> Result<Vec<String>, WebStorageError> { let conn = get_webstorage(state, storage.persistent)?; let mut stmt = conn.prepare_cached("SELECT key FROM data")?; let keys = stmt .query_map(params![], |row| row.get::<_, String>(0))? .map(|r| r.unwrap()) .collect(); Ok(keys) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/cache/lib.rs
ext/cache/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::borrow::Cow; use std::cell::RefCell; use std::path::PathBuf; use std::pin::Pin; use std::rc::Rc; use std::sync::Arc; use async_trait::async_trait; use bytes::Bytes; use deno_core::AsyncRefCell; use deno_core::AsyncResult; use deno_core::ByteString; use deno_core::OpState; use deno_core::Resource; use deno_core::ResourceId; use deno_core::op2; use deno_core::serde::Deserialize; use deno_core::serde::Serialize; use deno_error::JsErrorBox; use futures::Stream; use tokio::io::AsyncRead; use tokio::io::AsyncReadExt; mod lsc_shard; mod lscache; mod sqlite; pub use lsc_shard::CacheShard; pub use lscache::LscBackend; pub use sqlite::SqliteBackedCache; use tokio_util::io::StreamReader; #[derive(Debug, thiserror::Error, deno_error::JsError)] pub enum CacheError { #[class(type)] #[error("CacheStorage is not available in this context")] ContextUnsupported, #[class(type)] #[error("Cache name cannot be empty")] EmptyName, #[class(type)] #[error("Cache is not available")] NotAvailable, #[class(type)] #[error("Cache not found")] NotFound, #[class(type)] #[error("Cache deletion is not supported")] DeletionNotSupported, #[class(type)] #[error("Content-Encoding is not allowed in response headers")] ContentEncodingNotAllowed, #[class(generic)] #[error(transparent)] Sqlite(#[from] rusqlite::Error), #[class(generic)] #[error(transparent)] JoinError(#[from] tokio::task::JoinError), #[class(inherit)] #[error(transparent)] Resource(#[from] deno_core::error::ResourceError), #[class(inherit)] #[error(transparent)] Other(JsErrorBox), #[class(inherit)] #[error("{0}")] Io(#[from] std::io::Error), #[class(type)] #[error(transparent)] InvalidHeaderName(#[from] hyper::header::InvalidHeaderName), #[class(type)] #[error(transparent)] InvalidHeaderValue(#[from] hyper::header::InvalidHeaderValue), #[class(type)] #[error(transparent)] Hyper(#[from] hyper::Error), #[class(generic)] #[error(transparent)] ClientError(#[from] hyper_util::client::legacy::Error), #[class(generic)] #[error("Failed to create cache storage directory {}", .dir.display())] CacheStorageDirectory { dir: PathBuf, #[source] source: std::io::Error, }, #[class(generic)] #[error("cache {method} request failed: {status}")] RequestFailed { method: &'static str, status: hyper::StatusCode, }, } #[derive(Clone)] pub struct CreateCache(pub Arc<dyn Fn() -> Result<CacheImpl, CacheError>>); deno_core::extension!(deno_cache, deps = [ deno_webidl, deno_web, deno_fetch ], ops = [ op_cache_storage_open, op_cache_storage_has, op_cache_storage_delete, op_cache_put, op_cache_match, op_cache_delete, ], esm = [ "01_cache.js" ], options = { maybe_create_cache: Option<CreateCache>, }, state = |state, options| { if let Some(create_cache) = options.maybe_create_cache { state.put(create_cache); } }, ); #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct CachePutRequest { pub cache_id: i64, pub request_url: String, pub request_headers: Vec<(ByteString, ByteString)>, pub response_headers: Vec<(ByteString, ByteString)>, pub response_status: u16, pub response_status_text: String, pub response_rid: Option<ResourceId>, } #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct CacheMatchRequest { pub cache_id: i64, pub request_url: String, pub request_headers: Vec<(ByteString, ByteString)>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CacheMatchResponse(CacheMatchResponseMeta, Option<ResourceId>); #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CacheMatchResponseMeta { pub response_status: u16, pub response_status_text: String, pub request_headers: Vec<(ByteString, ByteString)>, pub response_headers: Vec<(ByteString, ByteString)>, } #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "camelCase")] pub struct CacheDeleteRequest { pub cache_id: i64, pub request_url: String, } #[async_trait(?Send)] pub trait Cache: Clone + 'static { type CacheMatchResourceType: Resource; async fn storage_open(&self, cache_name: String) -> Result<i64, CacheError>; async fn storage_has(&self, cache_name: String) -> Result<bool, CacheError>; async fn storage_delete( &self, cache_name: String, ) -> Result<bool, CacheError>; /// Put a resource into the cache. async fn put( &self, request_response: CachePutRequest, resource: Option<Rc<dyn Resource>>, ) -> Result<(), CacheError>; async fn r#match( &self, request: CacheMatchRequest, ) -> Result< Option<(CacheMatchResponseMeta, Option<Self::CacheMatchResourceType>)>, CacheError, >; async fn delete( &self, request: CacheDeleteRequest, ) -> Result<bool, CacheError>; } #[derive(Clone)] pub enum CacheImpl { Sqlite(SqliteBackedCache), Lsc(LscBackend), } #[async_trait(?Send)] impl Cache for CacheImpl { type CacheMatchResourceType = CacheResponseResource; async fn storage_open(&self, cache_name: String) -> Result<i64, CacheError> { match self { Self::Sqlite(cache) => cache.storage_open(cache_name).await, Self::Lsc(cache) => cache.storage_open(cache_name).await, } } async fn storage_has(&self, cache_name: String) -> Result<bool, CacheError> { match self { Self::Sqlite(cache) => cache.storage_has(cache_name).await, Self::Lsc(cache) => cache.storage_has(cache_name).await, } } async fn storage_delete( &self, cache_name: String, ) -> Result<bool, CacheError> { match self { Self::Sqlite(cache) => cache.storage_delete(cache_name).await, Self::Lsc(cache) => cache.storage_delete(cache_name).await, } } async fn put( &self, request_response: CachePutRequest, resource: Option<Rc<dyn Resource>>, ) -> Result<(), CacheError> { match self { Self::Sqlite(cache) => cache.put(request_response, resource).await, Self::Lsc(cache) => cache.put(request_response, resource).await, } } async fn r#match( &self, request: CacheMatchRequest, ) -> Result< Option<(CacheMatchResponseMeta, Option<Self::CacheMatchResourceType>)>, CacheError, > { match self { Self::Sqlite(cache) => cache.r#match(request).await, Self::Lsc(cache) => cache.r#match(request).await, } } async fn delete( &self, request: CacheDeleteRequest, ) -> Result<bool, CacheError> { match self { Self::Sqlite(cache) => cache.delete(request).await, Self::Lsc(cache) => cache.delete(request).await, } } } pub enum CacheResponseResource { Sqlite(AsyncRefCell<tokio::fs::File>), Lsc(AsyncRefCell<Pin<Box<dyn AsyncRead>>>), } impl CacheResponseResource { fn sqlite(file: tokio::fs::File) -> Self { Self::Sqlite(AsyncRefCell::new(file)) } fn lsc( body: impl Stream<Item = Result<Bytes, std::io::Error>> + 'static, ) -> Self { Self::Lsc(AsyncRefCell::new(Box::pin(StreamReader::new(body)))) } async fn read( self: Rc<Self>, data: &mut [u8], ) -> Result<usize, std::io::Error> { let nread = match &*self { CacheResponseResource::Sqlite(_) => { let resource = deno_core::RcRef::map(&self, |r| match r { Self::Sqlite(r) => r, _ => unreachable!(), }); let mut file = resource.borrow_mut().await; file.read(data).await? } CacheResponseResource::Lsc(_) => { let resource = deno_core::RcRef::map(&self, |r| match r { Self::Lsc(r) => r, _ => unreachable!(), }); let mut file = resource.borrow_mut().await; file.read(data).await? } }; Ok(nread) } } impl Resource for CacheResponseResource { deno_core::impl_readable_byob!(); fn name(&self) -> Cow<'_, str> { "CacheResponseResource".into() } } #[op2(async)] #[number] pub async fn op_cache_storage_open( state: Rc<RefCell<OpState>>, #[string] cache_name: String, ) -> Result<i64, CacheError> { let cache = get_cache(&state)?; cache.storage_open(cache_name).await } #[op2(async)] pub async fn op_cache_storage_has( state: Rc<RefCell<OpState>>, #[string] cache_name: String, ) -> Result<bool, CacheError> { let cache = get_cache(&state)?; cache.storage_has(cache_name).await } #[op2(async)] pub async fn op_cache_storage_delete( state: Rc<RefCell<OpState>>, #[string] cache_name: String, ) -> Result<bool, CacheError> { let cache = get_cache(&state)?; cache.storage_delete(cache_name).await } #[op2(async)] pub async fn op_cache_put( state: Rc<RefCell<OpState>>, #[serde] request_response: CachePutRequest, ) -> Result<(), CacheError> { let cache = get_cache(&state)?; let resource = match request_response.response_rid { Some(rid) => Some( state .borrow_mut() .resource_table .take_any(rid) .map_err(CacheError::Resource)?, ), None => None, }; cache.put(request_response, resource).await } #[op2(async)] #[serde] pub async fn op_cache_match( state: Rc<RefCell<OpState>>, #[serde] request: CacheMatchRequest, ) -> Result<Option<CacheMatchResponse>, CacheError> { let cache = get_cache(&state)?; match cache.r#match(request).await? { Some((meta, None)) => Ok(Some(CacheMatchResponse(meta, None))), Some((meta, Some(resource))) => { let rid = state.borrow_mut().resource_table.add(resource); Ok(Some(CacheMatchResponse(meta, Some(rid)))) } None => Ok(None), } } #[op2(async)] pub async fn op_cache_delete( state: Rc<RefCell<OpState>>, #[serde] request: CacheDeleteRequest, ) -> Result<bool, CacheError> { let cache = get_cache(&state)?; cache.delete(request).await } pub fn get_cache( state: &Rc<RefCell<OpState>>, ) -> Result<CacheImpl, CacheError> { let mut state = state.borrow_mut(); if let Some(cache) = state.try_borrow::<CacheImpl>() { Ok(cache.clone()) } else if let Some(create_cache) = state.try_borrow::<CreateCache>() { let cache = create_cache.0()?; state.put(cache); Ok(state.borrow::<CacheImpl>().clone()) } else { Err(CacheError::ContextUnsupported) } } /// Check if headers, mentioned in the vary header, of query request /// and cached request are equal. pub fn vary_header_matches( vary_header: &ByteString, query_request_headers: &[(ByteString, ByteString)], cached_request_headers: &[(ByteString, ByteString)], ) -> bool { let vary_header = match std::str::from_utf8(vary_header) { Ok(vary_header) => vary_header, Err(_) => return false, }; let headers = get_headers_from_vary_header(vary_header); for header in headers { let query_header = get_header(&header, query_request_headers); let cached_header = get_header(&header, cached_request_headers); if query_header != cached_header { return false; } } true } #[test] fn test_vary_header_matches() { let vary_header = ByteString::from("accept-encoding"); let query_request_headers = vec![( ByteString::from("accept-encoding"), ByteString::from("gzip"), )]; let cached_request_headers = vec![( ByteString::from("accept-encoding"), ByteString::from("gzip"), )]; assert!(vary_header_matches( &vary_header, &query_request_headers, &cached_request_headers )); let vary_header = ByteString::from("accept-encoding"); let query_request_headers = vec![( ByteString::from("accept-encoding"), ByteString::from("gzip"), )]; let cached_request_headers = vec![(ByteString::from("accept-encoding"), ByteString::from("br"))]; assert!(!vary_header_matches( &vary_header, &query_request_headers, &cached_request_headers )); } /// Get headers from the vary header. pub fn get_headers_from_vary_header(vary_header: &str) -> Vec<String> { vary_header .split(',') .map(|s| s.trim().to_lowercase()) .collect() } #[test] fn test_get_headers_from_vary_header() { let headers = get_headers_from_vary_header("accept-encoding"); assert_eq!(headers, vec!["accept-encoding"]); let headers = get_headers_from_vary_header("accept-encoding, user-agent"); assert_eq!(headers, vec!["accept-encoding", "user-agent"]); } /// Get value for the header with the given name. pub fn get_header( name: &str, headers: &[(ByteString, ByteString)], ) -> Option<ByteString> { headers .iter() .find(|(k, _)| { if let Ok(k) = std::str::from_utf8(k) { k.eq_ignore_ascii_case(name) } else { false } }) .map(|(_, v)| v.to_owned()) } #[test] fn test_get_header() { let headers = vec![ ( ByteString::from("accept-encoding"), ByteString::from("gzip"), ), ( ByteString::from("content-type"), ByteString::from("application/json"), ), ( ByteString::from("vary"), ByteString::from("accept-encoding"), ), ]; let value = get_header("accept-encoding", &headers); assert_eq!(value, Some(ByteString::from("gzip"))); let value = get_header("content-type", &headers); assert_eq!(value, Some(ByteString::from("application/json"))); let value = get_header("vary", &headers); assert_eq!(value, Some(ByteString::from("accept-encoding"))); } /// Serialize headers into bytes. pub fn serialize_headers(headers: &[(ByteString, ByteString)]) -> Vec<u8> { let mut serialized_headers = Vec::new(); for (name, value) in headers { serialized_headers.extend_from_slice(name); serialized_headers.extend_from_slice(b"\r\n"); serialized_headers.extend_from_slice(value); serialized_headers.extend_from_slice(b"\r\n"); } serialized_headers } /// Deserialize bytes into headers. pub fn deserialize_headers( serialized_headers: &[u8], ) -> Vec<(ByteString, ByteString)> { let mut headers = Vec::new(); let mut piece = None; let mut start = 0; for (i, byte) in serialized_headers.iter().enumerate() { if byte == &b'\r' && serialized_headers.get(i + 1) == Some(&b'\n') { if piece.is_none() { piece = Some(start..i); } else { let name = piece.unwrap(); let value = start..i; headers.push(( ByteString::from(&serialized_headers[name]), ByteString::from(&serialized_headers[value]), )); piece = None; } start = i + 2; } } assert!(piece.is_none()); assert_eq!(start, serialized_headers.len()); headers }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/cache/sqlite.rs
ext/cache/sqlite.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::future::poll_fn; use std::path::PathBuf; use std::pin::Pin; use std::rc::Rc; use std::sync::Arc; use std::time::SystemTime; use std::time::UNIX_EPOCH; use deno_core::BufMutView; use deno_core::ByteString; use deno_core::Resource; use deno_core::parking_lot::Mutex; use deno_core::unsync::spawn_blocking; use rusqlite::Connection; use rusqlite::OptionalExtension; use rusqlite::params; use tokio::io::AsyncWrite; use tokio::io::AsyncWriteExt; use crate::CacheDeleteRequest; use crate::CacheError; use crate::CacheMatchRequest; use crate::CacheMatchResponseMeta; use crate::CachePutRequest; use crate::CacheResponseResource; use crate::deserialize_headers; use crate::get_header; use crate::serialize_headers; use crate::vary_header_matches; #[derive(Clone)] pub struct SqliteBackedCache { pub connection: Arc<Mutex<Connection>>, pub cache_storage_dir: PathBuf, } #[derive(Debug)] enum Mode { Disk, InMemory, } impl SqliteBackedCache { pub fn new(cache_storage_dir: PathBuf) -> Result<Self, CacheError> { let mode = match std::env::var("DENO_CACHE_DB_MODE") .unwrap_or_default() .as_str() { "disk" | "" => Mode::Disk, "memory" => Mode::InMemory, _ => { log::warn!("Unknown DENO_CACHE_DB_MODE value, defaulting to disk"); Mode::Disk } }; let connection = if matches!(mode, Mode::InMemory) { rusqlite::Connection::open_in_memory() .unwrap_or_else(|_| panic!("failed to open in-memory cache db")) } else { std::fs::create_dir_all(&cache_storage_dir).map_err(|source| { CacheError::CacheStorageDirectory { dir: cache_storage_dir.clone(), source, } })?; let path = cache_storage_dir.join("cache_metadata.db"); let connection = rusqlite::Connection::open(&path).unwrap_or_else(|_| { panic!("failed to open cache db at {}", path.display()) }); // Enable write-ahead-logging mode. let initial_pragmas = " -- enable write-ahead-logging mode PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA optimize; "; connection.execute_batch(initial_pragmas)?; connection }; connection.execute( "CREATE TABLE IF NOT EXISTS cache_storage ( id INTEGER PRIMARY KEY, cache_name TEXT NOT NULL UNIQUE )", (), )?; connection .execute( "CREATE TABLE IF NOT EXISTS request_response_list ( id INTEGER PRIMARY KEY, cache_id INTEGER NOT NULL, request_url TEXT NOT NULL, request_headers BLOB NOT NULL, response_headers BLOB NOT NULL, response_status INTEGER NOT NULL, response_status_text TEXT, response_body_key TEXT, last_inserted_at INTEGER UNSIGNED NOT NULL, FOREIGN KEY (cache_id) REFERENCES cache_storage(id) ON DELETE CASCADE, UNIQUE (cache_id, request_url) )", (), )?; Ok(SqliteBackedCache { connection: Arc::new(Mutex::new(connection)), cache_storage_dir, }) } } impl SqliteBackedCache { /// Open a cache storage. Internally, this creates a row in the /// sqlite db if the cache doesn't exist and returns the internal id /// of the cache. pub async fn storage_open( &self, cache_name: String, ) -> Result<i64, CacheError> { let db = self.connection.clone(); let cache_storage_dir = self.cache_storage_dir.clone(); spawn_blocking(move || { let db = db.lock(); db.execute( "INSERT OR IGNORE INTO cache_storage (cache_name) VALUES (?1)", params![cache_name], )?; let cache_id = db.query_row( "SELECT id FROM cache_storage WHERE cache_name = ?1", params![cache_name], |row| { let id: i64 = row.get(0)?; Ok(id) }, )?; let responses_dir = get_responses_dir(cache_storage_dir, cache_id); std::fs::create_dir_all(responses_dir)?; Ok::<i64, CacheError>(cache_id) }) .await? } /// Check if a cache with the provided name exists. /// Note: this doesn't check the disk, it only checks the sqlite db. pub async fn storage_has( &self, cache_name: String, ) -> Result<bool, CacheError> { let db = self.connection.clone(); spawn_blocking(move || { let db = db.lock(); let cache_exists = db.query_row( "SELECT count(id) FROM cache_storage WHERE cache_name = ?1", params![cache_name], |row| { let count: i64 = row.get(0)?; Ok(count > 0) }, )?; Ok::<bool, CacheError>(cache_exists) }) .await? } /// Delete a cache storage. Internally, this deletes the row in the sqlite db. pub async fn storage_delete( &self, cache_name: String, ) -> Result<bool, CacheError> { let db = self.connection.clone(); let cache_storage_dir = self.cache_storage_dir.clone(); spawn_blocking(move || { let db = db.lock(); let maybe_cache_id = db .query_row( "DELETE FROM cache_storage WHERE cache_name = ?1 RETURNING id", params![cache_name], |row| { let id: i64 = row.get(0)?; Ok(id) }, ) .optional()?; if let Some(cache_id) = maybe_cache_id { let cache_dir = cache_storage_dir.join(cache_id.to_string()); if cache_dir.exists() { std::fs::remove_dir_all(cache_dir)?; } } Ok::<bool, CacheError>(maybe_cache_id.is_some()) }) .await? } pub async fn put( &self, request_response: CachePutRequest, resource: Option<Rc<dyn Resource>>, ) -> Result<(), CacheError> { let db = self.connection.clone(); let cache_storage_dir = self.cache_storage_dir.clone(); let now = SystemTime::now() .duration_since(UNIX_EPOCH) .expect("SystemTime is before unix epoch"); if let Some(resource) = resource { let body_key = hash(&format!( "{}_{}", &request_response.request_url, now.as_nanos() )); let responses_dir = get_responses_dir(cache_storage_dir, request_response.cache_id); let response_path = responses_dir.join(&body_key); let mut file = tokio::fs::File::create(response_path).await?; let mut buf = BufMutView::new(64 * 1024); loop { let (size, buf2) = resource .clone() .read_byob(buf) .await .map_err(CacheError::Other)?; if size == 0 { break; } buf = buf2; // Use poll_write to avoid holding a slice across await points poll_fn(|cx| Pin::new(&mut file).poll_write(cx, &buf[..size])).await?; } file.flush().await?; file.sync_all().await?; assert_eq!( insert_cache_asset(db, request_response, Some(body_key.clone()),) .await?, Some(body_key) ); } else { assert!( insert_cache_asset(db, request_response, None) .await? .is_none() ); } Ok(()) } pub async fn r#match( &self, request: CacheMatchRequest, ) -> Result< Option<(CacheMatchResponseMeta, Option<CacheResponseResource>)>, CacheError, > { let db = self.connection.clone(); let cache_storage_dir = self.cache_storage_dir.clone(); let (query_result, request) = spawn_blocking(move || { let db = db.lock(); let result = db.query_row( "SELECT response_body_key, response_headers, response_status, response_status_text, request_headers FROM request_response_list WHERE cache_id = ?1 AND request_url = ?2", (request.cache_id, &request.request_url), |row| { let response_body_key: Option<String> = row.get(0)?; let response_headers: Vec<u8> = row.get(1)?; let response_status: u16 = row.get(2)?; let response_status_text: String = row.get(3)?; let request_headers: Vec<u8> = row.get(4)?; let response_headers: Vec<(ByteString, ByteString)> = deserialize_headers(&response_headers); let request_headers: Vec<(ByteString, ByteString)> = deserialize_headers(&request_headers); Ok((CacheMatchResponseMeta { request_headers, response_headers, response_status, response_status_text}, response_body_key )) }, ); // Return ownership of request to the caller result.optional().map(|x| (x, request)) }) .await??; match query_result { Some((cache_meta, Some(response_body_key))) => { // From https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm // If there's Vary header in the response, ensure all the // headers of the cached request match the query request. if let Some(vary_header) = get_header("vary", &cache_meta.response_headers) && !vary_header_matches( &vary_header, &request.request_headers, &cache_meta.request_headers, ) { return Ok(None); } let response_path = get_responses_dir(cache_storage_dir, request.cache_id) .join(response_body_key); let file = match tokio::fs::File::open(response_path).await { Ok(file) => file, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { // Best efforts to delete the old cache item _ = self .delete(CacheDeleteRequest { cache_id: request.cache_id, request_url: request.request_url, }) .await; return Ok(None); } Err(err) => return Err(err.into()), }; Ok(Some(( cache_meta, Some(CacheResponseResource::sqlite(file)), ))) } Some((cache_meta, None)) => Ok(Some((cache_meta, None))), None => Ok(None), } } pub async fn delete( &self, request: CacheDeleteRequest, ) -> Result<bool, CacheError> { let db = self.connection.clone(); spawn_blocking(move || { // TODO(@satyarohith): remove the response body from disk if one exists let db = db.lock(); let rows_effected = db.execute( "DELETE FROM request_response_list WHERE cache_id = ?1 AND request_url = ?2", (request.cache_id, &request.request_url), )?; Ok::<bool, CacheError>(rows_effected > 0) }) .await? } } async fn insert_cache_asset( db: Arc<Mutex<Connection>>, put: CachePutRequest, response_body_key: Option<String>, ) -> Result<Option<String>, CacheError> { spawn_blocking(move || { let maybe_response_body = { let db = db.lock(); db.query_row( "INSERT OR REPLACE INTO request_response_list (cache_id, request_url, request_headers, response_headers, response_body_key, response_status, response_status_text, last_inserted_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) RETURNING response_body_key", ( put.cache_id, put.request_url, serialize_headers(&put.request_headers), serialize_headers(&put.response_headers), response_body_key, put.response_status, put.response_status_text, SystemTime::now().duration_since(UNIX_EPOCH).expect("SystemTime is before unix epoch").as_secs(), ), |row| { let response_body_key: Option<String> = row.get(0)?; Ok(response_body_key) }, )? }; Ok::<Option<String>, CacheError>(maybe_response_body) }).await? } #[inline] fn get_responses_dir(cache_storage_dir: PathBuf, cache_id: i64) -> PathBuf { cache_storage_dir .join(cache_id.to_string()) .join("responses") } impl deno_core::Resource for SqliteBackedCache { fn name(&self) -> std::borrow::Cow<'_, str> { "SqliteBackedCache".into() } } pub fn hash(token: &str) -> String { use sha2::Digest; format!("{:x}", sha2::Sha256::digest(token.as_bytes())) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/cache/lscache.rs
ext/cache/lscache.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::cell::RefCell; use std::rc::Rc; use async_stream::try_stream; use base64::Engine; use bytes::Bytes; use deno_core::BufMutView; use deno_core::ByteString; use deno_core::Resource; use deno_core::unsync::spawn; use futures::StreamExt; use futures::TryStreamExt; use http::HeaderMap; use http::HeaderName; use http::HeaderValue; use http::header::VARY; use http_body_util::combinators::UnsyncBoxBody; use slab::Slab; use crate::CacheDeleteRequest; use crate::CacheError; use crate::CacheMatchRequest; use crate::CacheMatchResponseMeta; use crate::CachePutRequest; use crate::CacheResponseResource; use crate::get_header; use crate::get_headers_from_vary_header; use crate::lsc_shard::CacheShard; const REQHDR_PREFIX: &str = "x-lsc-meta-reqhdr-"; #[derive(Clone, Default)] pub struct LscBackend { shard: Rc<RefCell<Option<Rc<CacheShard>>>>, id2name: Rc<RefCell<Slab<String>>>, } impl LscBackend { pub fn set_shard(&self, shard: Rc<CacheShard>) { *self.shard.borrow_mut() = Some(shard); } } #[allow(clippy::unused_async)] impl LscBackend { /// Open a cache storage. Internally, this allocates an id and maps it /// to the provided cache name. pub async fn storage_open( &self, cache_name: String, ) -> Result<i64, CacheError> { if cache_name.is_empty() { return Err(CacheError::EmptyName); } let id = self.id2name.borrow_mut().insert(cache_name); Ok(id as i64) } /// Check if a cache with the provided name exists. Always returns `true`. pub async fn storage_has( &self, _cache_name: String, ) -> Result<bool, CacheError> { Ok(true) } /// Delete a cache storage. Not yet implemented. pub async fn storage_delete( &self, _cache_name: String, ) -> Result<bool, CacheError> { Err(CacheError::DeletionNotSupported) } /// Writes an entry to the cache. pub async fn put( &self, request_response: CachePutRequest, resource: Option<Rc<dyn Resource>>, ) -> Result<(), CacheError> { let Some(shard) = self.shard.borrow().as_ref().cloned() else { return Err(CacheError::NotAvailable); }; let Some(cache_name) = self .id2name .borrow_mut() .get(request_response.cache_id as usize) .cloned() else { return Err(CacheError::NotFound); }; let object_key = build_cache_object_key( cache_name.as_bytes(), request_response.request_url.as_bytes(), ); let mut headers = HeaderMap::new(); for hdr in &request_response.request_headers { headers.insert( HeaderName::from_bytes( &[REQHDR_PREFIX.as_bytes(), &hdr.0[..]].concat(), )?, HeaderValue::from_bytes(&hdr.1[..])?, ); } for hdr in &request_response.response_headers { if hdr.0.starts_with(b"x-lsc-meta-") { continue; } if hdr.0[..] == b"content-encoding"[..] { return Err(CacheError::ContentEncodingNotAllowed); } headers.insert( HeaderName::from_bytes(&hdr.0[..])?, HeaderValue::from_bytes(&hdr.1[..])?, ); } headers.insert( HeaderName::from_bytes(b"x-lsc-meta-cached-at")?, HeaderValue::from_bytes( chrono::Utc::now() .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) .as_bytes(), )?, ); let body = try_stream! { if let Some(resource) = resource { loop { let (size, buf) = resource.clone().read_byob(BufMutView::new(64 * 1024)).await.map_err(CacheError::Other)?; if size == 0 { break; } yield Bytes::copy_from_slice(&buf[..size]); } } }; let (body_tx, body_rx) = futures::channel::mpsc::channel(4); spawn(body.map(Ok::<Result<_, CacheError>, _>).forward(body_tx)); let body = http_body_util::StreamBody::new( body_rx.into_stream().map_ok(http_body::Frame::data), ); let body = UnsyncBoxBody::new(body); shard.put_object(&object_key, headers, body).await?; Ok(()) } /// Matches a request against the cache. pub async fn r#match( &self, request: CacheMatchRequest, ) -> Result< Option<(CacheMatchResponseMeta, Option<CacheResponseResource>)>, CacheError, > { let Some(shard) = self.shard.borrow().as_ref().cloned() else { return Err(CacheError::NotAvailable); }; let Some(cache_name) = self .id2name .borrow() .get(request.cache_id as usize) .cloned() else { return Err(CacheError::NotFound); }; let object_key = build_cache_object_key( cache_name.as_bytes(), request.request_url.as_bytes(), ); let Some(res) = shard.get_object(&object_key).await? else { return Ok(None); }; // Is this a tombstone? if res.headers().contains_key("x-lsc-meta-deleted-at") { return Ok(None); } // From https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm // If there's Vary header in the response, ensure all the // headers of the cached request match the query request. if let Some(vary_header) = res.headers().get(&VARY) && !vary_header_matches( vary_header.as_bytes(), &request.request_headers, res.headers(), ) { return Ok(None); } let mut response_headers: Vec<(ByteString, ByteString)> = res .headers() .iter() .filter_map(|(k, v)| { if k.as_str().starts_with("x-lsc-meta-") || k.as_str() == "x-ryw" { None } else { Some((k.as_str().into(), v.as_bytes().into())) } }) .collect(); if let Some(x) = res .headers() .get("x-lsc-meta-cached-at") .and_then(|x| x.to_str().ok()) && let Ok(cached_at) = chrono::DateTime::parse_from_rfc3339(x) { let age = chrono::Utc::now() .signed_duration_since(cached_at) .num_seconds(); if age >= 0 { response_headers.push(("age".into(), age.to_string().into())); } } let meta = CacheMatchResponseMeta { response_status: res.status().as_u16(), response_status_text: res .status() .canonical_reason() .unwrap_or("") .to_string(), request_headers: res .headers() .iter() .filter_map(|(k, v)| { let reqhdr_prefix = REQHDR_PREFIX.as_bytes(); if k.as_str().as_bytes().starts_with(reqhdr_prefix) { Some(( k.as_str().as_bytes()[REQHDR_PREFIX.len()..].into(), v.as_bytes().into(), )) } else { None } }) .collect(), response_headers, }; let body = http_body_util::BodyDataStream::new(res.into_body()) .into_stream() .map_err(std::io::Error::other); let body = CacheResponseResource::lsc(body); Ok(Some((meta, Some(body)))) } pub async fn delete( &self, request: CacheDeleteRequest, ) -> Result<bool, CacheError> { let Some(shard) = self.shard.borrow().as_ref().cloned() else { return Err(CacheError::NotAvailable); }; let Some(cache_name) = self .id2name .borrow_mut() .get(request.cache_id as usize) .cloned() else { return Err(CacheError::NotFound); }; let object_key = build_cache_object_key( cache_name.as_bytes(), request.request_url.as_bytes(), ); let mut headers = HeaderMap::new(); headers.insert( HeaderName::from_bytes(b"expires")?, HeaderValue::from_bytes(b"Thu, 01 Jan 1970 00:00:00 GMT")?, ); headers.insert( HeaderName::from_bytes(b"x-lsc-meta-deleted-at")?, HeaderValue::from_bytes( chrono::Utc::now() .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) .as_bytes(), )?, ); shard.put_object_empty(&object_key, headers).await?; Ok(true) } } impl deno_core::Resource for LscBackend { fn name(&self) -> std::borrow::Cow<'_, str> { "LscBackend".into() } } fn vary_header_matches( vary_header: &[u8], query_request_headers: &[(ByteString, ByteString)], cached_headers: &HeaderMap, ) -> bool { let vary_header = match std::str::from_utf8(vary_header) { Ok(vary_header) => vary_header, Err(_) => return false, }; let headers = get_headers_from_vary_header(vary_header); for header in headers { // Ignoring `accept-encoding` is safe because we refuse to cache responses // with `content-encoding` if header == "accept-encoding" { continue; } let lookup_key = format!("{}{}", REQHDR_PREFIX, header); let query_header = get_header(&header, query_request_headers); let cached_header = cached_headers.get(&lookup_key); if query_header.as_ref().map(|x| &x[..]) != cached_header.as_ref().map(|x| x.as_bytes()) { return false; } } true } fn build_cache_object_key(cache_name: &[u8], request_url: &[u8]) -> String { format!( "v1/{}/{}", base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(cache_name), base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(request_url), ) }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/cache/lsc_shard.rs
ext/cache/lsc_shard.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::convert::Infallible; use bytes::Bytes; use http::Method; use http::Request; use http::Response; use http_body_util::BodyExt; use http_body_util::Either; use http_body_util::Empty; use http_body_util::combinators::UnsyncBoxBody; use hyper::HeaderMap; use hyper::StatusCode; use hyper::body::Incoming; use hyper::header::AUTHORIZATION; use hyper_util::client::legacy::Client; use hyper_util::client::legacy::connect::HttpConnector; use hyper_util::rt::tokio::TokioExecutor; use crate::CacheError; type ClientBody = Either<UnsyncBoxBody<Bytes, CacheError>, UnsyncBoxBody<Bytes, Infallible>>; pub struct CacheShard { client: Client<HttpConnector, ClientBody>, endpoint: String, token: String, } impl CacheShard { pub fn new(endpoint: String, token: String) -> Self { let client = Client::builder(TokioExecutor::new()) .pool_idle_timeout(std::time::Duration::from_secs(30)) .build_http(); Self { client, endpoint, token, } } pub async fn get_object( &self, object_key: &str, ) -> Result<Option<Response<Incoming>>, CacheError> { let body = Either::Right(UnsyncBoxBody::new(Empty::new())); let req = Request::builder() .method(Method::GET) .uri(format!("{}/objects/{}", self.endpoint, object_key)) .header(&AUTHORIZATION, format!("Bearer {}", self.token)) .header("x-ryw", "1") .body(body) .unwrap(); let res = self.client.request(req).await?; if res.status().is_success() { Ok(Some(res)) } else if res.status() == StatusCode::NOT_FOUND { Ok(None) } else { Err(CacheError::RequestFailed { method: "GET", status: res.status(), }) } } pub async fn put_object_empty( &self, object_key: &str, headers: HeaderMap, ) -> Result<(), CacheError> { let body = Either::Right(UnsyncBoxBody::new(Empty::new())); let mut builder = Request::builder() .method(Method::PUT) .uri(format!("{}/objects/{}", self.endpoint, object_key)) .header(&AUTHORIZATION, format!("Bearer {}", self.token)); for (key, val) in headers.iter() { builder = builder.header(key, val) } let req = builder.body(body).unwrap(); let res = self.client.request(req).await?; if res.status().is_success() { Ok(()) } else { let status = res.status(); log::debug!( "Response body {:#?}", res.into_body().collect().await?.to_bytes() ); Err(CacheError::RequestFailed { method: "PUT", status, }) } } pub async fn put_object( &self, object_key: &str, headers: HeaderMap, body: UnsyncBoxBody<Bytes, CacheError>, ) -> Result<(), CacheError> { let mut builder = Request::builder() .method(Method::PUT) .uri(format!("{}/objects/{}", self.endpoint, object_key)) .header(&AUTHORIZATION, format!("Bearer {}", self.token)); for (key, val) in headers.iter() { builder = builder.header(key, val) } let req = builder.body(Either::Left(body)).unwrap(); let res = self.client.request(req).await?; if res.status().is_success() { Ok(()) } else { let status = res.status(); log::debug!( "Response body {:#?}", res.into_body().collect().await?.to_bytes() ); Err(CacheError::RequestFailed { method: "PUT", status, }) } } }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/global.rs
ext/node/global.rs
// Copyright 2018-2025 the Deno authors. MIT license. use std::rc::Rc; use deno_core::v8; use deno_core::v8::GetPropertyNamesArgs; use deno_core::v8::MapFnTo; // NOTE(bartlomieju): somehow calling `.map_fn_to()` multiple times on a function // returns two different pointers. That shouldn't be the case as `.map_fn_to()` // creates a thin wrapper that is a pure function. @piscisaureus suggests it // might be a bug in Rust compiler; so for now we just create and store // these mapped functions per-thread. We should revisit it in the future and // ideally remove altogether. thread_local! { pub static GETTER_MAP_FN: v8::NamedPropertyGetterCallback = getter.map_fn_to(); pub static SETTER_MAP_FN: v8::NamedPropertySetterCallback = setter.map_fn_to(); pub static QUERY_MAP_FN: v8::NamedPropertyQueryCallback = query.map_fn_to(); pub static DELETER_MAP_FN: v8::NamedPropertyDeleterCallback = deleter.map_fn_to(); pub static ENUMERATOR_MAP_FN: v8::NamedPropertyEnumeratorCallback = enumerator.map_fn_to(); pub static DEFINER_MAP_FN: v8::NamedPropertyDefinerCallback = definer.map_fn_to(); pub static DESCRIPTOR_MAP_FN: v8::NamedPropertyGetterCallback = descriptor.map_fn_to(); } /// Convert an ASCII string to a UTF-16 byte encoding of the string. const fn str_to_utf16<const N: usize>(s: &str) -> [u16; N] { let mut out = [0_u16; N]; let mut i = 0; let bytes = s.as_bytes(); assert!(N == bytes.len()); while i < bytes.len() { assert!(bytes[i] < 128, "only works for ASCII strings"); out[i] = bytes[i] as u16; i += 1; } out } // ext/node changes the global object to be a proxy object that intercepts all // property accesses for globals that are different between Node and Deno and // dynamically returns a different value depending on if the accessing code is // in node_modules/ or not. // // To make this performant, a v8 named property handler is used, that only // intercepts property accesses for properties that are not already present on // the global object (it is non-masking). This means that in the common case, // when a user accesses a global that is the same between Node and Deno (like // Uint8Array or fetch), the proxy overhead is avoided. // // The Deno and Node specific globals are stored in a struct in a context slot. // // These are the globals that are handled: // - clearInterval (both, but different implementation) // - clearTimeout (both, but different implementation) // - process (always available in Node, while the availability in Deno depends // on project creation time in Deno Deploy) // - setInterval (both, but different implementation) // - setTimeout (both, but different implementation) // - window (deno only) // UTF-16 encodings of the managed globals. THIS LIST MUST BE SORTED. #[rustfmt::skip] const MANAGED_GLOBALS: [&[u16]; 6] = [ &str_to_utf16::<13>("clearInterval"), &str_to_utf16::<12>("clearTimeout"), &str_to_utf16::<7>("process"), &str_to_utf16::<11>("setInterval"), &str_to_utf16::<10>("setTimeout"), &str_to_utf16::<6>("window"), ]; // Calculates the shortest & longest length of global var names const MANAGED_GLOBALS_INFO: (usize, usize) = { let l = MANAGED_GLOBALS[0].len(); let (mut longest, mut shortest, mut i) = (l, l, 1); while i < MANAGED_GLOBALS.len() { let l = MANAGED_GLOBALS[i].len(); if l > longest { longest = l } if l < shortest { shortest = l } i += 1; } (shortest, longest) }; const SHORTEST_MANAGED_GLOBAL: usize = MANAGED_GLOBALS_INFO.0; const LONGEST_MANAGED_GLOBAL: usize = MANAGED_GLOBALS_INFO.1; #[derive(Debug, Clone, Copy)] enum Mode { Deno, Node, } pub struct GlobalsStorage { deno_globals: v8::Global<v8::Object>, node_globals: v8::Global<v8::Object>, } impl GlobalsStorage { fn inner_for_mode(&self, mode: Mode) -> v8::Global<v8::Object> { match mode { Mode::Deno => &self.deno_globals, Mode::Node => &self.node_globals, } .clone() } } pub fn global_template_middleware<'s>( _scope: &mut v8::PinScope<'s, '_, ()>, template: v8::Local<'s, v8::ObjectTemplate>, ) -> v8::Local<'s, v8::ObjectTemplate> { let mut config = v8::NamedPropertyHandlerConfiguration::new().flags( v8::PropertyHandlerFlags::NON_MASKING | v8::PropertyHandlerFlags::HAS_NO_SIDE_EFFECT, ); config = GETTER_MAP_FN.with(|getter| config.getter_raw(*getter)); config = SETTER_MAP_FN.with(|setter| config.setter_raw(*setter)); config = QUERY_MAP_FN.with(|query| config.query_raw(*query)); config = DELETER_MAP_FN.with(|deleter| config.deleter_raw(*deleter)); config = ENUMERATOR_MAP_FN.with(|enumerator| config.enumerator_raw(*enumerator)); config = DEFINER_MAP_FN.with(|definer| config.definer_raw(*definer)); config = DESCRIPTOR_MAP_FN.with(|descriptor| config.descriptor_raw(*descriptor)); template.set_named_property_handler(config); template } pub fn global_object_middleware<'s>( scope: &mut v8::PinScope<'s, '_>, global: v8::Local<'s, v8::Object>, ) { // ensure the global object is not Object.prototype let object_key = v8::String::new_external_onebyte_static(scope, b"Object").unwrap(); let object = global .get(scope, object_key.into()) .unwrap() .to_object(scope) .unwrap(); let prototype_key = v8::String::new_external_onebyte_static(scope, b"prototype").unwrap(); let object_prototype = object .get(scope, prototype_key.into()) .unwrap() .to_object(scope) .unwrap(); assert_ne!(global, object_prototype); // globalThis.__bootstrap.ext_node_denoGlobals and // globalThis.__bootstrap.ext_node_nodeGlobals are the objects that contain // the Deno and Node specific globals respectively. If they do not yet exist // on the global object, create them as null prototype objects. let bootstrap_key = v8::String::new_external_onebyte_static(scope, b"__bootstrap").unwrap(); let bootstrap = match global.get(scope, bootstrap_key.into()) { Some(value) if value.is_object() => value.to_object(scope).unwrap(), Some(value) if value.is_undefined() => { let null = v8::null(scope); let obj = v8::Object::with_prototype_and_properties(scope, null.into(), &[], &[]); global.set(scope, bootstrap_key.into(), obj.into()); obj } _ => panic!("__bootstrap should not be tampered with"), }; let deno_globals_key = v8::String::new_external_onebyte_static(scope, b"ext_node_denoGlobals") .unwrap(); let deno_globals = match bootstrap.get(scope, deno_globals_key.into()) { Some(value) if value.is_object() => value, Some(value) if value.is_undefined() => { let null = v8::null(scope); let obj = v8::Object::with_prototype_and_properties(scope, null.into(), &[], &[]) .into(); bootstrap.set(scope, deno_globals_key.into(), obj); obj } _ => panic!("__bootstrap.ext_node_denoGlobals should not be tampered with"), }; let deno_globals_obj: v8::Local<v8::Object> = deno_globals.try_into().unwrap(); let deno_globals = v8::Global::new(scope, deno_globals_obj); let node_globals_key = v8::String::new_external_onebyte_static(scope, b"ext_node_nodeGlobals") .unwrap(); let node_globals = match bootstrap.get(scope, node_globals_key.into()) { Some(value) if value.is_object() => value, Some(value) if value.is_undefined() => { let null = v8::null(scope); let obj = v8::Object::with_prototype_and_properties(scope, null.into(), &[], &[]) .into(); bootstrap.set(scope, node_globals_key.into(), obj); obj } _ => panic!("__bootstrap.ext_node_nodeGlobals should not be tampered with"), }; let node_globals_obj: v8::Local<v8::Object> = node_globals.try_into().unwrap(); let node_globals = v8::Global::new(scope, node_globals_obj); // Create the storage struct and store it in a context slot. let storage = GlobalsStorage { deno_globals, node_globals, }; scope.get_current_context().set_slot(Rc::new(storage)); } fn is_managed_key( scope: &mut v8::PinScope<'_, '_>, key: v8::Local<v8::Name>, ) -> bool { let Ok(str): Result<v8::Local<v8::String>, _> = key.try_into() else { return false; }; let len = str.length(); #[allow(clippy::manual_range_contains)] if len < SHORTEST_MANAGED_GLOBAL || len > LONGEST_MANAGED_GLOBAL { return false; } let buf = &mut [0u16; LONGEST_MANAGED_GLOBAL]; str.write_v2(scope, 0, buf.as_mut_slice(), v8::WriteFlags::empty()); MANAGED_GLOBALS.binary_search(&&buf[..len]).is_ok() } fn current_mode(scope: &mut v8::PinScope<'_, '_>) -> Mode { let Some(host_defined_options) = scope.get_current_host_defined_options() else { return Mode::Deno; }; // SAFETY: host defined options must always be a PrimitiveArray in current V8. let host_defined_options = unsafe { v8::Local::<v8::PrimitiveArray>::cast_unchecked(host_defined_options) }; if host_defined_options.length() < 1 { return Mode::Deno; } let is_node = host_defined_options.get(scope, 0).is_true(); if is_node { Mode::Node } else { Mode::Deno } } pub fn getter<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue, ) -> v8::Intercepted { if !is_managed_key(scope, key) { return v8::Intercepted::No; }; let this = args.this(); let mode = current_mode(scope); let context = scope.get_current_context(); let inner = { let Some(storage) = context.get_slot::<GlobalsStorage>() else { return v8::Intercepted::No; }; storage.inner_for_mode(mode) }; let inner = v8::Local::new(scope, inner); if !inner.has_own_property(scope, key).unwrap_or(false) { return v8::Intercepted::No; } let Some(value) = inner.get_with_receiver(scope, key.into(), this) else { return v8::Intercepted::No; }; rv.set(value); v8::Intercepted::Yes } pub fn setter<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, value: v8::Local<'s, v8::Value>, args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue<()>, ) -> v8::Intercepted { if !is_managed_key(scope, key) { return v8::Intercepted::No; }; let this = args.this(); let mode = current_mode(scope); let context = scope.get_current_context(); let inner = { let Some(storage) = context.get_slot::<GlobalsStorage>() else { return v8::Intercepted::No; }; storage.inner_for_mode(mode) }; let inner = v8::Local::new(scope, inner); let Some(success) = inner.set_with_receiver(scope, key.into(), value, this) else { return v8::Intercepted::No; }; rv.set_bool(success); v8::Intercepted::Yes } pub fn query<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, _args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue<v8::Integer>, ) -> v8::Intercepted { if !is_managed_key(scope, key) { return v8::Intercepted::No; }; let mode = current_mode(scope); let context = scope.get_current_context(); let inner = { let Some(storage) = context.get_slot::<GlobalsStorage>() else { return v8::Intercepted::No; }; storage.inner_for_mode(mode) }; let inner = v8::Local::new(scope, inner); let Some(true) = inner.has_own_property(scope, key) else { return v8::Intercepted::No; }; let Some(attributes) = inner.get_property_attributes(scope, key.into()) else { return v8::Intercepted::No; }; rv.set_uint32(attributes.as_u32()); v8::Intercepted::Yes } pub fn deleter<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue<v8::Boolean>, ) -> v8::Intercepted { if !is_managed_key(scope, key) { return v8::Intercepted::No; }; let mode = current_mode(scope); let context = scope.get_current_context(); let inner = { let Some(storage) = context.get_slot::<GlobalsStorage>() else { return v8::Intercepted::No; }; storage.inner_for_mode(mode) }; let inner = v8::Local::new(scope, inner); let Some(success) = inner.delete(scope, key.into()) else { return v8::Intercepted::No; }; if args.should_throw_on_error() && !success { let message = v8::String::new(scope, "Cannot delete property").unwrap(); let exception = v8::Exception::type_error(scope, message); scope.throw_exception(exception); return v8::Intercepted::Yes; } rv.set_bool(success); v8::Intercepted::Yes } pub fn enumerator<'s>( scope: &mut v8::PinScope<'s, '_>, _args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue<v8::Array>, ) { let mode = current_mode(scope); let context = scope.get_current_context(); let inner = { let Some(storage) = context.get_slot::<GlobalsStorage>() else { return; }; storage.inner_for_mode(mode) }; let inner = v8::Local::new(scope, inner); let Some(array) = inner.get_property_names( scope, GetPropertyNamesArgs { mode: v8::KeyCollectionMode::OwnOnly, property_filter: v8::PropertyFilter::ALL_PROPERTIES, ..Default::default() }, ) else { return; }; rv.set(array); } pub fn definer<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, descriptor: &v8::PropertyDescriptor, args: v8::PropertyCallbackArguments<'s>, _rv: v8::ReturnValue<()>, ) -> v8::Intercepted { if !is_managed_key(scope, key) { return v8::Intercepted::No; }; let mode = current_mode(scope); let context = scope.get_current_context(); let inner = { let Some(storage) = context.get_slot::<GlobalsStorage>() else { return v8::Intercepted::No; }; storage.inner_for_mode(mode) }; let inner = v8::Local::new(scope, inner); let Some(success) = inner.define_property(scope, key, descriptor) else { return v8::Intercepted::No; }; if args.should_throw_on_error() && !success { let message = v8::String::new(scope, "Cannot define property").unwrap(); let exception = v8::Exception::type_error(scope, message); scope.throw_exception(exception); } v8::Intercepted::Yes } pub fn descriptor<'s>( scope: &mut v8::PinScope<'s, '_>, key: v8::Local<'s, v8::Name>, _args: v8::PropertyCallbackArguments<'s>, mut rv: v8::ReturnValue, ) -> v8::Intercepted { if !is_managed_key(scope, key) { return v8::Intercepted::No; }; let mode = current_mode(scope); v8::tc_scope!(scope, scope); let context = scope.get_current_context(); let inner = { let Some(storage) = context.get_slot::<GlobalsStorage>() else { return v8::Intercepted::No; }; storage.inner_for_mode(mode) }; let inner = v8::Local::new(scope, inner); let Some(descriptor) = inner.get_own_property_descriptor(scope, key) else { scope.rethrow().expect("to have caught an exception"); return v8::Intercepted::Yes; }; if descriptor.is_undefined() { return v8::Intercepted::No; } rv.set(descriptor); v8::Intercepted::Yes }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false
denoland/deno
https://github.com/denoland/deno/blob/7222e85d435b977de1ab810db067b86f29e6444f/ext/node/lib.rs
ext/node/lib.rs
// Copyright 2018-2025 the Deno authors. MIT license. #![deny(clippy::print_stderr)] #![deny(clippy::print_stdout)] #![allow(clippy::too_many_arguments)] use std::borrow::Cow; use std::path::Path; use deno_core::FastString; use deno_core::OpState; use deno_core::op2; use deno_core::url::Url; #[allow(unused_imports)] use deno_core::v8; use deno_core::v8::ExternalReference; use deno_error::JsErrorBox; use deno_permissions::OpenAccessKind; use deno_permissions::PermissionsContainer; use node_resolver::DenoIsBuiltInNodeModuleChecker; use node_resolver::InNpmPackageChecker; use node_resolver::IsBuiltInNodeModuleChecker; use node_resolver::NpmPackageFolderResolver; use node_resolver::PackageJsonResolverRc; use node_resolver::errors::PackageJsonLoadError; extern crate libz_sys as zlib; mod global; pub mod ops; pub use deno_package_json::PackageJson; use deno_permissions::PermissionCheckError; pub use node_resolver::DENO_SUPPORTED_BUILTIN_NODE_MODULES as SUPPORTED_BUILTIN_NODE_MODULES; pub use node_resolver::PathClean; use ops::handle_wrap::AsyncId; pub use ops::inspector::InspectorServerUrl; pub use ops::ipc::ChildPipeFd; use ops::vm; pub use ops::vm::ContextInitMode; pub use ops::vm::VM_CONTEXT_INDEX; pub use ops::vm::create_v8_context; pub use ops::vm::init_global_template; pub use crate::global::GlobalsStorage; use crate::global::global_object_middleware; use crate::global::global_template_middleware; pub fn is_builtin_node_module(module_name: &str) -> bool { DenoIsBuiltInNodeModuleChecker.is_builtin_node_module(module_name) } #[allow(clippy::disallowed_types)] pub type NodeRequireLoaderRc = std::rc::Rc<dyn NodeRequireLoader>; pub trait NodeRequireLoader { #[must_use = "the resolved return value to mitigate time-of-check to time-of-use issues"] fn ensure_read_permission<'a>( &self, permissions: &mut PermissionsContainer, path: Cow<'a, Path>, ) -> Result<Cow<'a, Path>, JsErrorBox>; fn load_text_file_lossy(&self, path: &Path) -> Result<FastString, JsErrorBox>; /// Get if the module kind is maybe CJS and loading should determine /// if its CJS or ESM. fn is_maybe_cjs(&self, specifier: &Url) -> Result<bool, PackageJsonLoadError>; fn resolve_require_node_module_paths(&self, from: &Path) -> Vec<String> { default_resolve_require_node_module_paths(from) } } pub fn default_resolve_require_node_module_paths(from: &Path) -> Vec<String> { let mut paths = Vec::with_capacity(from.components().count()); let mut current_path = from; let mut maybe_parent = Some(current_path); while let Some(parent) = maybe_parent { if !parent.ends_with("node_modules") { paths.push(parent.join("node_modules").to_string_lossy().into_owned()); } current_path = parent; maybe_parent = current_path.parent(); } paths } #[op2] #[string] fn op_node_build_os() -> String { env!("TARGET").split('-').nth(2).unwrap().to_string() } #[derive(Debug, thiserror::Error, deno_error::JsError)] enum DotEnvLoadErr { #[class(generic)] #[error(transparent)] DotEnv(#[from] dotenvy::Error), #[class(inherit)] #[error(transparent)] Permission( #[from] #[inherit] PermissionCheckError, ), } #[op2(fast)] #[undefined] fn op_node_load_env_file( state: &mut OpState, #[string] path: &str, ) -> Result<(), DotEnvLoadErr> { let path = state .borrow::<PermissionsContainer>() .check_open( Cow::Borrowed(Path::new(path)), OpenAccessKind::ReadNoFollow, Some("process.loadEnvFile"), ) .map_err(DotEnvLoadErr::Permission)?; dotenvy::from_filename(path).map_err(DotEnvLoadErr::DotEnv)?; Ok(()) } #[derive(Clone)] pub struct NodeExtInitServices< TInNpmPackageChecker: InNpmPackageChecker, TNpmPackageFolderResolver: NpmPackageFolderResolver, TSys: ExtNodeSys, > { pub node_require_loader: NodeRequireLoaderRc, pub node_resolver: NodeResolverRc<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys>, pub pkg_json_resolver: PackageJsonResolverRc<TSys>, pub sys: TSys, } deno_core::extension!(deno_node, deps = [ deno_io, deno_fs ], parameters = [TInNpmPackageChecker: InNpmPackageChecker, TNpmPackageFolderResolver: NpmPackageFolderResolver, TSys: ExtNodeSys], ops = [ ops::blocklist::op_socket_address_parse, ops::blocklist::op_socket_address_get_serialization, ops::blocklist::op_blocklist_new, ops::blocklist::op_blocklist_add_address, ops::blocklist::op_blocklist_add_range, ops::blocklist::op_blocklist_add_subnet, ops::blocklist::op_blocklist_check, ops::buffer::op_is_ascii, ops::buffer::op_is_utf8, ops::buffer::op_transcode, ops::buffer::op_node_buffer_compare, ops::buffer::op_node_buffer_compare_offset, ops::constant::op_node_fs_constants, ops::buffer::op_node_decode_utf8, ops::crypto::op_node_check_prime_async, ops::crypto::op_node_check_prime_bytes_async, ops::crypto::op_node_check_prime_bytes, ops::crypto::op_node_check_prime, ops::crypto::op_node_cipheriv_encrypt, ops::crypto::op_node_cipheriv_final, ops::crypto::op_node_cipheriv_set_aad, ops::crypto::op_node_cipheriv_take, ops::crypto::op_node_create_cipheriv, ops::crypto::op_node_create_decipheriv, ops::crypto::op_node_create_hash, ops::crypto::op_node_decipheriv_decrypt, ops::crypto::op_node_decipheriv_final, ops::crypto::op_node_decipheriv_set_aad, ops::crypto::op_node_decipheriv_auth_tag, ops::crypto::op_node_dh_compute_secret, ops::crypto::op_node_diffie_hellman, ops::crypto::op_node_ecdh_compute_public_key, ops::crypto::op_node_ecdh_compute_secret, ops::crypto::op_node_ecdh_encode_pubkey, ops::crypto::op_node_ecdh_generate_keys, ops::crypto::op_node_fill_random_async, ops::crypto::op_node_fill_random, ops::crypto::op_node_gen_prime_async, ops::crypto::op_node_gen_prime, ops::crypto::op_node_get_hash_size, ops::crypto::op_node_get_hashes, ops::crypto::op_node_hash_clone, ops::crypto::op_node_hash_digest_hex, ops::crypto::op_node_hash_digest, ops::crypto::op_node_hash_update_str, ops::crypto::op_node_hash_update, ops::crypto::op_node_hkdf_async, ops::crypto::op_node_hkdf, ops::crypto::op_node_pbkdf2_async, ops::crypto::op_node_pbkdf2, ops::crypto::op_node_pbkdf2_validate, ops::crypto::op_node_private_decrypt, ops::crypto::op_node_private_encrypt, ops::crypto::op_node_public_encrypt, ops::crypto::op_node_random_int, ops::crypto::op_node_scrypt_async, ops::crypto::op_node_scrypt_sync, ops::crypto::op_node_sign, ops::crypto::op_node_sign_ed25519, ops::crypto::op_node_verify, ops::crypto::op_node_verify_ed25519, ops::crypto::op_node_verify_spkac, ops::crypto::op_node_cert_export_public_key, ops::crypto::op_node_cert_export_challenge, ops::crypto::keys::op_node_create_private_key, ops::crypto::keys::op_node_create_ed_raw, ops::crypto::keys::op_node_create_rsa_jwk, ops::crypto::keys::op_node_create_ec_jwk, ops::crypto::keys::op_node_create_public_key, ops::crypto::keys::op_node_create_secret_key, ops::crypto::keys::op_node_derive_public_key_from_private_key, ops::crypto::keys::op_node_dh_keys_generate_and_export, ops::crypto::keys::op_node_export_private_key_der, ops::crypto::keys::op_node_export_private_key_jwk, ops::crypto::keys::op_node_export_private_key_pem, ops::crypto::keys::op_node_export_public_key_der, ops::crypto::keys::op_node_export_public_key_pem, ops::crypto::keys::op_node_export_public_key_jwk, ops::crypto::keys::op_node_export_secret_key_b64url, ops::crypto::keys::op_node_export_secret_key, ops::crypto::keys::op_node_generate_dh_group_key_async, ops::crypto::keys::op_node_generate_dh_group_key, ops::crypto::keys::op_node_generate_dh_key_async, ops::crypto::keys::op_node_generate_dh_key, ops::crypto::keys::op_node_generate_dsa_key_async, ops::crypto::keys::op_node_generate_dsa_key, ops::crypto::keys::op_node_generate_ec_key_async, ops::crypto::keys::op_node_generate_ec_key, ops::crypto::keys::op_node_generate_ed25519_key_async, ops::crypto::keys::op_node_generate_ed25519_key, ops::crypto::keys::op_node_generate_rsa_key_async, ops::crypto::keys::op_node_generate_rsa_key, ops::crypto::keys::op_node_generate_rsa_pss_key, ops::crypto::keys::op_node_generate_rsa_pss_key_async, ops::crypto::keys::op_node_generate_secret_key_async, ops::crypto::keys::op_node_generate_secret_key, ops::crypto::keys::op_node_generate_x25519_key_async, ops::crypto::keys::op_node_generate_x25519_key, ops::crypto::keys::op_node_get_asymmetric_key_details, ops::crypto::keys::op_node_get_asymmetric_key_type, ops::crypto::keys::op_node_get_private_key_from_pair, ops::crypto::keys::op_node_get_public_key_from_pair, ops::crypto::keys::op_node_get_symmetric_key_size, ops::crypto::keys::op_node_key_type, ops::crypto::x509::op_node_x509_parse, ops::crypto::x509::op_node_x509_ca, ops::crypto::x509::op_node_x509_check_email, ops::crypto::x509::op_node_x509_check_host, ops::crypto::x509::op_node_x509_fingerprint, ops::crypto::x509::op_node_x509_fingerprint256, ops::crypto::x509::op_node_x509_fingerprint512, ops::crypto::x509::op_node_x509_get_issuer, ops::crypto::x509::op_node_x509_get_subject, ops::crypto::x509::op_node_x509_get_valid_from, ops::crypto::x509::op_node_x509_get_valid_to, ops::crypto::x509::op_node_x509_get_serial_number, ops::crypto::x509::op_node_x509_key_usage, ops::crypto::x509::op_node_x509_public_key, ops::dns::op_node_getaddrinfo, ops::dns::op_node_getnameinfo, ops::fs::op_node_fs_exists_sync, ops::fs::op_node_fs_exists, ops::fs::op_node_lchmod_sync, ops::fs::op_node_lchmod, ops::fs::op_node_lchown_sync, ops::fs::op_node_lchown, ops::fs::op_node_lutimes_sync, ops::fs::op_node_lutimes, ops::fs::op_node_mkdtemp_sync, ops::fs::op_node_mkdtemp, ops::fs::op_node_open_sync, ops::fs::op_node_open, ops::fs::op_node_statfs_sync, ops::fs::op_node_statfs, ops::fs::op_node_file_from_fd, ops::winerror::op_node_sys_to_uv_error, ops::v8::op_v8_cached_data_version_tag, ops::v8::op_v8_get_heap_statistics, ops::v8::op_v8_get_wire_format_version, ops::v8::op_v8_new_deserializer, ops::v8::op_v8_new_serializer, ops::v8::op_v8_read_double, ops::v8::op_v8_read_header, ops::v8::op_v8_read_raw_bytes, ops::v8::op_v8_read_uint32, ops::v8::op_v8_read_uint64, ops::v8::op_v8_read_value, ops::v8::op_v8_release_buffer, ops::v8::op_v8_set_treat_array_buffer_views_as_host_objects, ops::v8::op_v8_transfer_array_buffer, ops::v8::op_v8_transfer_array_buffer_de, ops::v8::op_v8_write_double, ops::v8::op_v8_write_header, ops::v8::op_v8_write_raw_bytes, ops::v8::op_v8_write_uint32, ops::v8::op_v8_write_uint64, ops::v8::op_v8_write_value, ops::vm::op_vm_create_script, ops::vm::op_vm_create_context, ops::vm::op_vm_script_run_in_context, ops::vm::op_vm_is_context, ops::vm::op_vm_compile_function, ops::vm::op_vm_script_get_source_map_url, ops::vm::op_vm_script_create_cached_data, ops::idna::op_node_idna_domain_to_ascii, ops::idna::op_node_idna_domain_to_unicode, ops::idna::op_node_idna_punycode_to_ascii, ops::idna::op_node_idna_punycode_to_unicode, ops::idna::op_node_idna_punycode_decode, ops::idna::op_node_idna_punycode_encode, ops::zlib::op_zlib_crc32, ops::zlib::op_zlib_crc32_string, ops::handle_wrap::op_node_new_async_id, ops::http::op_node_http_fetch_response_upgrade, ops::http::op_node_http_request_with_conn, ops::http::op_node_http_response_reclaim_conn, ops::http::op_node_http_await_information, ops::http::op_node_http_await_response, ops::http2::op_http2_connect, ops::http2::op_http2_poll_client_connection, ops::http2::op_http2_client_request, ops::http2::op_http2_client_get_response, ops::http2::op_http2_client_get_response_body_chunk, ops::http2::op_http2_client_send_data, ops::http2::op_http2_client_reset_stream, ops::http2::op_http2_client_send_trailers, ops::http2::op_http2_client_get_response_trailers, ops::http2::op_http2_accept, ops::http2::op_http2_listen, ops::http2::op_http2_send_response, ops::os::op_node_os_get_priority, ops::os::op_node_os_set_priority, ops::os::op_node_os_user_info, ops::os::op_geteuid, ops::os::op_getegid, ops::os::op_cpus, ops::os::op_homedir, op_node_build_os, op_node_load_env_file, ops::require::op_require_can_parse_as_esm, ops::require::op_require_init_paths, ops::require::op_require_node_module_paths<TSys>, ops::require::op_require_proxy_path, ops::require::op_require_is_deno_dir_package<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys>, ops::require::op_require_resolve_deno_dir<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys>, ops::require::op_require_is_maybe_cjs, ops::require::op_require_is_request_relative, ops::require::op_require_resolve_lookup_paths, ops::require::op_require_try_self<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys>, ops::require::op_require_real_path<TSys>, ops::require::op_require_path_is_absolute, ops::require::op_require_path_dirname, ops::require::op_require_stat<TSys>, ops::require::op_require_path_resolve, ops::require::op_require_path_basename, ops::require::op_require_read_file, ops::require::op_require_as_file_path, ops::require::op_require_resolve_exports<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys>, ops::require::op_require_read_package_scope<TSys>, ops::require::op_require_package_imports_resolve<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys>, ops::require::op_require_break_on_next_statement, ops::util::op_node_guess_handle_type, ops::util::op_node_view_has_buffer, ops::util::op_node_get_own_non_index_properties, ops::util::op_node_call_is_from_dependency<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys>, ops::util::op_node_in_npm_package<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys>, ops::worker_threads::op_worker_threads_filename<TSys>, ops::ipc::op_node_child_ipc_pipe, ops::ipc::op_node_ipc_write_json, ops::ipc::op_node_ipc_read_json, ops::ipc::op_node_ipc_read_advanced, ops::ipc::op_node_ipc_write_advanced, ops::ipc::op_node_ipc_buffer_constructor, ops::ipc::op_node_ipc_ref, ops::ipc::op_node_ipc_unref, ops::process::op_node_process_kill, ops::process::op_node_process_setegid, ops::process::op_node_process_seteuid, ops::process::op_node_process_setgid, ops::process::op_node_process_setuid, ops::process::op_process_abort, ops::tls::op_get_root_certificates, ops::tls::op_tls_peer_certificate, ops::tls::op_tls_canonicalize_ipv4_address, ops::tls::op_node_tls_start, ops::tls::op_node_tls_handshake, ops::inspector::op_inspector_open, ops::inspector::op_inspector_close, ops::inspector::op_inspector_url, ops::inspector::op_inspector_wait, ops::inspector::op_inspector_connect, ops::inspector::op_inspector_dispatch, ops::inspector::op_inspector_disconnect, ops::inspector::op_inspector_emit_protocol_event, ops::inspector::op_inspector_enabled, ops::sqlite::op_node_database_backup, ], objects = [ ops::perf_hooks::EldHistogram, ops::sqlite::DatabaseSync, ops::sqlite::Session, ops::handle_wrap::AsyncWrap, ops::handle_wrap::HandleWrap, ops::sqlite::StatementSync, ops::crypto::digest::Hasher, ops::zlib::BrotliDecoder, ops::zlib::BrotliEncoder, ops::zlib::Zlib, ], esm_entry_point = "ext:deno_node/02_init.js", esm = [ dir "polyfills", "00_globals.js", "02_init.js", "_events.mjs", "_fs/_fs_access.ts", "_fs/_fs_appendFile.ts", "_fs/_fs_chmod.ts", "_fs/_fs_chown.ts", "_fs/_fs_close.ts", "_fs/_fs_common.ts", "_fs/_fs_constants.ts", "_fs/_fs_copy.ts", "_fs/_fs_cp.ts", "_fs/cp/cp.ts", "_fs/cp/cp_sync.ts", "_fs/_fs_dir.ts", "_fs/_fs_exists.ts", "_fs/_fs_fchmod.ts", "_fs/_fs_fchown.ts", "_fs/_fs_fdatasync.ts", "_fs/_fs_fstat.ts", "_fs/_fs_fsync.ts", "_fs/_fs_ftruncate.ts", "_fs/_fs_futimes.ts", "_fs/_fs_glob.ts", "_fs/_fs_lchmod.ts", "_fs/_fs_lchown.ts", "_fs/_fs_link.ts", "_fs/_fs_lstat.ts", "_fs/_fs_lutimes.ts", "_fs/_fs_mkdir.ts", "_fs/_fs_mkdtemp.ts", "_fs/_fs_open.ts", "_fs/_fs_opendir.ts", "_fs/_fs_read.ts", "_fs/_fs_readdir.ts", "_fs/_fs_readFile.ts", "_fs/_fs_readlink.ts", "_fs/_fs_readv.ts", "_fs/_fs_realpath.ts", "_fs/_fs_rename.ts", "_fs/_fs_rm.ts", "_fs/_fs_rmdir.ts", "_fs/_fs_stat.ts", "_fs/_fs_statfs.ts", "_fs/_fs_symlink.ts", "_fs/_fs_truncate.ts", "_fs/_fs_unlink.ts", "_fs/_fs_utimes.ts", "_fs/_fs_watch.ts", "_fs/_fs_write.ts", "_fs/_fs_writeFile.ts", "_fs/_fs_writev.ts", "_next_tick.ts", "_process/exiting.ts", "_process/process.ts", "_process/streams.mjs", "_readline.mjs", "_util/_util_callbackify.js", "_util/asserts.ts", "_util/async.ts", "_util/os.ts", "_util/std_asserts.ts", "_utils.ts", "_zlib_binding.mjs", "assertion_error.ts", "internal_binding/_libuv_winerror.ts", "internal_binding/_listen.ts", "internal_binding/_node.ts", "internal_binding/_timingSafeEqual.ts", "internal_binding/_utils.ts", "internal_binding/ares.ts", "internal_binding/async_wrap.ts", "internal_binding/buffer.ts", "internal_binding/cares_wrap.ts", "internal_binding/connection_wrap.ts", "internal_binding/constants.ts", "internal_binding/crypto.ts", "internal_binding/handle_wrap.ts", "internal_binding/http_parser.ts", "internal_binding/mod.ts", "internal_binding/node_file.ts", "internal_binding/node_options.ts", "internal_binding/pipe_wrap.ts", "internal_binding/stream_wrap.ts", "internal_binding/string_decoder.ts", "internal_binding/symbols.ts", "internal_binding/tcp_wrap.ts", "internal_binding/tty_wrap.ts", "internal_binding/types.ts", "internal_binding/udp_wrap.ts", "internal_binding/util.ts", "internal_binding/uv.ts", "internal/assert/calltracker.js", "internal/assert.mjs", "internal/async_hooks.ts", "internal/blocklist.mjs", "internal/buffer.mjs", "internal/child_process.ts", "internal/cli_table.ts", "internal/console/constructor.mjs", "internal/constants.ts", "internal/crypto/_keys.ts", "internal/crypto/_randomBytes.ts", "internal/crypto/_randomFill.mjs", "internal/crypto/_randomInt.ts", "internal/crypto/certificate.ts", "internal/crypto/cipher.ts", "internal/crypto/constants.ts", "internal/crypto/diffiehellman.ts", "internal/crypto/hash.ts", "internal/crypto/hkdf.ts", "internal/crypto/keygen.ts", "internal/crypto/keys.ts", "internal/crypto/pbkdf2.ts", "internal/crypto/random.ts", "internal/crypto/scrypt.ts", "internal/crypto/sig.ts", "internal/crypto/util.ts", "internal/crypto/x509.ts", "internal/dgram.ts", "internal/dns/promises.ts", "internal/dns/utils.ts", "internal/dtrace.ts", "internal/error_codes.ts", "internal/errors.ts", "internal/event_target.mjs", "internal/events/abort_listener.mjs", "internal/fixed_queue.ts", "internal/fs/streams.mjs", "internal/fs/utils.mjs", "internal/fs/handle.ts", "internal/hide_stack_frames.ts", "internal/http.ts", "internal/http2/util.ts", "internal/idna.ts", "internal/net.ts", "internal/normalize_encoding.ts", "internal/options.ts", "internal/primordials.mjs", "internal/process/per_thread.mjs", "internal/process/report.ts", "internal/process/warning.ts", "internal/querystring.ts", "internal/readline/callbacks.mjs", "internal/readline/emitKeypressEvents.mjs", "internal/readline/interface.mjs", "internal/readline/promises.mjs", "internal/readline/symbols.mjs", "internal/readline/utils.mjs", "internal/stream_base_commons.ts", "internal/streams/add-abort-signal.js", "internal/streams/compose.js", "internal/streams/destroy.js", "internal/streams/duplexify.js", "internal/streams/duplexpair.js", "internal/streams/end-of-stream.js", "internal/streams/from.js", "internal/streams/lazy_transform.js", "internal/streams/legacy.js", "internal/streams/operators.js", "internal/streams/pipeline.js", "internal/streams/state.js", "internal/streams/utils.js", "internal/test/binding.ts", "internal/timers.mjs", "internal/url.ts", "internal/util.mjs", "internal/util/comparisons.ts", "internal/util/debuglog.ts", "internal/util/inspect.mjs", "internal/util/parse_args/parse_args.js", "internal/util/parse_args/utils.js", "internal/util/types.ts", "internal/validators.mjs", "internal/webstreams/adapters.js", "path/_constants.ts", "path/_interface.ts", "path/_util.ts", "path/_posix.ts", "path/_win32.ts", "path/common.ts", "path/mod.ts", "path/separator.ts", "readline/promises.ts", "node:_http_agent" = "_http_agent.mjs", "node:_http_common" = "_http_common.ts", "node:_http_outgoing" = "_http_outgoing.ts", "node:_http_server" = "_http_server.ts", "node:_stream_duplex" = "internal/streams/duplex.js", "node:_stream_passthrough" = "internal/streams/passthrough.js", "node:_stream_readable" = "internal/streams/readable.js", "node:_stream_transform" = "internal/streams/transform.js", "node:_stream_writable" = "internal/streams/writable.js", "node:_tls_common" = "_tls_common.ts", "node:_tls_wrap" = "_tls_wrap.js", "node:assert" = "assert.ts", "node:assert/strict" = "assert/strict.ts", "node:async_hooks" = "async_hooks.ts", "node:buffer" = "buffer.ts", "node:child_process" = "child_process.ts", "node:cluster" = "cluster.ts", "node:console" = "console.ts", "node:constants" = "constants.ts", "node:crypto" = "crypto.ts", "node:dgram" = "dgram.ts", "node:diagnostics_channel" = "diagnostics_channel.js", "node:dns" = "dns.ts", "node:dns/promises" = "dns/promises.ts", "node:domain" = "domain.ts", "node:events" = "events.ts", "node:fs" = "fs.ts", "node:fs/promises" = "fs/promises.ts", "node:http" = "http.ts", "node:http2" = "http2.ts", "node:https" = "https.ts", "node:inspector" = "inspector.js", "node:inspector/promises" = "inspector/promises.js", "node:module" = "01_require.js", "node:net" = "net.ts", "node:os" = "os.ts", "node:path" = "path.ts", "node:path/posix" = "path/posix.ts", "node:path/win32" = "path/win32.ts", "node:perf_hooks" = "perf_hooks.js", "node:process" = "process.ts", "node:punycode" = "punycode.ts", "node:querystring" = "querystring.js", "node:readline" = "readline.ts", "node:readline/promises" = "readline/promises.ts", "node:repl" = "repl.ts", "node:sqlite" = "sqlite.ts", "node:stream" = "stream.ts", "node:stream/consumers" = "stream/consumers.js", "node:stream/promises" = "stream/promises.js", "node:stream/web" = "stream/web.js", "node:string_decoder" = "string_decoder.ts", "node:sys" = "sys.ts", "node:test" = "testing.ts", "node:timers" = "timers.ts", "node:timers/promises" = "timers/promises.ts", "node:tls" = "tls.ts", "node:trace_events" = "trace_events.ts", "node:tty" = "tty.js", "node:url" = "url.ts", "node:util" = "util.ts", "node:util/types" = "util/types.ts", "node:v8" = "v8.ts", "node:vm" = "vm.js", "node:wasi" = "wasi.ts", "node:worker_threads" = "worker_threads.ts", "node:zlib" = "zlib.js", ], lazy_loaded_esm = [ dir "polyfills", "deps/minimatch.js", ], options = { maybe_init: Option<NodeExtInitServices<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys>>, fs: deno_fs::FileSystemRc, }, state = |state, options| { state.put(options.fs.clone()); if let Some(init) = &options.maybe_init { state.put(init.sys.clone()); state.put(init.node_require_loader.clone()); state.put(init.node_resolver.clone()); state.put(init.pkg_json_resolver.clone()); } state.put(AsyncId::default()); }, global_template_middleware = global_template_middleware, global_object_middleware = global_object_middleware, customizer = |ext: &mut deno_core::Extension| { let external_references = [ vm::QUERY_MAP_FN.with(|query| { ExternalReference { named_query: *query, } }), vm::GETTER_MAP_FN.with(|getter| { ExternalReference { named_getter: *getter, } }), vm::SETTER_MAP_FN.with(|setter| { ExternalReference { named_setter: *setter, } }), vm::DESCRIPTOR_MAP_FN.with(|descriptor| { ExternalReference { named_getter: *descriptor, } }), vm::DELETER_MAP_FN.with(|deleter| { ExternalReference { named_deleter: *deleter, } }), vm::ENUMERATOR_MAP_FN.with(|enumerator| { ExternalReference { enumerator: *enumerator, } }), vm::DEFINER_MAP_FN.with(|definer| { ExternalReference { named_definer: *definer, } }), vm::INDEXED_QUERY_MAP_FN.with(|query| { ExternalReference { indexed_query: *query, } }), vm::INDEXED_GETTER_MAP_FN.with(|getter| { ExternalReference { indexed_getter: *getter, } }), vm::INDEXED_SETTER_MAP_FN.with(|setter| { ExternalReference { indexed_setter: *setter, } }), vm::INDEXED_DESCRIPTOR_MAP_FN.with(|descriptor| { ExternalReference { indexed_getter: *descriptor, } }), vm::INDEXED_DELETER_MAP_FN.with(|deleter| { ExternalReference { indexed_deleter: *deleter, } }), vm::INDEXED_DEFINER_MAP_FN.with(|definer| { ExternalReference { indexed_definer: *definer, } }), vm::INDEXED_ENUMERATOR_MAP_FN.with(|enumerator| { ExternalReference { enumerator: *enumerator, } }), global::GETTER_MAP_FN.with(|getter| { ExternalReference { named_getter: *getter, } }), global::SETTER_MAP_FN.with(|setter| { ExternalReference { named_setter: *setter, } }), global::QUERY_MAP_FN.with(|query| { ExternalReference { named_query: *query, } }), global::DELETER_MAP_FN.with(|deleter| { ExternalReference { named_deleter: *deleter, } }), global::ENUMERATOR_MAP_FN.with(|enumerator| { ExternalReference { enumerator: *enumerator, } }), global::DEFINER_MAP_FN.with(|definer| { ExternalReference { named_definer: *definer, } }), global::DESCRIPTOR_MAP_FN.with(|descriptor| { ExternalReference { named_getter: *descriptor, } }), ]; ext.external_references.to_mut().extend(external_references); }, ); #[sys_traits::auto_impl] pub trait ExtNodeSys: node_resolver::NodeResolverSys + sys_traits::EnvCurrentDir + Clone { } pub type NodeResolver<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys> = node_resolver::NodeResolver< TInNpmPackageChecker, DenoIsBuiltInNodeModuleChecker, TNpmPackageFolderResolver, TSys, >; #[allow(clippy::disallowed_types)] pub type NodeResolverRc<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys> = deno_fs::sync::MaybeArc< NodeResolver<TInNpmPackageChecker, TNpmPackageFolderResolver, TSys>, >; #[allow(clippy::disallowed_types)] pub fn create_host_defined_options<'s>( scope: &mut v8::PinScope<'s, '_>, ) -> v8::Local<'s, v8::Data> { let host_defined_options = v8::PrimitiveArray::new(scope, 1); let value = v8::Boolean::new(scope, true); host_defined_options.set(scope, 0, value.into()); host_defined_options.into() }
rust
MIT
7222e85d435b977de1ab810db067b86f29e6444f
2026-01-04T15:31:58.521149Z
false