1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-21 15:04:11 -05:00

refactor: use once_cell instead of lazy_static (#13135)

This commit is contained in:
Divy Srivastava 2021-12-19 02:44:42 +05:30 committed by GitHub
parent 3db18bf9e6
commit 6de53b631f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
27 changed files with 434 additions and 313 deletions

13
Cargo.lock generated
View file

@ -672,7 +672,6 @@ dependencies = [
"http", "http",
"import_map", "import_map",
"jsonc-parser", "jsonc-parser",
"lazy_static",
"libc", "libc",
"log", "log",
"lspower", "lspower",
@ -755,9 +754,9 @@ dependencies = [
"anyhow", "anyhow",
"futures", "futures",
"indexmap", "indexmap",
"lazy_static",
"libc", "libc",
"log", "log",
"once_cell",
"parking_lot", "parking_lot",
"pin-project", "pin-project",
"serde", "serde",
@ -778,8 +777,8 @@ dependencies = [
"deno_core", "deno_core",
"deno_web", "deno_web",
"elliptic-curve", "elliptic-curve",
"lazy_static",
"num-traits", "num-traits",
"once_cell",
"p256", "p256",
"p384", "p384",
"rand 0.8.4", "rand 0.8.4",
@ -934,11 +933,11 @@ dependencies = [
"fwdansi", "fwdansi",
"http", "http",
"hyper", "hyper",
"lazy_static",
"libc", "libc",
"log", "log",
"nix", "nix",
"notify", "notify",
"once_cell",
"regex", "regex",
"ring", "ring",
"serde", "serde",
@ -968,7 +967,7 @@ name = "deno_tls"
version = "0.16.0" version = "0.16.0"
dependencies = [ dependencies = [
"deno_core", "deno_core",
"lazy_static", "once_cell",
"rustls", "rustls",
"rustls-native-certs", "rustls-native-certs",
"rustls-pemfile", "rustls-pemfile",
@ -2406,9 +2405,9 @@ dependencies = [
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.8.0" version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56" checksum = "da32515d9f6e6e489d7bc9d84c71b060db7247dc035bbe44eac88cf87486d8d5"
[[package]] [[package]]
name = "opaque-debug" name = "opaque-debug"

View file

@ -62,13 +62,12 @@ fancy-regex = "=0.7.1"
http = "=0.2.4" http = "=0.2.4"
import_map = "=0.4.0" import_map = "=0.4.0"
jsonc-parser = { version = "=0.17.0", features = ["serde"] } jsonc-parser = { version = "=0.17.0", features = ["serde"] }
lazy_static = "=1.4.0"
libc = "=0.2.106" libc = "=0.2.106"
log = { version = "=0.4.14", features = ["serde"] } log = { version = "=0.4.14", features = ["serde"] }
lspower = "=1.4.0" lspower = "=1.4.0"
notify = "=5.0.0-pre.12" notify = "=5.0.0-pre.12"
num_cpus = "=1.13.0" num_cpus = "=1.13.0"
once_cell = "=1.8.0" once_cell = "=1.9.0"
percent-encoding = "=2.1.0" percent-encoding = "=2.1.0"
pin-project = "=1.0.8" pin-project = "=1.0.8"
rand = { version = "=0.8.4", features = ["small_rng"] } rand = { version = "=0.8.4", features = ["small_rng"] }

View file

@ -7,6 +7,7 @@ use deno_core::error::AnyError;
use deno_core::located_script_name; use deno_core::located_script_name;
use deno_core::url::Url; use deno_core::url::Url;
use deno_core::JsRuntime; use deno_core::JsRuntime;
use once_cell::sync::Lazy;
pub use esm_resolver::check_if_should_use_esm_loader; pub use esm_resolver::check_if_should_use_esm_loader;
pub(crate) use esm_resolver::NodeEsmResolver; pub(crate) use esm_resolver::NodeEsmResolver;
@ -62,15 +63,27 @@ static SUPPORTED_MODULES: &[&str] = &[
"zlib", "zlib",
]; ];
lazy_static::lazy_static! { static NODE_COMPAT_URL: Lazy<String> = Lazy::new(|| {
static ref NODE_COMPAT_URL: String = std::env::var("DENO_NODE_COMPAT_URL").map(String::into).ok() std::env::var("DENO_NODE_COMPAT_URL")
.unwrap_or_else(|| STD_URL_STR.to_string()); .map(String::into)
static ref GLOBAL_URL_STR: String = format!("{}node/global.ts", NODE_COMPAT_URL.as_str()); .ok()
pub(crate) static ref GLOBAL_URL: Url = Url::parse(&GLOBAL_URL_STR).unwrap(); .unwrap_or_else(|| STD_URL_STR.to_string())
static ref MODULE_URL_STR: String = format!("{}node/module.ts", NODE_COMPAT_URL.as_str()); });
pub(crate) static ref MODULE_URL: Url = Url::parse(&MODULE_URL_STR).unwrap();
static ref COMPAT_IMPORT_URL: Url = Url::parse("flags:compat").unwrap(); static GLOBAL_URL_STR: Lazy<String> =
} Lazy::new(|| format!("{}node/global.ts", NODE_COMPAT_URL.as_str()));
pub(crate) static GLOBAL_URL: Lazy<Url> =
Lazy::new(|| Url::parse(&GLOBAL_URL_STR).unwrap());
static MODULE_URL_STR: Lazy<String> =
Lazy::new(|| format!("{}node/module.ts", NODE_COMPAT_URL.as_str()));
pub(crate) static MODULE_URL: Lazy<Url> =
Lazy::new(|| Url::parse(&MODULE_URL_STR).unwrap());
static COMPAT_IMPORT_URL: Lazy<Url> =
Lazy::new(|| Url::parse("flags:compat").unwrap());
/// Provide imports into a module graph when the compat flag is true. /// Provide imports into a module graph when the compat flag is true.
pub(crate) fn get_node_imports() -> Vec<(Url, Vec<String>)> { pub(crate) fn get_node_imports() -> Vec<(Url, Vec<String>)> {

View file

@ -7,6 +7,7 @@ use deno_core::serde::Deserializer;
use deno_core::serde::Serialize; use deno_core::serde::Serialize;
use deno_core::serde::Serializer; use deno_core::serde::Serializer;
use deno_graph::ModuleGraphError; use deno_graph::ModuleGraphError;
use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use std::error::Error; use std::error::Error;
use std::fmt; use std::fmt;
@ -65,13 +66,13 @@ const UNSTABLE_DENO_PROPS: &[&str] = &[
"utimeSync", "utimeSync",
]; ];
lazy_static::lazy_static! { static MSG_MISSING_PROPERTY_DENO: Lazy<Regex> = Lazy::new(|| {
static ref MSG_MISSING_PROPERTY_DENO: Regex =
Regex::new(r#"Property '([^']+)' does not exist on type 'typeof Deno'"#) Regex::new(r#"Property '([^']+)' does not exist on type 'typeof Deno'"#)
.unwrap(); .unwrap()
static ref MSG_SUGGESTION: Regex = });
Regex::new(r#" Did you mean '([^']+)'\?"#).unwrap();
} static MSG_SUGGESTION: Lazy<Regex> =
Lazy::new(|| Regex::new(r#" Did you mean '([^']+)'\?"#).unwrap());
/// Potentially convert a "raw" diagnostic message from TSC to something that /// Potentially convert a "raw" diagnostic message from TSC to something that
/// provides a more sensible error message given a Deno runtime context. /// provides a more sensible error message given a Deno runtime context.

View file

@ -12,6 +12,7 @@ use deno_core::url::Url;
use deno_runtime::permissions::PermissionsOptions; use deno_runtime::permissions::PermissionsOptions;
use log::debug; use log::debug;
use log::Level; use log::Level;
use once_cell::sync::Lazy;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::num::NonZeroU32; use std::num::NonZeroU32;
use std::num::NonZeroU8; use std::num::NonZeroU8;
@ -19,8 +20,8 @@ use std::num::NonZeroUsize;
use std::path::PathBuf; use std::path::PathBuf;
use std::str::FromStr; use std::str::FromStr;
lazy_static::lazy_static! { static LONG_VERSION: Lazy<String> = Lazy::new(|| {
static ref LONG_VERSION: String = format!( format!(
"{} ({}, {})\nv8 {}\ntypescript {}", "{} ({}, {})\nv8 {}\ntypescript {}",
crate::version::deno(), crate::version::deno(),
if crate::version::is_canary() { if crate::version::is_canary() {
@ -31,8 +32,8 @@ lazy_static::lazy_static! {
env!("TARGET"), env!("TARGET"),
deno_core::v8_version(), deno_core::v8_version(),
crate::version::TYPESCRIPT crate::version::TYPESCRIPT
); )
} });
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct BundleFlags { pub struct BundleFlags {

View file

@ -18,22 +18,26 @@ use deno_core::ModuleSpecifier;
use lspower::lsp; use lspower::lsp;
use lspower::lsp::Position; use lspower::lsp::Position;
use lspower::lsp::Range; use lspower::lsp::Range;
use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::collections::HashMap; use std::collections::HashMap;
lazy_static::lazy_static! { /// Diagnostic error codes which actually are the same, and so when grouping
/// Diagnostic error codes which actually are the same, and so when grouping /// fixes we treat them the same.
/// fixes we treat them the same. static FIX_ALL_ERROR_CODES: Lazy<HashMap<&'static str, &'static str>> =
static ref FIX_ALL_ERROR_CODES: HashMap<&'static str, &'static str> = Lazy::new(|| {
(&[("2339", "2339"), ("2345", "2339"),]) (&[("2339", "2339"), ("2345", "2339")])
.iter() .iter()
.cloned() .cloned()
.collect(); .collect()
});
/// Fixes which help determine if there is a preferred fix when there are /// Fixes which help determine if there is a preferred fix when there are
/// multiple fixes available. /// multiple fixes available.
static ref PREFERRED_FIXES: HashMap<&'static str, (u32, bool)> = (&[ static PREFERRED_FIXES: Lazy<HashMap<&'static str, (u32, bool)>> =
Lazy::new(|| {
(&[
("annotateWithTypeFromJSDoc", (1, false)), ("annotateWithTypeFromJSDoc", (1, false)),
("constructorForDerivedNeedSuperCall", (1, false)), ("constructorForDerivedNeedSuperCall", (1, false)),
("extendsInterfaceBecomesImplements", (1, false)), ("extendsInterfaceBecomesImplements", (1, false)),
@ -49,21 +53,23 @@ lazy_static::lazy_static! {
]) ])
.iter() .iter()
.cloned() .cloned()
.collect(); .collect()
});
static ref IMPORT_SPECIFIER_RE: Regex = Regex::new(r#"\sfrom\s+["']([^"']*)["']"#).unwrap(); static IMPORT_SPECIFIER_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"\sfrom\s+["']([^"']*)["']"#).unwrap());
static ref DENO_TYPES_RE: Regex = static DENO_TYPES_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r#"(?i)^\s*@deno-types\s*=\s*(?:["']([^"']+)["']|(\S+))"#) Regex::new(r#"(?i)^\s*@deno-types\s*=\s*(?:["']([^"']+)["']|(\S+))"#).unwrap()
.unwrap(); });
static ref TRIPLE_SLASH_REFERENCE_RE: Regex =
Regex::new(r"(?i)^/\s*<reference\s.*?/>").unwrap();
static ref PATH_REFERENCE_RE: Regex =
Regex::new(r#"(?i)\spath\s*=\s*["']([^"']*)["']"#).unwrap();
static ref TYPES_REFERENCE_RE: Regex =
Regex::new(r#"(?i)\stypes\s*=\s*["']([^"']*)["']"#).unwrap();
} static TRIPLE_SLASH_REFERENCE_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?i)^/\s*<reference\s.*?/>").unwrap());
static PATH_REFERENCE_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"(?i)\spath\s*=\s*["']([^"']*)["']"#).unwrap());
static TYPES_REFERENCE_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r#"(?i)\stypes\s*=\s*["']([^"']*)["']"#).unwrap());
const SUPPORTED_EXTENSIONS: &[&str] = &[".ts", ".tsx", ".js", ".jsx", ".mjs"]; const SUPPORTED_EXTENSIONS: &[&str] = &[".ts", ".tsx", ".js", ".jsx", ".mjs"];

View file

@ -20,16 +20,18 @@ use deno_core::serde_json;
use deno_core::serde_json::json; use deno_core::serde_json::json;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use lspower::lsp; use lspower::lsp;
use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashSet; use std::collections::HashSet;
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
lazy_static::lazy_static! { static ABSTRACT_MODIFIER: Lazy<Regex> =
static ref ABSTRACT_MODIFIER: Regex = Regex::new(r"\babstract\b").unwrap(); Lazy::new(|| Regex::new(r"\babstract\b").unwrap());
static ref EXPORT_MODIFIER: Regex = Regex::new(r"\bexport\b").unwrap();
} static EXPORT_MODIFIER: Lazy<Regex> =
Lazy::new(|| Regex::new(r"\bexport\b").unwrap());
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
pub enum CodeLensSource { pub enum CodeLensSource {

View file

@ -24,6 +24,7 @@ use deno_core::url;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use deno_graph::Module; use deno_graph::Module;
use lspower::lsp; use lspower::lsp;
use once_cell::sync::Lazy;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::HashSet; use std::collections::HashSet;
@ -35,20 +36,39 @@ use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use std::time::SystemTime; use std::time::SystemTime;
lazy_static::lazy_static! { static JS_HEADERS: Lazy<HashMap<String, String>> = Lazy::new(|| {
static ref JS_HEADERS: HashMap<String, String> = ([ ([(
("content-type".to_string(), "application/javascript".to_string()) "content-type".to_string(),
]).iter().cloned().collect(); "application/javascript".to_string(),
static ref JSX_HEADERS: HashMap<String, String> = ([ )])
("content-type".to_string(), "text/jsx".to_string()) .iter()
]).iter().cloned().collect(); .cloned()
static ref TS_HEADERS: HashMap<String, String> = ([ .collect()
("content-type".to_string(), "application/typescript".to_string()) });
]).iter().cloned().collect();
static ref TSX_HEADERS: HashMap<String, String> = ([ static JSX_HEADERS: Lazy<HashMap<String, String>> = Lazy::new(|| {
("content-type".to_string(), "text/tsx".to_string()) ([("content-type".to_string(), "text/jsx".to_string())])
]).iter().cloned().collect(); .iter()
} .cloned()
.collect()
});
static TS_HEADERS: Lazy<HashMap<String, String>> = Lazy::new(|| {
([(
"content-type".to_string(),
"application/typescript".to_string(),
)])
.iter()
.cloned()
.collect()
});
static TSX_HEADERS: Lazy<HashMap<String, String>> = Lazy::new(|| {
([("content-type".to_string(), "text/tsx".to_string())])
.iter()
.cloned()
.collect()
});
/// The default parser from `deno_graph` does not include the configuration /// The default parser from `deno_graph` does not include the configuration
/// options we require here, and so implementing an empty struct that provides /// options we require here, and so implementing an empty struct that provides

View file

@ -29,15 +29,14 @@
use deno_core::anyhow::anyhow; use deno_core::anyhow::anyhow;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use fancy_regex::Regex as FancyRegex; use fancy_regex::Regex as FancyRegex;
use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt; use std::fmt;
use std::iter::Peekable; use std::iter::Peekable;
lazy_static::lazy_static! { static ESCAPE_STRING_RE: Lazy<Regex> =
static ref ESCAPE_STRING_RE: Regex = Lazy::new(|| Regex::new(r"([.+*?=^!:${}()\[\]|/\\])").unwrap());
Regex::new(r"([.+*?=^!:${}()\[\]|/\\])").unwrap();
}
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
enum TokenType { enum TokenType {

View file

@ -7,6 +7,7 @@ use deno_core::serde::Deserialize;
use deno_core::serde::Serialize; use deno_core::serde::Serialize;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use lspower::lsp; use lspower::lsp;
use once_cell::sync::Lazy;
pub struct RefactorCodeActionKind { pub struct RefactorCodeActionKind {
pub kind: lsp::CodeActionKind, pub kind: lsp::CodeActionKind,
@ -19,58 +20,120 @@ impl RefactorCodeActionKind {
} }
} }
lazy_static::lazy_static! { pub static EXTRACT_FUNCTION: Lazy<RefactorCodeActionKind> =
pub static ref EXTRACT_FUNCTION: RefactorCodeActionKind = RefactorCodeActionKind { Lazy::new(|| RefactorCodeActionKind {
kind : [lsp::CodeActionKind::REFACTOR_EXTRACT.as_str(), "function"].join(".").into(), kind: [lsp::CodeActionKind::REFACTOR_EXTRACT.as_str(), "function"]
.join(".")
.into(),
matches_callback: Box::new(|tag: &str| tag.starts_with("function_")), matches_callback: Box::new(|tag: &str| tag.starts_with("function_")),
}; });
pub static ref EXTRACT_CONSTANT: RefactorCodeActionKind = RefactorCodeActionKind { pub static EXTRACT_CONSTANT: Lazy<RefactorCodeActionKind> =
kind : [lsp::CodeActionKind::REFACTOR_EXTRACT.as_str(), "constant"].join(".").into(), Lazy::new(|| RefactorCodeActionKind {
kind: [lsp::CodeActionKind::REFACTOR_EXTRACT.as_str(), "constant"]
.join(".")
.into(),
matches_callback: Box::new(|tag: &str| tag.starts_with("constant_")), matches_callback: Box::new(|tag: &str| tag.starts_with("constant_")),
}; });
pub static ref EXTRACT_TYPE: RefactorCodeActionKind = RefactorCodeActionKind { pub static EXTRACT_TYPE: Lazy<RefactorCodeActionKind> =
kind : [lsp::CodeActionKind::REFACTOR_EXTRACT.as_str(), "type"].join(".").into(), Lazy::new(|| RefactorCodeActionKind {
matches_callback: Box::new(|tag: &str| tag.starts_with("Extract to type alias")), kind: [lsp::CodeActionKind::REFACTOR_EXTRACT.as_str(), "type"]
}; .join(".")
.into(),
matches_callback: Box::new(|tag: &str| {
tag.starts_with("Extract to type alias")
}),
});
pub static ref EXTRACT_INTERFACE: RefactorCodeActionKind = RefactorCodeActionKind { pub static EXTRACT_INTERFACE: Lazy<RefactorCodeActionKind> =
kind : [lsp::CodeActionKind::REFACTOR_EXTRACT.as_str(), "interface"].join(".").into(), Lazy::new(|| RefactorCodeActionKind {
matches_callback: Box::new(|tag: &str| tag.starts_with("Extract to interface")), kind: [lsp::CodeActionKind::REFACTOR_EXTRACT.as_str(), "interface"]
}; .join(".")
.into(),
matches_callback: Box::new(|tag: &str| {
tag.starts_with("Extract to interface")
}),
});
pub static ref MOVE_NEWFILE: RefactorCodeActionKind = RefactorCodeActionKind { pub static MOVE_NEWFILE: Lazy<RefactorCodeActionKind> =
kind : [lsp::CodeActionKind::REFACTOR.as_str(), "move", "newFile"].join(".").into(), Lazy::new(|| RefactorCodeActionKind {
matches_callback: Box::new(|tag: &str| tag.starts_with("Move to a new file")), kind: [lsp::CodeActionKind::REFACTOR.as_str(), "move", "newFile"]
}; .join(".")
.into(),
matches_callback: Box::new(|tag: &str| {
tag.starts_with("Move to a new file")
}),
});
pub static ref REWRITE_IMPORT: RefactorCodeActionKind = RefactorCodeActionKind { pub static REWRITE_IMPORT: Lazy<RefactorCodeActionKind> =
kind : [lsp::CodeActionKind::REFACTOR_REWRITE.as_str(), "import"].join(".").into(), Lazy::new(|| RefactorCodeActionKind {
matches_callback: Box::new(|tag: &str| tag.starts_with("Convert namespace import") || tag.starts_with("Convert named imports")), kind: [lsp::CodeActionKind::REFACTOR_REWRITE.as_str(), "import"]
}; .join(".")
.into(),
matches_callback: Box::new(|tag: &str| {
tag.starts_with("Convert namespace import")
|| tag.starts_with("Convert named imports")
}),
});
pub static ref REWRITE_EXPORT: RefactorCodeActionKind = RefactorCodeActionKind { pub static REWRITE_EXPORT: Lazy<RefactorCodeActionKind> =
kind : [lsp::CodeActionKind::REFACTOR_REWRITE.as_str(), "export"].join(".").into(), Lazy::new(|| RefactorCodeActionKind {
matches_callback: Box::new(|tag: &str| tag.starts_with("Convert default export") || tag.starts_with("Convert named export")), kind: [lsp::CodeActionKind::REFACTOR_REWRITE.as_str(), "export"]
}; .join(".")
.into(),
matches_callback: Box::new(|tag: &str| {
tag.starts_with("Convert default export")
|| tag.starts_with("Convert named export")
}),
});
pub static ref REWRITE_ARROW_BRACES: RefactorCodeActionKind = RefactorCodeActionKind { pub static REWRITE_ARROW_BRACES: Lazy<RefactorCodeActionKind> =
kind : [lsp::CodeActionKind::REFACTOR_REWRITE.as_str(), "arrow", "braces"].join(".").into(), Lazy::new(|| RefactorCodeActionKind {
matches_callback: Box::new(|tag: &str| tag.starts_with("Add or remove braces in an arrow function")), kind: [
}; lsp::CodeActionKind::REFACTOR_REWRITE.as_str(),
"arrow",
"braces",
]
.join(".")
.into(),
matches_callback: Box::new(|tag: &str| {
tag.starts_with("Add or remove braces in an arrow function")
}),
});
pub static ref REWRITE_PARAMETERS_TO_DESTRUCTURED: RefactorCodeActionKind = RefactorCodeActionKind { pub static REWRITE_PARAMETERS_TO_DESTRUCTURED: Lazy<RefactorCodeActionKind> =
kind : [lsp::CodeActionKind::REFACTOR_REWRITE.as_str(), "parameters", "toDestructured"].join(".").into(), Lazy::new(|| RefactorCodeActionKind {
matches_callback: Box::new(|tag: &str| tag.starts_with("Convert parameters to destructured object")), kind: [
}; lsp::CodeActionKind::REFACTOR_REWRITE.as_str(),
"parameters",
"toDestructured",
]
.join(".")
.into(),
matches_callback: Box::new(|tag: &str| {
tag.starts_with("Convert parameters to destructured object")
}),
});
pub static ref REWRITE_PROPERTY_GENERATEACCESSORS: RefactorCodeActionKind = RefactorCodeActionKind { pub static REWRITE_PROPERTY_GENERATEACCESSORS: Lazy<RefactorCodeActionKind> =
kind : [lsp::CodeActionKind::REFACTOR_REWRITE.as_str(), "property", "generateAccessors"].join(".").into(), Lazy::new(|| RefactorCodeActionKind {
matches_callback: Box::new(|tag: &str| tag.starts_with("Generate 'get' and 'set' accessors")), kind: [
}; lsp::CodeActionKind::REFACTOR_REWRITE.as_str(),
"property",
"generateAccessors",
]
.join(".")
.into(),
matches_callback: Box::new(|tag: &str| {
tag.starts_with("Generate 'get' and 'set' accessors")
}),
});
pub static ref ALL_KNOWN_REFACTOR_ACTION_KINDS: Vec<&'static RefactorCodeActionKind> = vec![ pub static ALL_KNOWN_REFACTOR_ACTION_KINDS: Lazy<
Vec<&'static RefactorCodeActionKind>,
> = Lazy::new(|| {
vec![
&EXTRACT_FUNCTION, &EXTRACT_FUNCTION,
&EXTRACT_CONSTANT, &EXTRACT_CONSTANT,
&EXTRACT_TYPE, &EXTRACT_TYPE,
@ -80,9 +143,9 @@ lazy_static::lazy_static! {
&REWRITE_EXPORT, &REWRITE_EXPORT,
&REWRITE_ARROW_BRACES, &REWRITE_ARROW_BRACES,
&REWRITE_PARAMETERS_TO_DESTRUCTURED, &REWRITE_PARAMETERS_TO_DESTRUCTURED,
&REWRITE_PROPERTY_GENERATEACCESSORS &REWRITE_PROPERTY_GENERATEACCESSORS,
]; ]
} });
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]

View file

@ -31,6 +31,7 @@ use deno_runtime::deno_web::BlobStore;
use deno_runtime::permissions::Permissions; use deno_runtime::permissions::Permissions;
use log::error; use log::error;
use lspower::lsp; use lspower::lsp;
use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use std::collections::HashMap; use std::collections::HashMap;
use std::path::Path; use std::path::Path;
@ -61,10 +62,8 @@ const COMPONENT: &percent_encoding::AsciiSet = &percent_encoding::CONTROLS
.add(b'+') .add(b'+')
.add(b','); .add(b',');
lazy_static::lazy_static! { static REPLACEMENT_VARIABLE_RE: Lazy<Regex> =
static ref REPLACEMENT_VARIABLE_RE: Regex = Lazy::new(|| Regex::new(r"\$\{\{?(\w+)\}?\}").unwrap());
Regex::new(r"\$\{\{?(\w+)\}?\}").unwrap();
}
fn base_url(url: &Url) -> String { fn base_url(url: &Url) -> String {
url.origin().ascii_serialization() url.origin().ascii_serialization()

View file

@ -42,6 +42,7 @@ use log::warn;
use lspower::jsonrpc::Error as LspError; use lspower::jsonrpc::Error as LspError;
use lspower::jsonrpc::Result as LspResult; use lspower::jsonrpc::Result as LspResult;
use lspower::lsp; use lspower::lsp;
use once_cell::sync::Lazy;
use regex::Captures; use regex::Captures;
use regex::Regex; use regex::Regex;
use std::borrow::Cow; use std::borrow::Cow;
@ -56,16 +57,23 @@ use text_size::TextSize;
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tokio::sync::oneshot; use tokio::sync::oneshot;
lazy_static::lazy_static! { static BRACKET_ACCESSOR_RE: Lazy<Regex> =
static ref BRACKET_ACCESSOR_RE: Regex = Regex::new(r#"^\[['"](.+)[\['"]\]$"#).unwrap(); Lazy::new(|| Regex::new(r#"^\[['"](.+)[\['"]\]$"#).unwrap());
static ref CAPTION_RE: Regex = Regex::new(r"<caption>(.*?)</caption>\s*\r?\n((?:\s|\S)*)").unwrap(); static CAPTION_RE: Lazy<Regex> = Lazy::new(|| {
static ref CODEBLOCK_RE: Regex = Regex::new(r"^\s*[~`]{3}").unwrap(); Regex::new(r"<caption>(.*?)</caption>\s*\r?\n((?:\s|\S)*)").unwrap()
static ref EMAIL_MATCH_RE: Regex = Regex::new(r"(.+)\s<([-.\w]+@[-.\w]+)>").unwrap(); });
static ref JSDOC_LINKS_RE: Regex = Regex::new(r"(?i)\{@(link|linkplain|linkcode) (https?://[^ |}]+?)(?:[| ]([^{}\n]+?))?\}").unwrap(); static CODEBLOCK_RE: Lazy<Regex> =
static ref PART_KIND_MODIFIER_RE: Regex = Regex::new(r",|\s+").unwrap(); Lazy::new(|| Regex::new(r"^\s*[~`]{3}").unwrap());
static ref PART_RE: Regex = Regex::new(r"^(\S+)\s*-?\s*").unwrap(); static EMAIL_MATCH_RE: Lazy<Regex> =
static ref SCOPE_RE: Regex = Regex::new(r"scope_(\d)").unwrap(); Lazy::new(|| Regex::new(r"(.+)\s<([-.\w]+@[-.\w]+)>").unwrap());
} static JSDOC_LINKS_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"(?i)\{@(link|linkplain|linkcode) (https?://[^ |}]+?)(?:[| ]([^{}\n]+?))?\}").unwrap()
});
static PART_KIND_MODIFIER_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r",|\s+").unwrap());
static PART_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(\S+)\s*-?\s*").unwrap());
static SCOPE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"scope_(\d)").unwrap());
const FILE_EXTENSION_KIND_MODIFIERS: &[&str] = const FILE_EXTENSION_KIND_MODIFIERS: &[&str] =
&[".d.ts", ".ts", ".tsx", ".js", ".jsx", ".json"]; &[".d.ts", ".ts", ".tsx", ".js", ".jsx", ".json"];

View file

@ -9,13 +9,13 @@ use deno_core::error::AnyError;
use deno_core::url::Position; use deno_core::url::Position;
use deno_core::url::Url; use deno_core::url::Url;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use once_cell::sync::Lazy;
use std::collections::HashMap; use std::collections::HashMap;
lazy_static::lazy_static! { /// Used in situations where a default URL needs to be used where otherwise a
/// Used in situations where a default URL needs to be used where otherwise a /// panic is undesired.
/// panic is undesired. pub(crate) static INVALID_SPECIFIER: Lazy<ModuleSpecifier> =
pub(crate) static ref INVALID_SPECIFIER: ModuleSpecifier = ModuleSpecifier::parse("deno://invalid").unwrap(); Lazy::new(|| ModuleSpecifier::parse("deno://invalid").unwrap());
}
/// Matches the `encodeURIComponent()` encoding from JavaScript, which matches /// Matches the `encodeURIComponent()` encoding from JavaScript, which matches
/// the component percent encoding set. /// the component percent encoding set.

View file

@ -8,6 +8,7 @@ use deno_core::error::AnyError;
use deno_core::resolve_url_or_path; use deno_core::resolve_url_or_path;
use deno_core::url::Url; use deno_core::url::Url;
use log::Level; use log::Level;
use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use regex::RegexBuilder; use regex::RegexBuilder;
use std::env; use std::env;
@ -21,15 +22,12 @@ use std::path::PathBuf;
#[cfg(not(windows))] #[cfg(not(windows))]
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
lazy_static::lazy_static! { static EXEC_NAME_RE: Lazy<Regex> = Lazy::new(|| {
static ref EXEC_NAME_RE: Regex = RegexBuilder::new( RegexBuilder::new(r"^[a-z][\w-]*$")
r"^[a-z][\w-]*$" .case_insensitive(true)
).case_insensitive(true).build().unwrap(); .build()
// Regular expression to test disk driver letter. eg "C:\\User\username\path\to" .unwrap()
static ref DRIVE_LETTER_REG: Regex = RegexBuilder::new( });
r"^[c-z]:"
).case_insensitive(true).build().unwrap();
}
fn validate_name(exec_name: &str) -> Result<(), AnyError> { fn validate_name(exec_name: &str) -> Result<(), AnyError> {
if EXEC_NAME_RE.is_match(exec_name) { if EXEC_NAME_RE.is_match(exec_name) {
@ -375,13 +373,12 @@ fn is_in_path(dir: &Path) -> bool {
mod tests { mod tests {
use super::*; use super::*;
use deno_core::parking_lot::Mutex; use deno_core::parking_lot::Mutex;
use once_cell::sync::Lazy;
use std::process::Command; use std::process::Command;
use tempfile::TempDir; use tempfile::TempDir;
use test_util::testdata_path; use test_util::testdata_path;
lazy_static::lazy_static! { pub static ENV_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
pub static ref ENV_LOCK: Mutex<()> = Mutex::new(());
}
#[test] #[test]
fn install_infer_name_from_url() { fn install_infer_name_from_url() {

View file

@ -7,6 +7,7 @@ use deno_core::error::AnyError;
use deno_core::futures::StreamExt; use deno_core::futures::StreamExt;
use deno_runtime::deno_fetch::reqwest; use deno_runtime::deno_fetch::reqwest;
use deno_runtime::deno_fetch::reqwest::Client; use deno_runtime::deno_fetch::reqwest::Client;
use once_cell::sync::Lazy;
use semver_parser::version::parse as semver_parse; use semver_parser::version::parse as semver_parse;
use std::fs; use std::fs;
use std::io::Write; use std::io::Write;
@ -15,9 +16,8 @@ use std::path::PathBuf;
use std::process::Command; use std::process::Command;
use tempfile::TempDir; use tempfile::TempDir;
lazy_static::lazy_static! { static ARCHIVE_NAME: Lazy<String> =
static ref ARCHIVE_NAME: String = format!("deno-{}.zip", env!("TARGET")); Lazy::new(|| format!("deno-{}.zip", env!("TARGET")));
}
const RELEASE_URL: &str = "https://github.com/denoland/deno/releases"; const RELEASE_URL: &str = "https://github.com/denoland/deno/releases";

View file

@ -25,6 +25,7 @@ use deno_core::ModuleSpecifier;
use deno_core::OpFn; use deno_core::OpFn;
use deno_core::RuntimeOptions; use deno_core::RuntimeOptions;
use deno_core::Snapshot; use deno_core::Snapshot;
use once_cell::sync::Lazy;
use std::collections::HashMap; use std::collections::HashMap;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
@ -63,10 +64,14 @@ macro_rules! inc {
}; };
} }
lazy_static::lazy_static! { /// Contains static assets that are not preloaded in the compiler snapshot.
/// Contains static assets that are not preloaded in the compiler snapshot. pub(crate) static STATIC_ASSETS: Lazy<HashMap<&'static str, &'static str>> =
pub(crate) static ref STATIC_ASSETS: HashMap<&'static str, &'static str> = (&[ Lazy::new(|| {
("lib.dom.asynciterable.d.ts", inc!("lib.dom.asynciterable.d.ts")), (&[
(
"lib.dom.asynciterable.d.ts",
inc!("lib.dom.asynciterable.d.ts"),
),
("lib.dom.d.ts", inc!("lib.dom.d.ts")), ("lib.dom.d.ts", inc!("lib.dom.d.ts")),
("lib.dom.iterable.d.ts", inc!("lib.dom.iterable.d.ts")), ("lib.dom.iterable.d.ts", inc!("lib.dom.iterable.d.ts")),
("lib.es6.d.ts", inc!("lib.es6.d.ts")), ("lib.es6.d.ts", inc!("lib.es6.d.ts")),
@ -79,13 +84,19 @@ lazy_static::lazy_static! {
("lib.esnext.full.d.ts", inc!("lib.esnext.full.d.ts")), ("lib.esnext.full.d.ts", inc!("lib.esnext.full.d.ts")),
("lib.scripthost.d.ts", inc!("lib.scripthost.d.ts")), ("lib.scripthost.d.ts", inc!("lib.scripthost.d.ts")),
("lib.webworker.d.ts", inc!("lib.webworker.d.ts")), ("lib.webworker.d.ts", inc!("lib.webworker.d.ts")),
("lib.webworker.importscripts.d.ts", inc!("lib.webworker.importscripts.d.ts")), (
("lib.webworker.iterable.d.ts", inc!("lib.webworker.iterable.d.ts")), "lib.webworker.importscripts.d.ts",
inc!("lib.webworker.importscripts.d.ts"),
),
(
"lib.webworker.iterable.d.ts",
inc!("lib.webworker.iterable.d.ts"),
),
]) ])
.iter() .iter()
.cloned() .cloned()
.collect(); .collect()
} });
/// Retrieve a static asset that are included in the binary. /// Retrieve a static asset that are included in the binary.
pub fn get_asset(asset: &str) -> Option<&'static str> { pub fn get_asset(asset: &str) -> Option<&'static str> {

View file

@ -16,9 +16,9 @@ path = "lib.rs"
anyhow = "1.0.43" anyhow = "1.0.43"
futures = "0.3.16" futures = "0.3.16"
indexmap = "1.7.0" indexmap = "1.7.0"
lazy_static = "1.4.0"
libc = "0.2.106" libc = "0.2.106"
log = "0.4.14" log = "0.4.14"
once_cell = "=1.9.0"
parking_lot = "0.11.1" parking_lot = "0.11.1"
pin-project = "1.0.7" pin-project = "1.0.7"
serde = { version = "1.0.129", features = ["derive"] } serde = { version = "1.0.129", features = ["derive"] }

View file

@ -17,6 +17,7 @@ use crate::PromiseId;
use crate::ZeroCopyBuf; use crate::ZeroCopyBuf;
use anyhow::Error; use anyhow::Error;
use log::debug; use log::debug;
use once_cell::sync::Lazy;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize; use serde::Serialize;
use serde_v8::to_v8; use serde_v8::to_v8;
@ -35,71 +36,71 @@ const UNDEFINED_OP_ID_MSG: &str =
This error is often caused by a typo in an op name, or not calling This error is often caused by a typo in an op name, or not calling
JsRuntime::sync_ops_cache() after JsRuntime initialization."; JsRuntime::sync_ops_cache() after JsRuntime initialization.";
lazy_static::lazy_static! { pub static EXTERNAL_REFERENCES: Lazy<v8::ExternalReferences> =
pub static ref EXTERNAL_REFERENCES: v8::ExternalReferences = Lazy::new(|| {
v8::ExternalReferences::new(&[ v8::ExternalReferences::new(&[
v8::ExternalReference { v8::ExternalReference {
function: opcall_async.map_fn_to() function: opcall_async.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: opcall_sync.map_fn_to() function: opcall_sync.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: ref_op.map_fn_to() function: ref_op.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: unref_op.map_fn_to() function: unref_op.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: set_macrotask_callback.map_fn_to() function: set_macrotask_callback.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: set_nexttick_callback.map_fn_to() function: set_nexttick_callback.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: set_promise_reject_callback.map_fn_to() function: set_promise_reject_callback.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: set_uncaught_exception_callback.map_fn_to() function: set_uncaught_exception_callback.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: run_microtasks.map_fn_to() function: run_microtasks.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: has_tick_scheduled.map_fn_to() function: has_tick_scheduled.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: set_has_tick_scheduled.map_fn_to() function: set_has_tick_scheduled.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: eval_context.map_fn_to() function: eval_context.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: queue_microtask.map_fn_to() function: queue_microtask.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: create_host_object.map_fn_to() function: create_host_object.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: encode.map_fn_to() function: encode.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: decode.map_fn_to() function: decode.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: serialize.map_fn_to() function: serialize.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: deserialize.map_fn_to() function: deserialize.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: get_promise_details.map_fn_to() function: get_promise_details.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: get_proxy_details.map_fn_to() function: get_proxy_details.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: is_proxy.map_fn_to() function: is_proxy.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: memory_usage.map_fn_to(), function: memory_usage.map_fn_to(),
@ -108,10 +109,10 @@ lazy_static::lazy_static! {
function: call_console.map_fn_to(), function: call_console.map_fn_to(),
}, },
v8::ExternalReference { v8::ExternalReference {
function: set_wasm_streaming_callback.map_fn_to() function: set_wasm_streaming_callback.map_fn_to(),
} },
]); ])
} });
pub fn script_origin<'a>( pub fn script_origin<'a>(
s: &mut v8::HandleScope<'a>, s: &mut v8::HandleScope<'a>,

View file

@ -20,8 +20,8 @@ block-modes = "0.8.1"
deno_core = { version = "0.111.0", path = "../../core" } deno_core = { version = "0.111.0", path = "../../core" }
deno_web = { version = "0.60.0", path = "../web" } deno_web = { version = "0.60.0", path = "../web" }
elliptic-curve = { version = "0.10.6", features = ["std", "pem"] } elliptic-curve = { version = "0.10.6", features = ["std", "pem"] }
lazy_static = "1.4.0"
num-traits = "0.2.14" num-traits = "0.2.14"
once_cell = "=1.9.0"
p256 = { version = "0.9.0", features = ["ecdh"] } p256 = { version = "0.9.0", features = ["ecdh"] }
p384 = "0.8.0" p384 = "0.8.0"
rand = "0.8.4" rand = "0.8.4"

View file

@ -1,11 +1,13 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use crate::shared::*;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::OpState; use deno_core::OpState;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use elliptic_curve::rand_core::OsRng; use elliptic_curve::rand_core::OsRng;
use num_traits::FromPrimitive; use num_traits::FromPrimitive;
use once_cell::sync::Lazy;
use ring::rand::SecureRandom; use ring::rand::SecureRandom;
use ring::signature::EcdsaKeyPair; use ring::signature::EcdsaKeyPair;
use rsa::pkcs1::ToRsaPrivateKey; use rsa::pkcs1::ToRsaPrivateKey;
@ -13,13 +15,11 @@ use rsa::BigUint;
use rsa::RsaPrivateKey; use rsa::RsaPrivateKey;
use serde::Deserialize; use serde::Deserialize;
use crate::shared::*;
// Allowlist for RSA public exponents. // Allowlist for RSA public exponents.
lazy_static::lazy_static! { static PUB_EXPONENT_1: Lazy<BigUint> =
static ref PUB_EXPONENT_1: BigUint = BigUint::from_u64(3).unwrap(); Lazy::new(|| BigUint::from_u64(3).unwrap());
static ref PUB_EXPONENT_2: BigUint = BigUint::from_u64(65537).unwrap(); static PUB_EXPONENT_2: Lazy<BigUint> =
} Lazy::new(|| BigUint::from_u64(65537).unwrap());
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase", tag = "algorithm")] #[serde(rename_all = "camelCase", tag = "algorithm")]

View file

@ -17,8 +17,6 @@ use std::num::NonZeroU32;
use std::rc::Rc; use std::rc::Rc;
use block_modes::BlockMode; use block_modes::BlockMode;
use lazy_static::lazy_static;
use num_traits::cast::FromPrimitive;
use p256::elliptic_curve::sec1::FromEncodedPoint; use p256::elliptic_curve::sec1::FromEncodedPoint;
use p256::pkcs8::FromPrivateKey; use p256::pkcs8::FromPrivateKey;
use rand::rngs::OsRng; use rand::rngs::OsRng;
@ -42,7 +40,6 @@ use rsa::pkcs1::der::Encodable;
use rsa::pkcs1::FromRsaPrivateKey; use rsa::pkcs1::FromRsaPrivateKey;
use rsa::pkcs1::FromRsaPublicKey; use rsa::pkcs1::FromRsaPublicKey;
use rsa::pkcs8::der::asn1; use rsa::pkcs8::der::asn1;
use rsa::BigUint;
use rsa::PublicKey; use rsa::PublicKey;
use rsa::RsaPrivateKey; use rsa::RsaPrivateKey;
use rsa::RsaPublicKey; use rsa::RsaPublicKey;
@ -73,12 +70,7 @@ use crate::key::HkdfOutput;
use crate::shared::ID_MFG1; use crate::shared::ID_MFG1;
use crate::shared::ID_P_SPECIFIED; use crate::shared::ID_P_SPECIFIED;
use crate::shared::ID_SHA1_OID; use crate::shared::ID_SHA1_OID;
use once_cell::sync::Lazy;
// Allowlist for RSA public exponents.
lazy_static! {
static ref PUB_EXPONENT_1: BigUint = BigUint::from_u64(3).unwrap();
static ref PUB_EXPONENT_2: BigUint = BigUint::from_u64(65537).unwrap();
}
pub fn init(maybe_seed: Option<u64>) -> Extension { pub fn init(maybe_seed: Option<u64>) -> Extension {
Extension::builder() Extension::builder()
@ -642,53 +634,64 @@ const SALT_LENGTH_TAG: rsa::pkcs8::der::TagNumber =
const P_SOURCE_ALGORITHM_TAG: rsa::pkcs8::der::TagNumber = const P_SOURCE_ALGORITHM_TAG: rsa::pkcs8::der::TagNumber =
rsa::pkcs8::der::TagNumber::new(2); rsa::pkcs8::der::TagNumber::new(2);
lazy_static! { // Default HashAlgorithm for RSASSA-PSS-params (sha1)
// Default HashAlgorithm for RSASSA-PSS-params (sha1) //
// // sha1 HashAlgorithm ::= {
// sha1 HashAlgorithm ::= { // algorithm id-sha1,
// algorithm id-sha1, // parameters SHA1Parameters : NULL
// parameters SHA1Parameters : NULL // }
// } //
// // SHA1Parameters ::= NULL
// SHA1Parameters ::= NULL static SHA1_HASH_ALGORITHM: Lazy<rsa::pkcs8::AlgorithmIdentifier<'static>> =
static ref SHA1_HASH_ALGORITHM: rsa::pkcs8::AlgorithmIdentifier<'static> = rsa::pkcs8::AlgorithmIdentifier { Lazy::new(|| {
rsa::pkcs8::AlgorithmIdentifier {
// id-sha1 // id-sha1
oid: ID_SHA1_OID, oid: ID_SHA1_OID,
// NULL // NULL
parameters: Some(asn1::Any::from(asn1::Null)), parameters: Some(asn1::Any::from(asn1::Null)),
}; }
});
// TODO(@littledivy): `pkcs8` should provide AlgorithmIdentifier to Any conversion. // TODO(@littledivy): `pkcs8` should provide AlgorithmIdentifier to Any conversion.
static ref ENCODED_SHA1_HASH_ALGORITHM: Vec<u8> = SHA1_HASH_ALGORITHM.to_vec().unwrap(); static ENCODED_SHA1_HASH_ALGORITHM: Lazy<Vec<u8>> =
// Default MaskGenAlgrithm for RSASSA-PSS-params (mgf1SHA1) Lazy::new(|| SHA1_HASH_ALGORITHM.to_vec().unwrap());
// // Default MaskGenAlgrithm for RSASSA-PSS-params (mgf1SHA1)
// mgf1SHA1 MaskGenAlgorithm ::= { //
// algorithm id-mgf1, // mgf1SHA1 MaskGenAlgorithm ::= {
// parameters HashAlgorithm : sha1 // algorithm id-mgf1,
// } // parameters HashAlgorithm : sha1
static ref MGF1_SHA1_MASK_ALGORITHM: rsa::pkcs8::AlgorithmIdentifier<'static> = rsa::pkcs8::AlgorithmIdentifier { // }
static MGF1_SHA1_MASK_ALGORITHM: Lazy<
rsa::pkcs8::AlgorithmIdentifier<'static>,
> = Lazy::new(|| {
rsa::pkcs8::AlgorithmIdentifier {
// id-mgf1 // id-mgf1
oid: ID_MFG1, oid: ID_MFG1,
// sha1 // sha1
parameters: Some(asn1::Any::from_der(&ENCODED_SHA1_HASH_ALGORITHM).unwrap()), parameters: Some(
}; asn1::Any::from_der(&ENCODED_SHA1_HASH_ALGORITHM).unwrap(),
),
}
});
// Default PSourceAlgorithm for RSAES-OAEP-params // Default PSourceAlgorithm for RSAES-OAEP-params
// The default label is an empty string. // The default label is an empty string.
// //
// pSpecifiedEmpty PSourceAlgorithm ::= { // pSpecifiedEmpty PSourceAlgorithm ::= {
// algorithm id-pSpecified, // algorithm id-pSpecified,
// parameters EncodingParameters : emptyString // parameters EncodingParameters : emptyString
// } // }
// //
// emptyString EncodingParameters ::= ''H // emptyString EncodingParameters ::= ''H
static ref P_SPECIFIED_EMPTY: rsa::pkcs8::AlgorithmIdentifier<'static> = rsa::pkcs8::AlgorithmIdentifier { static P_SPECIFIED_EMPTY: Lazy<rsa::pkcs8::AlgorithmIdentifier<'static>> =
Lazy::new(|| {
rsa::pkcs8::AlgorithmIdentifier {
// id-pSpecified // id-pSpecified
oid: ID_P_SPECIFIED, oid: ID_P_SPECIFIED,
// EncodingParameters // EncodingParameters
parameters: Some(asn1::Any::from(asn1::OctetString::new(b"").unwrap())), parameters: Some(asn1::Any::from(asn1::OctetString::new(b"").unwrap())),
}; }
} });
impl<'a> TryFrom<rsa::pkcs8::der::asn1::Any<'a>> impl<'a> TryFrom<rsa::pkcs8::der::asn1::Any<'a>>
for PssPrivateKeyParameters<'a> for PssPrivateKeyParameters<'a>

View file

@ -15,7 +15,7 @@ path = "lib.rs"
[dependencies] [dependencies]
deno_core = { version = "0.111.0", path = "../../core" } deno_core = { version = "0.111.0", path = "../../core" }
lazy_static = "1.4.0" once_cell = "=1.9.0"
rustls = { version = "0.20", features = ["dangerous_configuration"] } rustls = { version = "0.20", features = ["dangerous_configuration"] }
rustls-native-certs = "0.6.1" rustls-native-certs = "0.6.1"
rustls-pemfile = "0.2.1" rustls-pemfile = "0.2.1"

View file

@ -89,11 +89,6 @@ pub struct BasicAuth {
pub password: String, pub password: String,
} }
lazy_static::lazy_static! {
static ref CLIENT_SESSION_MEMORY_CACHE: Arc<ClientSessionMemoryCache> =
Arc::new(ClientSessionMemoryCache::default());
}
#[derive(Default)] #[derive(Default)]
struct ClientSessionMemoryCache(Mutex<HashMap<Vec<u8>, Vec<u8>>>); struct ClientSessionMemoryCache(Mutex<HashMap<Vec<u8>, Vec<u8>>>);

View file

@ -68,10 +68,10 @@ filetime = "0.2.15"
fs3 = "0.5.0" fs3 = "0.5.0"
http = "0.2.4" http = "0.2.4"
hyper = { version = "0.14.12", features = ["server", "stream", "http1", "http2", "runtime"] } hyper = { version = "0.14.12", features = ["server", "stream", "http1", "http2", "runtime"] }
lazy_static = "1.4.0"
libc = "0.2.106" libc = "0.2.106"
log = "0.4.14" log = "0.4.14"
notify = "=5.0.0-pre.12" notify = "=5.0.0-pre.12"
once_cell = "=1.9.0"
regex = "1.5.4" regex = "1.5.4"
ring = "0.16.20" ring = "0.16.20"
serde = { version = "1.0.129", features = ["derive"] } serde = { version = "1.0.129", features = ["derive"] }

View file

@ -1,5 +1,6 @@
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
use once_cell::sync::Lazy;
use std::fmt; use std::fmt;
use std::io::Write; use std::io::Write;
use termcolor::Color::{Ansi256, Black, Blue, Cyan, Green, Red, White, Yellow}; use termcolor::Color::{Ansi256, Black, Blue, Cyan, Green, Red, White, Yellow};
@ -8,9 +9,8 @@ use termcolor::{Ansi, ColorSpec, WriteColor};
#[cfg(windows)] #[cfg(windows)]
use termcolor::{BufferWriter, ColorChoice}; use termcolor::{BufferWriter, ColorChoice};
lazy_static::lazy_static! { static NO_COLOR: Lazy<bool> =
static ref NO_COLOR: bool = std::env::var_os("NO_COLOR").is_some(); Lazy::new(|| std::env::var_os("NO_COLOR").is_some());
}
pub fn use_color() -> bool { pub fn use_color() -> bool {
!(*NO_COLOR) !(*NO_COLOR)

View file

@ -15,6 +15,7 @@ use deno_core::RcRef;
use deno_core::Resource; use deno_core::Resource;
use deno_core::ResourceId; use deno_core::ResourceId;
use deno_core::ZeroCopyBuf; use deno_core::ZeroCopyBuf;
use once_cell::sync::Lazy;
use std::borrow::Cow; use std::borrow::Cow;
use std::fs::File as StdFile; use std::fs::File as StdFile;
use std::io::Read; use std::io::Read;
@ -36,32 +37,35 @@ use {
}; };
#[cfg(unix)] #[cfg(unix)]
lazy_static::lazy_static! { static STDIN_HANDLE: Lazy<StdFile> =
static ref STDIN_HANDLE: StdFile = unsafe { StdFile::from_raw_fd(0) }; Lazy::new(|| unsafe { StdFile::from_raw_fd(0) });
static ref STDOUT_HANDLE: StdFile = unsafe { StdFile::from_raw_fd(1) }; #[cfg(unix)]
static ref STDERR_HANDLE: StdFile = unsafe { StdFile::from_raw_fd(2) }; static STDOUT_HANDLE: Lazy<StdFile> =
} Lazy::new(|| unsafe { StdFile::from_raw_fd(1) });
#[cfg(unix)]
static STDERR_HANDLE: Lazy<StdFile> =
Lazy::new(|| unsafe { StdFile::from_raw_fd(2) });
/// Due to portability issues on Windows handle to stdout is created from raw
/// file descriptor. The caveat of that approach is fact that when this
/// handle is dropped underlying file descriptor is closed - that is highly
/// not desirable in case of stdout. That's why we store this global handle
/// that is then cloned when obtaining stdio for process. In turn when
/// resource table is dropped storing reference to that handle, the handle
/// itself won't be closed (so Deno.core.print) will still work.
// TODO(ry) It should be possible to close stdout.
#[cfg(windows)] #[cfg(windows)]
lazy_static::lazy_static! { static STDIN_HANDLE: Lazy<StdFile> = Lazy::new(|| unsafe {
/// Due to portability issues on Windows handle to stdout is created from raw
/// file descriptor. The caveat of that approach is fact that when this
/// handle is dropped underlying file descriptor is closed - that is highly
/// not desirable in case of stdout. That's why we store this global handle
/// that is then cloned when obtaining stdio for process. In turn when
/// resource table is dropped storing reference to that handle, the handle
/// itself won't be closed (so Deno.core.print) will still work.
// TODO(ry) It should be possible to close stdout.
static ref STDIN_HANDLE: StdFile = unsafe {
StdFile::from_raw_handle(GetStdHandle(winbase::STD_INPUT_HANDLE)) StdFile::from_raw_handle(GetStdHandle(winbase::STD_INPUT_HANDLE))
}; });
static ref STDOUT_HANDLE: StdFile = unsafe { #[cfg(windows)]
static STDOUT_HANDLE: Lazy<StdFile> = Lazy::new(|| unsafe {
StdFile::from_raw_handle(GetStdHandle(winbase::STD_OUTPUT_HANDLE)) StdFile::from_raw_handle(GetStdHandle(winbase::STD_OUTPUT_HANDLE))
}; });
static ref STDERR_HANDLE: StdFile = unsafe { #[cfg(windows)]
static STDERR_HANDLE: Lazy<StdFile> = Lazy::new(|| unsafe {
StdFile::from_raw_handle(GetStdHandle(winbase::STD_ERROR_HANDLE)) StdFile::from_raw_handle(GetStdHandle(winbase::STD_ERROR_HANDLE))
}; });
}
pub fn init() -> Extension { pub fn init() -> Extension {
Extension::builder() Extension::builder()

View file

@ -16,6 +16,7 @@ use deno_core::url;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use deno_core::OpState; use deno_core::OpState;
use log; use log;
use once_cell::sync::Lazy;
use std::collections::HashSet; use std::collections::HashSet;
use std::fmt; use std::fmt;
use std::hash::Hash; use std::hash::Hash;
@ -29,9 +30,8 @@ use std::sync::atomic::Ordering;
const PERMISSION_EMOJI: &str = "⚠️"; const PERMISSION_EMOJI: &str = "⚠️";
lazy_static::lazy_static! { static DEBUG_LOG_ENABLED: Lazy<bool> =
static ref DEBUG_LOG_ENABLED: bool = log::log_enabled!(log::Level::Debug); Lazy::new(|| log::log_enabled!(log::Level::Debug));
}
/// Tri-state value for storing permission state /// Tri-state value for storing permission state
#[derive(PartialEq, Debug, Clone, Copy, Deserialize, PartialOrd)] #[derive(PartialEq, Debug, Clone, Copy, Deserialize, PartialOrd)]
@ -2017,9 +2017,9 @@ fn permission_prompt(_message: &str) -> bool {
static STUB_PROMPT_VALUE: AtomicBool = AtomicBool::new(true); static STUB_PROMPT_VALUE: AtomicBool = AtomicBool::new(true);
#[cfg(test)] #[cfg(test)]
lazy_static::lazy_static! { static PERMISSION_PROMPT_STUB_VALUE_SETTER: Lazy<
static ref PERMISSION_PROMPT_STUB_VALUE_SETTER: Mutex<PermissionPromptStubValueSetter> = Mutex::new(PermissionPromptStubValueSetter); Mutex<PermissionPromptStubValueSetter>,
} > = Lazy::new(|| Mutex::new(PermissionPromptStubValueSetter));
#[cfg(test)] #[cfg(test)]
struct PermissionPromptStubValueSetter; struct PermissionPromptStubValueSetter;