1use crate::host::{with_host, JsObj};
19use fusevm::Value;
20
21pub mod assert;
22pub mod assert_diff;
23pub mod async_hooks;
24pub mod buffer;
25pub mod child_process;
26pub mod cluster;
27pub mod console;
28pub mod constants;
29pub mod crypto;
30pub mod date;
31pub mod dgram;
32pub mod diagnostics_channel;
33pub mod dns;
34pub mod domain;
35pub mod event_target;
36pub mod events;
37pub mod fetch;
38pub mod fs;
39pub mod fs_promises;
40pub mod http;
41pub mod http2;
42pub mod https;
43pub mod iterator;
44pub mod net;
45pub mod node_module;
46pub mod os;
47pub mod path;
48pub mod perf_hooks;
49pub mod process;
50pub mod punycode;
51pub mod querystring;
52pub mod readline;
53pub mod repl;
54pub mod stream;
55pub mod stream_consumers;
56pub mod stream_promises;
57pub mod stream_web;
58pub mod string_decoder;
59pub mod timers;
60pub mod tls;
61pub mod trace_events;
62pub mod tty;
63pub mod typedarray;
64pub mod url;
65pub mod url_legacy;
66pub mod util;
67pub mod util_types;
68pub mod v8;
69pub mod vm;
70pub mod worker_threads;
71pub mod zlib;
72
73pub const UNIMPLEMENTED_MODULES: &[&str] = &["inspector", "wasi"];
80
81pub fn is_unimplemented(ns: &str) -> bool {
83 UNIMPLEMENTED_MODULES.contains(&ns)
84}
85
86pub fn data_module(spec: &str) -> Option<Value> {
93 match spec.strip_prefix("node:").unwrap_or(spec) {
94 "constants" => {
95 cached_module_value("@constants", || Some(constants::object(&constants::flat())))
96 }
97 _ => None,
98 }
99}
100
101pub fn is_core(spec: &str) -> bool {
104 resolve(spec).is_some() || matches!(spec.strip_prefix("node:").unwrap_or(spec), "constants")
105}
106
107pub fn resolve(spec: &str) -> Option<&'static str> {
108 match spec.strip_prefix("node:").unwrap_or(spec) {
109 "fs" => Some("fs"),
110 "path" => Some("path"),
111 "os" => Some("os"),
112 "util" => Some("util"),
113 "assert" => Some("assert"),
114 "crypto" => Some("crypto"),
115 "buffer" => Some("buffer"),
116 "url" => Some("url"),
117 "process" => Some("process"),
118 "net" => Some("net"),
119 "http" => Some("http"),
120 "stream" => Some("Stream"),
126 "tty" => Some("tty"),
127 "events" => Some("EventEmitter"),
130 "string_decoder" => Some("string_decoder"),
131 "zlib" => Some("zlib"),
132 "querystring" => Some("querystring"),
133 "console" => Some("console"),
134 "path/posix" => Some("path"),
138 "path/win32" => Some("path/win32"),
139 "sys" => Some("util"),
141 "assert/strict" => Some("assertStrict"),
146 "child_process" => Some("child_process"),
147 "dns" => Some("dns"),
148 "punycode" => Some("punycode"),
149 "timers" => Some("timers"),
150 "timers/promises" => Some("timers/promises"),
151 "perf_hooks" => Some("perf_hooks"),
152 "async_hooks" => Some("async_hooks"),
153 "util/types" => Some("util/types"),
154 "diagnostics_channel" => Some("diagnostics_channel"),
155 "v8" => Some("v8"),
156 "readline" => Some("readline"),
157 "readline/promises" => Some("readline/promises"),
158 "vm" => Some("vm"),
159 "fs/promises" => Some("fs/promises"),
160 "dgram" => Some("dgram"),
161 "dns/promises" => Some("dns/promises"),
162 "worker_threads" => Some("worker_threads"),
163 "tls" => Some("tls"),
164 "https" => Some("https"),
165 "repl" => Some("repl"),
166 "cluster" => Some("cluster"),
167 "domain" => Some("domain"),
168 "http2" => Some("http2"),
169 "trace_events" => Some("trace_events"),
170 "module" => Some("module"),
171 "stream/consumers" => Some("stream/consumers"),
172 "stream/promises" => Some("stream/promises"),
173 "stream/web" => Some("stream/web"),
174 other => UNIMPLEMENTED_MODULES.iter().copied().find(|&m| m == other),
175 }
176}
177
178pub fn is_method(qualified: &str) -> bool {
181 let Some((ns, m)) = qualified.split_once('.') else {
182 return qualified == "assert";
183 };
184 is_unimplemented(ns)
188 || namespace_methods(ns).contains(&m)
189 || namespace_ctors(ns).contains(&m)
190 || namespace_values(ns).contains(&m)
191}
192
193pub fn namespace_methods(ns: &str) -> &'static [&'static str] {
197 match ns {
198 "fs" => fs::METHODS,
199 "path" | "path/win32" => path::METHODS,
200 "os" => os::METHODS,
201 "util" => util::METHODS,
202 "assert" | "assertStrict" => assert::METHODS,
203 "crypto" => crypto::METHODS,
204 "webcrypto" => crypto::WEBCRYPTO_METHODS,
205 "SubtleCrypto" => crypto::SUBTLE_METHODS,
206 "Buffer" => buffer::STATIC_METHODS,
207 "buffer" => buffer::MODULE_METHODS,
208 "Date" => date::STATIC_METHODS,
209 "Response" => fetch::RESPONSE_STATICS,
210 "AbortSignal" => fetch::ABORT_SIGNAL_STATICS,
211 "Iterator" => iterator::STATIC_METHODS,
212 n if typedarray::is_ctor(n) => typedarray::static_methods(n),
213 "URL" => url::STATIC_METHODS,
214 "url" => url::MODULE_METHODS,
215 "net" => net::MODULE_METHODS,
216 "http" => http::MODULE_METHODS,
217 "stream" | "Stream" => stream::METHODS,
218 n if stream::is_class(n) => stream::STATIC_METHODS,
219 "worker_threads" => worker_threads::METHODS,
220 "zlib" => zlib::MODULE_METHODS,
221 "querystring" => querystring::METHODS,
222 "tty" => tty::METHODS,
223 "process" => process::METHODS,
224 "EventEmitter" => events::STATIC_METHODS,
225 "console" => console::METHODS,
226 "child_process" => child_process::METHODS,
227 "dns" => dns::METHODS,
228 "dns/promises" => dns::PROMISES_METHODS,
229 "punycode" => punycode::METHODS,
230 "timers" => timers::METHODS,
231 "timers/promises" => timers::PROMISES_METHODS,
232 "perf_hooks" => perf_hooks::METHODS,
233 "performance" => perf_hooks::PERFORMANCE_METHODS,
234 "async_hooks" => async_hooks::METHODS,
235 "AsyncResource" => async_hooks::RESOURCE_STATIC_METHODS,
236 "AsyncLocalStorage" => async_hooks::ALS_STATIC_METHODS,
237 "util/types" => util_types::METHODS,
238 "diagnostics_channel" => diagnostics_channel::METHODS,
239 "v8" => v8::METHODS,
240 "readline" => readline::METHODS,
241 "readline/promises" => readline::PROMISES_METHODS,
242 "vm" => vm::METHODS,
243 "fs/promises" => fs_promises::METHODS,
244 "dgram" => dgram::MODULE_METHODS,
245 "tls" => tls::MODULE_METHODS,
246 "https" => https::MODULE_METHODS,
247 "repl" => repl::METHODS,
248 "cluster" => cluster::METHODS,
249 "domain" => domain::METHODS,
250 "http2" => http2::METHODS,
251 "trace_events" => trace_events::METHODS,
252 "module" => node_module::METHODS,
253 "Module" => node_module::MODULE_STATIC_METHODS,
254 "stream/consumers" => stream_consumers::METHODS,
255 "stream/promises" => stream_promises::METHODS,
256 _ => &[],
257 }
258}
259
260pub fn namespace_ctors(ns: &str) -> &'static [&'static str] {
264 match ns {
265 "buffer" => &["Buffer", "Blob", "File"],
266 "stream" | "Stream" => stream::CLASSES,
267 "url" => &["URL", "URLSearchParams"],
268 "EventEmitter" => &["EventEmitter"],
269 "async_hooks" => &["AsyncLocalStorage", "AsyncResource"],
270 "string_decoder" => &["StringDecoder"],
271 "assert" => &["AssertionError"],
272 "console" => &["Console"],
273 "vm" => &["Script"],
274 "fs" => &["promises", "Dirent", "Stats"],
275 "stream/web" => stream_web::CLASSES,
283 _ => &[],
284 }
285}
286
287pub fn namespace_statics_enumerable(ns: &str) -> bool {
297 ns != "Iterator"
298}
299
300pub fn namespace_values(ns: &str) -> &'static [&'static str] {
306 match ns {
307 "timers" | "readline" | "stream" | "Stream" => &["promises"],
308 "dns" => dns::VALUE_KEYS,
309 "assert" => &["strict"],
310 "EventEmitter" => &[
311 "usingDomains",
312 "captureRejectionSymbol",
313 "captureRejections",
314 "errorMonitor",
315 "defaultMaxListeners",
316 ],
317 "path" | "path/win32" => &["sep", "delimiter", "win32", "posix"],
318 "crypto" => &["constants", "webcrypto", "subtle"],
319 "os" => &["constants", "EOL", "devNull"],
320 "fs" | "fs/promises" | "http2" => &["constants"],
321 "buffer" => &[
322 "kMaxLength",
323 "kStringMaxLength",
324 "constants",
325 "INSPECT_MAX_BYTES",
326 ],
327 "http" => &["METHODS", "STATUS_CODES", "globalAgent"],
328 "https" => &["globalAgent"],
329 "perf_hooks" => &["performance", "constants"],
330 "worker_threads" => &["isMainThread", "threadId", "parentPort", "workerData"],
331 "cluster" => &[
332 "isWorker",
333 "isMaster",
334 "isPrimary",
335 "workers",
336 "settings",
337 "SCHED_NONE",
338 "SCHED_RR",
339 "schedulingPolicy",
340 ],
341 "domain" => &["active"],
342 _ => &[],
343 }
344}
345
346pub fn namespace_keys(ns: &str) -> Vec<String> {
347 if singleton_class(ns).is_some() {
350 return Vec::new();
351 }
352 if ns == crate::builtins::REQUIRE_CACHE {
354 return crate::module::cache_keys();
355 }
356 let mut out: Vec<String> = namespace_ctors(ns)
357 .iter()
358 .chain(namespace_values(ns))
359 .map(|s| s.to_string())
360 .collect();
361 for m in namespace_methods(ns) {
362 if !m.contains('.') && !out.iter().any(|k| k == m) {
366 out.push((*m).to_string());
367 }
368 }
369 if ns != "process" {
374 if let Some(theirs) = core_keys(ns) {
375 return theirs
376 .iter()
377 .filter(|k| out.iter().any(|o| o == *k))
378 .map(|k| (*k).to_string())
379 .collect();
380 }
381 }
382 out
383}
384
385pub fn core_keys(ns: &str) -> Option<&'static [&'static str]> {
387 let t = crate::core_arity::CORE_KEYS;
388 t.binary_search_by(|(k, _)| (*k).cmp(ns))
389 .ok()
390 .map(|i| t[i].1)
391}
392
393pub fn call(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
397 if name == "assert" {
398 return Some(assert::assert_ok(args));
399 }
400 let (ns, m) = name.split_once('.')?;
401 Some(match ns {
402 "fs" => fs::call(m, args)?,
403 "path" => path::call(path::Flavor::Posix, m, args)?,
404 "path/win32" => path::call(path::Flavor::Win32, m, args)?,
405 "os" => os::call(m, args)?,
406 "util" => util::call(m, args)?,
407 "assert" => assert::call(m, args)?,
408 "assertStrict" => assert::strict_call(m, args)?,
409 "crypto" => crypto::call(m, args)?,
410 "webcrypto" => crypto::call(m, args)?,
413 "SubtleCrypto" => crypto::subtle_call(m, args)?,
414 "Buffer" => buffer::static_call(m, args)?,
415 "buffer" if m == "Buffer" => Ok(with_host(|h| h.alloc(JsObj::Builtin("Buffer".into())))),
416 "buffer" => buffer::module_call(m, args)?,
417 "Date" => date::static_call(m, args)?,
418 "Response" | "AbortSignal" => fetch::static_call(ns, m, args)?,
419 "Iterator" => iterator::static_call(m, args)?,
420 n if typedarray::is_ctor(n) => typedarray::static_call(n, m, args)?,
421 "URL" => url::static_call(m, args)?,
422 "url" if m == "URL" => Ok(with_host(|h| h.alloc(JsObj::Builtin("URL".into())))),
423 "url" => url::call(m, args)?,
424 "net" => net::call(m, args)?,
425 "http" => http::call(m, args)?,
426 "stream" | "Stream" => stream::call(m, args)?,
427 "worker_threads" => worker_threads::call(m, args)?,
428 "zlib" => zlib::call(m, args)?,
429 "querystring" => querystring::call(m, args)?,
430 "tty" => tty::call(m, args)?,
431 "process" => process::call(m, args)?,
432 "EventEmitter" if m == "EventEmitter" => Ok(with_host(|h| {
433 h.alloc(JsObj::Builtin("EventEmitter".into()))
434 })),
435 "EventEmitter" => events::static_call(m, args)?,
436 n if stream::is_class(n) => stream::static_call(n, m, args)?,
437 "console" => console::call(m, args)?,
438 "child_process" => child_process::call(m, args)?,
439 "dns" => dns::call(m, args)?,
440 "punycode" => punycode::call(m, args)?,
441 "timers" => timers::call(m, args)?,
442 "timers/promises" => timers::promises_call(m, args)?,
443 "perf_hooks" | "performance" => perf_hooks::call(m, args)?,
444 "async_hooks" => async_hooks::call(m, args)?,
445 "AsyncResource" => async_hooks::static_call(m, args)?,
446 "AsyncLocalStorage" => async_hooks::als_static_call(m, args)?,
447 "util/types" => util_types::call(m, args)?,
448 "diagnostics_channel" => diagnostics_channel::call(m, args)?,
449 "v8" => v8::call(m, args)?,
450 "readline" => readline::call(m, args)?,
451 "readline/promises" => readline::promises_call(m, args)?,
452 "vm" => vm::call(m, args)?,
453 "fs/promises" => fs_promises::call(m, args)?,
454 "dgram" => dgram::call(m, args)?,
455 "dns/promises" => match m {
458 "getServers" | "setServers" | "getDefaultResultOrder" | "setDefaultResultOrder" => {
459 dns::call(m, args)?
460 }
461 _ => {
462 let mut pm = String::from("promise");
463 let mut cs = m.chars();
464 if let Some(c) = cs.next() {
465 pm.extend(c.to_uppercase());
466 pm.push_str(cs.as_str());
467 }
468 dns::call(&pm, args)?
469 }
470 },
471 "tls" => tls::call(m, args)?,
472 "https" => https::call(m, args)?,
473 "repl" => repl::call(m, args)?,
474 "cluster" => cluster::call(m, args)?,
475 "domain" => domain::call(m, args)?,
476 "http2" => http2::call(m, args)?,
477 "trace_events" => trace_events::call(m, args)?,
478 "module" => node_module::call(m, args)?,
479 "Module" => node_module::static_call(m, args)?,
480 "stream/consumers" => stream_consumers::call(m, args)?,
481 "stream/promises" => stream_promises::call(m, args)?,
482 _ if is_unimplemented(ns) => Err(format!("Error: {ns}.{m} is not implemented in node-js")),
483 _ => return None,
484 })
485}
486
487pub fn constant(ns: &str, name: &str) -> Option<Value> {
490 if name == "constants" {
494 let key = if ns == "fs/promises" { "fs" } else { ns };
495 return cached_module_value(key, || constant_uncached(ns, name));
496 }
497 constant_uncached(ns, name)
498}
499
500fn cached_module_value(key: &str, make: impl FnOnce() -> Option<Value>) -> Option<Value> {
502 thread_local! {
503 static CACHE: std::cell::RefCell<std::collections::HashMap<String, Value>> =
504 std::cell::RefCell::new(std::collections::HashMap::new());
505 }
506 if let Some(v) = CACHE.with(|c| c.borrow().get(key).cloned()) {
507 return Some(v);
508 }
509 let v = make()?;
510 CACHE.with(|c| c.borrow_mut().insert(key.to_string(), v.clone()));
511 Some(v)
512}
513
514fn constant_uncached(ns: &str, name: &str) -> Option<Value> {
515 match ns {
516 "Event" => event_target::constant(name),
517 "path" | "path/win32" if name == "posix" => {
520 Some(with_host(|h| h.alloc(JsObj::Builtin("path".into()))))
521 }
522 "path" | "path/win32" if name == "win32" => {
523 Some(with_host(|h| h.alloc(JsObj::Builtin("path/win32".into()))))
524 }
525 "path" => path::constant(path::Flavor::Posix, name),
526 "path/win32" => path::constant(path::Flavor::Win32, name),
527 "os" => os::constant(name),
528 "tls" if name == "rootCertificates" => {
530 cached_module_value("tls.rootCertificates", || tls::constant(name))
531 }
532 "tls" => tls::constant(name),
533 "fs" | "fs/promises" if name == "constants" => Some(constants::object(&constants::fs())),
538 "fs" if matches!(name, "Stats" | "Dirent") => {
541 Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
542 }
543 "crypto" if name == "constants" => Some(constants::object(&constants::crypto())),
544 "crypto" if name == "subtle" => Some(with_host(|h| {
549 h.alloc(JsObj::Builtin("SubtleCrypto".into()))
550 })),
551 "timers" if name == "promises" => Some(with_host(|h| {
553 h.alloc(JsObj::Builtin("timers/promises".into()))
554 })),
555 "crypto" if name == "webcrypto" => {
556 Some(with_host(|h| h.alloc(JsObj::Builtin("webcrypto".into()))))
557 }
558 "webcrypto" if name == "subtle" => Some(with_host(|h| {
559 h.alloc(JsObj::Builtin("SubtleCrypto".into()))
560 })),
561 "EventEmitter" | "events" if name == "defaultMaxListeners" => Some(Value::Float(10.0)),
565 "EventEmitter" | "events" if matches!(name, "captureRejections" | "usingDomains") => {
570 Some(Value::Bool(false))
571 }
572 "EventEmitter" | "events" if name == "captureRejectionSymbol" => {
573 Some(with_host(|h| h.symbol_for("nodejs.rejection")))
574 }
575 "EventEmitter" | "events" if name == "errorMonitor" => {
576 Some(with_host(|h| h.internal_symbol("events.errorMonitor")))
577 }
578 "Buffer" if name == "poolSize" => Some(Value::Float(65536.0)),
584 n if typedarray::is_ctor(n) && name == "BYTES_PER_ELEMENT" => {
589 typedarray::ELEMENT_KINDS
591 .contains(&n)
592 .then(|| Value::Float(typedarray::bytes_per_element(n) as f64))
593 }
594 "buffer" if name == "Buffer" => {
595 Some(with_host(|h| h.alloc(JsObj::Builtin("Buffer".into()))))
596 }
597 "buffer" if matches!(name, "Blob" | "File") => {
598 Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
599 }
600 "buffer" => buffer::module_constant(name),
601 "url" if name == "URL" => Some(with_host(|h| h.alloc(JsObj::Builtin("URL".into())))),
602 "net" => net::constant(name),
603 "tty" => tty::constant(name),
604 "repl" => repl::constant(name),
605 "readline" if name == "promises" => Some(with_host(|h| {
608 h.alloc(JsObj::Builtin("readline/promises".into()))
609 })),
610 "readline" | "readline/promises" => readline::constant(name),
611 "diagnostics_channel" => diagnostics_channel::constant(name),
612 "v8" => v8::constant(name),
613 "console" if name == "Console" => {
614 Some(with_host(|h| h.alloc(JsObj::Builtin("Console".into()))))
615 }
616 "assert" if name == "AssertionError" => Some(with_host(|h| {
617 h.alloc(JsObj::Builtin("AssertionError".into()))
618 })),
619 "assert" if name == "strict" => Some(with_host(|h| {
620 h.alloc(JsObj::Builtin("assertStrict".into()))
621 })),
622 n if stream::is_class(n) && name == "prototype" => with_host(|h| h.ensure_ctor_proto(n)),
627 "stream" | "Stream" => stream::constant(name),
628 "http" => http::constant(name),
629 "string_decoder" if name == "StringDecoder" => Some(with_host(|h| {
630 h.alloc(JsObj::Builtin("StringDecoder".into()))
631 })),
632 "process" => process::constant(name),
633 "EventEmitter" if name == "EventEmitter" => Some(with_host(|h| {
634 h.alloc(JsObj::Builtin("EventEmitter".into()))
635 })),
636 "perf_hooks" | "performance" => perf_hooks::constant(name),
637 "dns" => dns::constant(name),
638 "punycode" => punycode::constant(name),
639 "async_hooks" if matches!(name, "AsyncLocalStorage" | "AsyncResource") => {
640 Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
641 }
642 "vm" if name == "Script" => Some(with_host(|h| h.alloc(JsObj::Builtin("Script".into())))),
643 "url" if name == "URLSearchParams" => Some(with_host(|h| {
644 h.alloc(JsObj::Builtin("URLSearchParams".into()))
645 })),
646 "fs" if name == "promises" => {
647 Some(with_host(|h| h.alloc(JsObj::Builtin("fs/promises".into()))))
648 }
649 "worker_threads" => worker_threads::constant(name),
650 "https" => https::constant(name),
651 "cluster" => cluster::constant(name),
652 "domain" => domain::constant(name),
653 "http2" => http2::constant(name),
654 "module" => node_module::constant(name),
655 "Module" => node_module::static_constant(name),
656 "stream/web" => stream_web::constant(name),
657 "util" => util::constant(name),
659 "crypto"
662 if matches!(
663 name,
664 "Sign"
665 | "Verify"
666 | "KeyObject"
667 | "DiffieHellman"
668 | "ECDH"
669 | "X509Certificate"
670 | "Hash"
671 | "Hmac"
672 | "Cipheriv"
673 | "Decipheriv"
674 ) =>
675 {
676 Some(with_host(|h| h.alloc(JsObj::Builtin(name.into()))))
677 }
678 _ => None,
679 }
680}
681
682pub fn construct(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
686 match name {
687 "URL" => Some(url::construct(args)),
688 "EventEmitter" => Some(Ok(events::new_emitter())),
689 "Buffer" => {
698 let numeric = matches!(args.first(), Some(Value::Int(_)) | Some(Value::Float(_)))
699 && args.len() == 1;
700 let m = if numeric { "alloc" } else { "from" };
701 Some(buffer::static_call(m, args).unwrap_or(Ok(Value::Undef)))
702 }
703 "Date" => Some(date::construct(args)),
704 "StringDecoder" => Some(string_decoder::construct(args)),
705 "WeakRef" => Some(typedarray::construct_weakref(args)),
706 "FinalizationRegistry" => Some(typedarray::construct_finalization_registry(args)),
707 n if fetch::is_class(n) => fetch::construct(n, args),
708 n if event_target::is_class(n) => event_target::construct(n, args),
709 "TextEncoder" => Some(typedarray::construct_text_encoder()),
710 "TextDecoder" => Some(typedarray::construct_text_decoder(args)),
711 "DataView" => Some(typedarray::construct_dataview(args)),
712 n if typedarray::is_ctor(n) => Some(typedarray::construct(n, args)),
713 n if stream::is_class(n) => Some(Ok(stream::construct(n, args))),
714 "AsyncLocalStorage" | "AsyncResource" => async_hooks::construct(name, args),
715 "Script" => Some(vm::construct(args)),
716 "URLSearchParams" => Some(url::construct_search_params(args)),
717 "Worker" => Some(worker_threads::construct_worker(args)),
718 "Domain" => Some(domain::construct(args)),
719 "Tracing" => Some(trace_events::construct(args)),
720 "Blob" => Some(buffer::construct_blob(args)),
721 "File" => Some(buffer::construct_file(args)),
722 "AssertionError" => Some(Ok(assert::construct_assertion_error(args))),
723 "X509Certificate" => Some(crypto::construct_x509(args)),
724 "MIMEType" => Some(util::construct_mime_type(args)),
725 "MIMEParams" => Some(util::construct_mime_params(args)),
726 "Resolver" => Some(Ok(dns::construct_resolver(args))),
727 "ReadStream" | "WriteStream" => Some(Ok(tty::construct(name, args))),
728 "MessageChannel" => Some(worker_threads::construct_message_channel(args)),
729 "BroadcastChannel" => Some(worker_threads::construct_broadcast_channel(args)),
730 "PerformanceObserver" => Some(perf_hooks::construct(name, args)),
731 n if illegal_constructor(n) => Some(Err(crate::host::coded_error(
733 "TypeError",
734 "ERR_ILLEGAL_CONSTRUCTOR",
735 "Illegal constructor",
736 ))),
737 "REPLServer" | "Recoverable" => Some(repl::construct(name, args)),
738 "Interface" => Some(readline::construct(args)),
739 "Console" => Some(console::construct(args)),
740 "Serializer" | "DefaultSerializer" | "Deserializer" | "DefaultDeserializer" => {
741 Some(v8::construct(name, args))
742 }
743 "Socket" | "Stream" | "Server" | "SocketAddress" | "BlockList" => {
745 net::construct(name, args)
746 }
747 "Agent" | "http.Server" => http::construct(name, args),
748 _ => None,
749 }
750}
751
752pub fn native_tag(recv: &Value) -> Option<String> {
755 with_host(|h| match h.get(recv) {
756 Some(JsObj::Object(p)) => p.get("@@native").map(|v| h.str_of(v)),
757 _ => None,
758 })
759}
760
761pub fn has_to_json(tag: &str) -> bool {
765 matches!(tag, "Buffer" | "Date" | "URL" | "MIMEType" | "MIMEParams")
766}
767
768pub fn instance_has_method(tag: &str, name: &str) -> bool {
773 let mut ctor = Some(tag);
777 while let Some(t) = ctor {
778 let (base, emitter) = instance_method_lists(t);
779 if base.contains(&name) || emitter.contains(&name) {
780 return true;
781 }
782 ctor = native_parent(t);
783 }
784 false
785}
786
787pub fn native_parent(ctor: &str) -> Option<&'static str> {
804 match ctor {
805 "Readable" | "Writable" | "Duplex" | "Transform" | "PassThrough" => Some("Stream"),
806 "Stream" => Some("EventEmitter"),
807 "ChildProcess" | "Socket" | "Server" => Some("EventEmitter"),
810 "AbortSignal" => Some("EventTarget"),
814 "CustomEvent" => Some("Event"),
815 "SecretKeyObject" | "AsymmetricKeyObject" => Some("KeyObject"),
823 "PublicKeyObject" | "PrivateKeyObject" => Some("AsymmetricKeyObject"),
824 _ => None,
825 }
826}
827
828pub fn instance_late_methods(tag: &str) -> &'static [&'static str] {
861 match tag {
862 "URL" => &["toJSON"],
863 "Event" => event_target::EVENT_LATE_METHODS,
864 _ => &[],
865 }
866}
867
868pub fn instance_inspect_members(tag: &str) -> (&'static [&'static str], bool) {
880 match tag {
881 "URL" => (
882 &[
883 "href",
884 "origin",
885 "protocol",
886 "username",
887 "password",
888 "host",
889 "hostname",
890 "port",
891 "pathname",
892 "search",
893 "searchParams",
894 "hash",
895 ],
896 true,
897 ),
898 "AbortController" => (&["signal"], true),
899 "AbortSignal" => (&["aborted"], true),
900 "Event" | "CustomEvent" => (
903 &["type", "defaultPrevented", "cancelable", "timeStamp"],
904 true,
905 ),
906 "TextDecoder" => (&["encoding", "fatal", "ignoreBOM"], true),
907 "TextEncoder" => (&["encoding"], false),
908 _ => (&[], true),
909 }
910}
911
912pub fn instance_inspect_is_custom(tag: &str) -> bool {
918 tag == "EventTarget" || !instance_inspect_members(tag).0.is_empty()
919}
920
921pub fn instance_members_enumerable(tag: &str) -> bool {
922 !matches!(
923 tag,
924 "Script"
925 | "KeyObject"
926 | "SecretKeyObject"
927 | "AsymmetricKeyObject"
928 | "PublicKeyObject"
929 | "PrivateKeyObject"
930 )
931}
932
933pub fn instance_accessor_written(
934 tag: &str,
935 key: &str,
936 recv: &Value,
937 value: &Value,
938) -> Result<(), String> {
939 if tag == "URL" {
941 return url::set_component(recv, key, value);
942 }
943 if tag == "Event" {
945 return event_target::accessor_written(recv, key, value);
946 }
947 if tag == "AbortSignal" && key == "onabort" {
951 if !with_host(|h| crate::host::is_callable(h, value)) {
952 let null = with_host(|h| h.null());
953 with_host(|h| {
954 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
955 p.insert("@@onabort".into(), null);
956 }
957 });
958 }
959 event_target::ensure_handler_slot(recv, "abort");
960 }
961 Ok(())
962}
963
964pub fn instance_accessors(tag: &str) -> (&'static [(&'static str, bool)], &'static str) {
965 match tag {
966 "AbortController" => (&[("signal", false)], "AbortController"),
967 "AbortSignal" => (
968 &[("aborted", false), ("reason", false), ("onabort", true)],
969 "AbortSignal",
970 ),
971 "KeyObject" => (&[("type", false)], "KeyObject"),
972 "SecretKeyObject" => (&[("symmetricKeySize", false)], ""),
973 "AsymmetricKeyObject" => (
974 &[
975 ("asymmetricKeyType", false),
976 ("asymmetricKeyDetails", false),
977 ],
978 "",
979 ),
980 "TextEncoder" => (&[("encoding", false)], "TextEncoder"),
981 "StringDecoder" => (string_decoder::ACCESSORS, ""),
982 "Performance" => (&[("timeOrigin", false)], "Performance"),
983 "Crypto" => (&[("subtle", false)], "Crypto"),
984 "webcrypto.SubtleCrypto" => (&[], "SubtleCrypto"),
985 "CryptoKey" => (
986 &[
987 ("type", false),
988 ("extractable", false),
989 ("algorithm", false),
990 ("usages", false),
991 ],
992 "CryptoKey",
993 ),
994 "EventTarget" => (&[], "EventTarget"),
995 "Event" => (event_target::EVENT_ACCESSORS, "Event"),
996 "CustomEvent" => (&[("detail", false)], "CustomEvent"),
997 "URL" => (
999 &[
1000 ("href", true),
1001 ("origin", false),
1002 ("protocol", true),
1003 ("username", true),
1004 ("password", true),
1005 ("host", true),
1006 ("hostname", true),
1007 ("port", true),
1008 ("pathname", true),
1009 ("search", true),
1010 ("searchParams", false),
1011 ("hash", true),
1012 ],
1013 "URL",
1014 ),
1015 "TextDecoder" => (
1016 &[("encoding", false), ("fatal", false), ("ignoreBOM", false)],
1017 "TextDecoder",
1018 ),
1019 _ => (&[], ""),
1020 }
1021}
1022
1023pub fn instance_method_lists(tag: &str) -> (&'static [&'static str], &'static [&'static str]) {
1024 const EMITTER: &[&str] = events::METHODS;
1028 let base: &[&str] = match tag {
1029 "Timeout" => timers::TIMEOUT_METHODS,
1030 "IntervalIterator" => timers::INTERVAL_METHODS,
1031 "CollectionIterator" => &["next", "@@iterator"],
1032 "IteratorHelper" => iterator::METHODS,
1033 "Immediate" => timers::IMMEDIATE_METHODS,
1034 "Server" => &["listen", "close", "address"],
1035 "Socket" => &[
1036 "write",
1037 "end",
1038 "destroy",
1039 "pause",
1040 "resume",
1041 "setEncoding",
1042 "setKeepAlive",
1043 "setNoDelay",
1044 "setTimeout",
1045 "ref",
1046 "unref",
1047 "connect",
1048 ],
1049 "ServerResponse" => &[
1050 "writeHead",
1051 "setHeader",
1052 "getHeader",
1053 "getHeaderNames",
1054 "getHeaders",
1055 "hasHeader",
1056 "removeHeader",
1057 "write",
1058 "end",
1059 "flushHeaders",
1060 ],
1061 "IncomingMessage" => &["pause", "resume", "setEncoding", "destroy"],
1062 "Buffer" => buffer::INSTANCE_METHODS,
1063 "DataView" => typedarray::DATAVIEW_METHODS,
1064 "ArrayBuffer" => &["slice", "resize", "transfer", "transferToFixedLength"],
1065 "Date" => date::INSTANCE_METHODS,
1066 "Readable" | "Writable" | "Duplex" | "Transform" | "PassThrough" | "Stream" => &[
1067 "read",
1068 "write",
1069 "end",
1070 "pipe",
1071 "pause",
1072 "resume",
1073 "setEncoding",
1074 "destroy",
1075 "push",
1076 ],
1077 "URL" => &["toString"],
1079 "AsyncLocalStorage" => async_hooks::ALS_METHODS,
1080 "AsyncHook" => async_hooks::HOOK_METHODS,
1081 "AsyncResource" => async_hooks::RESOURCE_METHODS,
1082 "Channel" => &["subscribe", "unsubscribe", "publish"],
1083 "WriteStream" => &[
1084 "write",
1085 "end",
1086 "on",
1087 "once",
1088 "addListener",
1089 "prependListener",
1090 "removeListener",
1091 "off",
1092 "removeAllListeners",
1093 "listenerCount",
1094 "cork",
1095 "uncork",
1096 "setEncoding",
1097 "resume",
1098 "pause",
1099 "read",
1100 "pipe",
1101 "@@asyncIterator",
1102 ],
1103 "StdinIterator" => process::STDIN_ITERATOR_METHODS,
1104 "Hash" => &["update", "digest", "copy"],
1111 "Hmac" => &["update", "digest"],
1112 "Crypto" => crypto::WEBCRYPTO_METHODS,
1113 "webcrypto.SubtleCrypto" => crypto::SUBTLE_METHODS,
1114 "Performance" => &[
1117 "clearResourceTimings",
1118 "setResourceTimingBufferSize",
1119 "now",
1120 "mark",
1121 "measure",
1122 "getEntriesByName",
1123 "getEntriesByType",
1124 "getEntries",
1125 "clearMarks",
1126 "clearMeasures",
1127 "eventLoopUtilization",
1128 "timerify",
1129 ],
1130 "StringDecoder" => string_decoder::INSTANCE_METHODS,
1131 "Interface" => readline::INTERFACE_METHODS,
1132 "ReadlineIterator" => readline::ITERATOR_METHODS,
1133 "Script" => vm::SCRIPT_METHODS,
1134 "URLSearchParams" => url::SEARCH_PARAMS_METHODS,
1135 "UdpSocket" => dgram::SOCKET_METHODS,
1136 "Worker" => worker_threads::WORKER_METHODS,
1137 "MessagePort" => worker_threads::PORT_METHODS,
1138 "TLSServer" => tls::SERVER_METHODS,
1139 "TLSSocket" => tls::SOCKET_METHODS,
1140 "HTTPSServerResponse" => https::RESPONSE_METHODS,
1141 "HTTPSClientRequest" => https::CLIENT_REQUEST_METHODS,
1142 "REPLServer" => repl::REPLSERVER_METHODS,
1143 "ClusterWorker" => cluster::WORKER_METHODS,
1144 "Domain" => domain::DOMAIN_METHODS,
1145 "Tracing" => trace_events::TRACING_METHODS,
1146 "Http2Server" => http2::SERVER_METHODS,
1147 "Http2Stream" => http2::STREAM_METHODS,
1148 "Http2Session" => http2::SESSION_METHODS,
1149 "Cipheriv" | "Decipheriv" => &["update", "final", "setAutoPadding"],
1150 "BlockList" => net::BLOCKLIST_METHODS,
1151 "ClientRequest" => http::CLIENT_REQUEST_METHODS,
1152 "Agent" => &["destroy", "getName"],
1153 "Blob" | "File" => buffer::BLOB_METHODS,
1154 "ReadStream" => tty::READ_STREAM_METHODS,
1155 "Dirent" | "Stats" | "BigIntStats" => fs::DIRENT_METHODS,
1156 "Dir" => fs::DIR_METHODS,
1157 "FSReadStream" => fs::READ_STREAM_METHODS,
1158 "FSWriteStream" => fs::WRITE_STREAM_METHODS,
1159 "Resolver" => dns::RESOLVER_METHODS,
1160 "Histogram" => perf_hooks::HISTOGRAM_METHODS,
1161 "PerformanceObserver" => perf_hooks::PERFORMANCE_OBSERVER_METHODS,
1162 "PerformanceObserverEntryList" => perf_hooks::OBSERVER_ENTRY_LIST_METHODS,
1163 "BroadcastChannel" => worker_threads::BROADCAST_CHANNEL_METHODS,
1164 "TracingChannel" => diagnostics_channel::TRACING_CHANNEL_METHODS,
1165 "Serializer" => v8::SERIALIZER_METHODS,
1166 "Deserializer" => v8::DESERIALIZER_METHODS,
1167 "Console" => console::CONSOLE_METHODS,
1168 "ChildProcess" => child_process::CHILD_PROCESS_METHODS,
1169 "ChildPipe" => child_process::CHILD_PIPE_METHODS,
1170 "Sign" => &["update", "sign"],
1171 "Verify" => &["update", "verify"],
1172 "KeyObject" => &["equals", "toCryptoKey"],
1173 "SecretKeyObject" | "PublicKeyObject" | "PrivateKeyObject" => &["export"],
1175 "DiffieHellman" => &[
1176 "generateKeys",
1177 "computeSecret",
1178 "getPrime",
1179 "getGenerator",
1180 "getPublicKey",
1181 "getPrivateKey",
1182 "setPublicKey",
1183 "setPrivateKey",
1184 ],
1185 "ECDH" => &[
1186 "generateKeys",
1187 "computeSecret",
1188 "getPublicKey",
1189 "getPrivateKey",
1190 "setPrivateKey",
1191 ],
1192 "X509Certificate" => &["toString"],
1193 "FinalizationRegistry" => &["register", "unregister"],
1194 "MIMEType" => util::MIME_TYPE_METHODS,
1195 "MIMEParams" => util::MIME_PARAMS_METHODS,
1196 t if fetch::is_class(t) => fetch::methods_for(t),
1197 "EventTarget" => event_target::EVENT_TARGET_METHODS,
1198 "Event" => event_target::EVENT_METHODS,
1199 _ => &[],
1200 };
1201 let is_emitter = matches!(
1202 tag,
1203 "Server"
1204 | "Socket"
1205 | "ServerResponse"
1206 | "IncomingMessage"
1207 | "EventEmitter"
1208 | "Readable"
1209 | "Writable"
1210 | "Duplex"
1211 | "Transform"
1212 | "PassThrough"
1213 | "Stream"
1214 | "UdpSocket"
1215 | "Worker"
1216 | "MessagePort"
1217 | "TLSServer"
1218 | "TLSSocket"
1219 | "HTTPSServerResponse"
1220 | "HTTPSClientRequest"
1221 | "ClusterWorker"
1222 | "Domain"
1223 | "Http2Server"
1224 | "Http2Stream"
1225 | "Http2Session"
1226 | "ClientRequest"
1227 | "FSReadStream"
1228 | "FSWriteStream"
1229 | "ChildProcess"
1230 | "ChildPipe"
1231 );
1232 (base, if is_emitter { EMITTER } else { &[] })
1233}
1234
1235pub fn instance_call(
1239 tag: &str,
1240 recv: &Value,
1241 method: &str,
1242 args: Vec<Value>,
1243) -> Result<Value, String> {
1244 match tag {
1245 "Buffer" => buffer::instance_call(recv, method, &args),
1246 "Timeout" | "Immediate" => timers::instance_call(recv, method, &args),
1247 "IntervalIterator" => timers::interval_call(recv, method, &args),
1248 "CollectionIterator" => match method {
1249 "next" => crate::builtins::collection_iterator_next(recv),
1250 "@@iterator" => Ok(recv.clone()),
1251 m if iterator::is_helper(m) => iterator::call(recv, m, &args),
1252 _ => Err(crate::host::type_error(&format!(
1253 "mapIterator.{method} is not a function"
1254 ))),
1255 },
1256 "IteratorHelper" => match method {
1257 "next" => iterator::helper_next(recv),
1258 "@@iterator" => Ok(recv.clone()),
1259 "return" => Ok(iterator::helper_return(recv)),
1263 m if iterator::is_helper(m) => iterator::call(recv, m, &args),
1264 _ => Err(crate::host::type_error(&format!(
1265 "{method} is not a function"
1266 ))),
1267 },
1268 "Date" => date::instance_call(recv, method, &args),
1269 "StringDecoder" => string_decoder::instance_call(recv, method, &args),
1270 "WeakRef" => typedarray::weakref_call(recv, method),
1271 "FinalizationRegistry" => typedarray::finalization_registry_call(recv, method, &args),
1272 "TextEncoder" => typedarray::text_encoder_call(recv, method, &args),
1273 "TextDecoder" => typedarray::text_decoder_call(recv, method, &args),
1274 "TypedArray" => typedarray::instance_call(recv, method, &args),
1275 "DataView" => typedarray::dataview_call(recv, method, &args),
1276 "ArrayBuffer" if method == "slice" => {
1279 if typedarray::is_detached(recv) {
1280 return Err(typedarray::detached_error(
1281 "ArrayBuffer.prototype",
1282 "slice",
1283 true,
1284 ));
1285 }
1286 Ok(typedarray::buffer_slice(recv, &args))
1287 }
1288 "ArrayBuffer" if method == "resize" => typedarray::buffer_resize(recv, &args),
1289 "ArrayBuffer" if method == "transfer" => typedarray::buffer_transfer(recv, &args, false),
1290 "ArrayBuffer" if method == "transferToFixedLength" => {
1291 typedarray::buffer_transfer(recv, &args, true)
1292 }
1293 t if fetch::is_class(t) => fetch::instance_call(t, recv, method, &args),
1294 "EventTarget" | "Event" | "CustomEvent" => {
1295 event_target::instance_call(tag, recv, method, &args)
1296 }
1297 "Hash" => crypto::instance_call(recv, method, &args),
1298 "Hmac" => crypto::hmac_instance_call(recv, method, &args),
1299 "Interface" => readline::instance_call(recv, method, args),
1300 "ReadlineIterator" => readline::iterator_call(recv, method),
1301 "Script" => vm::instance_call(recv, method, args),
1302 "URLSearchParams" => url::search_params_call(recv, method, &args),
1303 "UdpSocket" => dgram::instance_call(recv, method, args),
1304 "Worker" | "MessagePort" | "BroadcastChannel" => {
1305 worker_threads::instance_call(tag, recv, method, args)
1306 }
1307 "TLSServer" | "TLSSocket" => tls::instance_call(tag, recv, method, args),
1308 "HTTPSServerResponse" | "HTTPSClientRequest" => {
1309 https::instance_call(tag, recv, method, args)
1310 }
1311 "REPLServer" => repl::instance_call(recv, method, args),
1312 "ClusterWorker" => cluster::instance_call(recv, method, args),
1313 "Domain" => domain::instance_call(recv, method, args),
1314 "Tracing" => trace_events::instance_call(recv, method, args),
1315 "Http2Server" | "Http2Stream" | "Http2Session" => {
1316 http2::instance_call(tag, recv, method, args)
1317 }
1318 "EventEmitter" => events::instance_call(recv, method, args),
1319 "URL" => url::instance_call(recv, method, &args),
1320 "Stats" | "BigIntStats" => fs::stats_call(recv, method),
1321 "Dirent" => fs::dirent_call(recv, method),
1322 "Dir" => fs::dir_call(recv, method, args),
1323 "FSReadStream" => fs::read_stream_call(recv, method, args),
1324 "FSWriteStream" => fs::write_stream_call(recv, method, args),
1325 "Server" | "Socket" | "BlockList" => net::instance_call(tag, recv, method, args),
1326 "IncomingMessage" | "ServerResponse" | "ClientRequest" | "Agent" => {
1327 http::instance_call(tag, recv, method, args)
1328 }
1329 "Readable" | "Writable" | "Duplex" | "Transform" | "PassThrough" | "Stream" => {
1330 stream::instance_call(tag, recv, method, args)
1331 }
1332 "Cipheriv" | "Decipheriv" => crypto::cipher_instance_call(tag, recv, method, &args),
1333 "Sign" | "Verify" => crypto::sign_verify_instance_call(tag, recv, method, &args),
1334 "KeyObject"
1335 | "SecretKeyObject"
1336 | "AsymmetricKeyObject"
1337 | "PublicKeyObject"
1338 | "PrivateKeyObject" => crypto::key_object_instance_call(recv, method, &args),
1339 "DiffieHellman" => crypto::dh_instance_call(recv, method, &args),
1340 "ECDH" => crypto::ecdh_instance_call(recv, method, &args),
1341 "X509Certificate" => crypto::x509_instance_call(recv, method, &args),
1342 "MIMEType" => util::mime_type_instance_call(recv, method, &args),
1343 "MIMEParams" => util::mime_params_instance_call(recv, method, &args),
1344 "Blob" | "File" => buffer::blob_call(recv, method, &args),
1345 "ReadStream" => tty::instance_call(recv, method, &args),
1346 "Resolver" => dns::resolver_instance_call(recv, method, args),
1347 "Histogram" => perf_hooks::histogram_instance_call(recv, method, &args),
1348 "PerformanceObserver" => perf_hooks::observer_instance_call(recv, method, &args),
1349 "PerformanceObserverEntryList" => perf_hooks::entry_list_instance_call(recv, method, &args),
1350 "TracingChannel" => diagnostics_channel::tracing_instance_call(recv, method, &args),
1351 "Serializer" | "Deserializer" => v8::instance_call(tag, recv, method, args),
1352 "Console" => console::instance_call(recv, method, args),
1353 "ChildProcess" => child_process::instance_call(recv, method, args),
1354 "ChildPipe" => child_process::pipe_call(recv, method, args),
1355 "AsyncLocalStorage" | "AsyncHook" | "AsyncResource" => {
1356 async_hooks::instance_call(tag, recv, method, args)
1357 }
1358 "Channel" => diagnostics_channel::instance_call(recv, method, &args),
1359 "WriteStream" => process::stream_instance_call(recv, method, &args),
1360 "StdinIterator" => process::stdin_iterator_call(recv, method),
1361 _ => Err(crate::host::type_error(&format!(
1362 "{method} is not a function"
1363 ))),
1364 }
1365}
1366
1367pub(crate) fn received_desc(v: &Value) -> String {
1374 with_host(|h| {
1375 if matches!(v, Value::Undef) {
1376 return "undefined".to_string();
1377 }
1378 if h.is_null(v) {
1379 return "null".to_string();
1380 }
1381 let ty = h.type_of(v);
1382 if ty == "function" {
1386 return format!("function {}", h.callable_name(v));
1387 }
1388 if ty == "object" {
1389 let name = match h.ctor_name(v) {
1392 n if !n.is_empty() => n,
1393 _ => match h.get(v) {
1394 Some(JsObj::Array(_)) => "Array".into(),
1395 Some(JsObj::Map { .. }) => "Map".into(),
1396 Some(JsObj::Set { .. }) => "Set".into(),
1397 Some(JsObj::Promise { .. }) => "Promise".into(),
1398 Some(JsObj::RegExp(_)) => "RegExp".into(),
1399 Some(JsObj::Object(p)) => match p.get("@@native") {
1400 Some(t) => h.str_of(t),
1401 None => "Object".into(),
1402 },
1403 _ => "Object".into(),
1404 },
1405 };
1406 return format!("an instance of {name}");
1407 }
1408 let shown = match ty {
1409 "string" => format!("'{}'", h.str_of(v)),
1410 "bigint" => format!("{}n", h.str_of(v)),
1411 "number" if matches!(v, Value::Float(f) if *f == 0.0 && f.is_sign_negative()) => {
1412 "-0".to_string()
1413 }
1414 _ => h.str_of(v),
1415 };
1416 format!("type {ty} ({shown})")
1417 })
1418}
1419
1420pub(crate) fn arg_str(args: &[Value], i: usize) -> String {
1422 with_host(|h| args.get(i).map(|v| h.str_of(v)).unwrap_or_default())
1423}
1424
1425pub(crate) fn arg_num(args: &[Value], i: usize) -> f64 {
1427 with_host(|h| args.get(i).map(|v| h.to_number(v)).unwrap_or(f64::NAN))
1428}
1429
1430pub(crate) fn to_hex(bytes: &[u8]) -> String {
1432 let mut s = String::with_capacity(bytes.len() * 2);
1433 for b in bytes {
1434 s.push(char::from_digit((b >> 4) as u32, 16).unwrap());
1435 s.push(char::from_digit((b & 0xf) as u32, 16).unwrap());
1436 }
1437 s
1438}
1439
1440pub(crate) fn from_hex(s: &str) -> Vec<u8> {
1445 let digit = |c: u8| (c as char).to_digit(16).map(|d| d as u8);
1446 s.as_bytes()
1447 .chunks_exact(2)
1448 .map_while(|p| Some((digit(p[0])? << 4) | digit(p[1])?))
1449 .collect()
1450}
1451
1452const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1453
1454pub(crate) fn to_base64(bytes: &[u8]) -> String {
1456 let mut out = String::new();
1457 for chunk in bytes.chunks(3) {
1458 let b = [
1459 chunk[0],
1460 *chunk.get(1).unwrap_or(&0),
1461 *chunk.get(2).unwrap_or(&0),
1462 ];
1463 let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | (b[2] as u32);
1464 out.push(B64[((n >> 18) & 63) as usize] as char);
1465 out.push(B64[((n >> 12) & 63) as usize] as char);
1466 out.push(if chunk.len() > 1 {
1467 B64[((n >> 6) & 63) as usize] as char
1468 } else {
1469 '='
1470 });
1471 out.push(if chunk.len() > 2 {
1472 B64[(n & 63) as usize] as char
1473 } else {
1474 '='
1475 });
1476 }
1477 out
1478}
1479
1480pub(crate) fn to_base64url(bytes: &[u8]) -> String {
1485 to_base64(bytes)
1486 .chars()
1487 .filter(|c| *c != '=')
1488 .map(|c| match c {
1489 '+' => '-',
1490 '/' => '_',
1491 c => c,
1492 })
1493 .collect()
1494}
1495
1496pub(crate) fn from_base64(s: &str) -> Vec<u8> {
1506 let rev = |c: u8| -> Option<u32> {
1507 let c = match c {
1508 b'-' => b'+',
1509 b'_' => b'/',
1510 c => c,
1511 };
1512 B64.iter().position(|&x| x == c).map(|p| p as u32)
1513 };
1514 let vals: Vec<u32> = s.bytes().filter_map(rev).collect();
1515 let mut out = Vec::new();
1516 for chunk in vals.chunks(4) {
1517 if chunk.len() < 2 {
1518 break;
1519 }
1520 let n = (chunk[0] << 18)
1521 | (chunk[1] << 12)
1522 | (chunk.get(2).copied().unwrap_or(0) << 6)
1523 | chunk.get(3).copied().unwrap_or(0);
1524 out.push((n >> 16) as u8);
1525 if chunk.len() > 2 {
1526 out.push((n >> 8) as u8);
1527 }
1528 if chunk.len() > 3 {
1529 out.push(n as u8);
1530 }
1531 }
1532 out
1533}
1534
1535pub(crate) fn validate_integer(v: &Value, name: &str, min: f64) -> Result<f64, String> {
1539 validate_integer_in(v, name, min, 9_007_199_254_740_991.0)
1540}
1541
1542pub(crate) fn validate_integer_in(
1544 v: &Value,
1545 name: &str,
1546 min: f64,
1547 max: f64,
1548) -> Result<f64, String> {
1549 if with_host(|h| h.type_of(v)) != "number" {
1550 return Err(crate::host::invalid_arg_type(name, "argument", "number", v));
1551 }
1552 let n = with_host(|h| h.to_number(v));
1553 if n.fract() != 0.0 || !n.is_finite() {
1554 return Err(out_of_range(name, "an integer", n));
1555 }
1556 if n < min || n > max {
1557 let must = format!(
1558 ">= {} && <= {}",
1559 crate::host::fmt_number(min),
1560 crate::host::fmt_number(max)
1561 );
1562 return Err(out_of_range(name, &must, n));
1563 }
1564 Ok(n)
1565}
1566
1567pub(crate) fn out_of_range(name: &str, must: &str, n: f64) -> String {
1570 crate::host::coded_error(
1571 "RangeError",
1572 "ERR_OUT_OF_RANGE",
1573 &format!(
1574 "The value of \"{name}\" is out of range. It must be {must}. Received {}",
1575 buffer::out_of_range_received(n)
1576 ),
1577 )
1578}
1579
1580pub fn singleton_class(ns: &str) -> Option<&'static str> {
1586 match ns {
1587 "performance" => Some("Performance"),
1588 "webcrypto" => Some("Crypto"),
1589 "SubtleCrypto" => Some(SUBTLE_CRYPTO_CLASS),
1590 _ => None,
1591 }
1592}
1593
1594pub const SUBTLE_CRYPTO_CLASS: &str = "webcrypto.SubtleCrypto";
1598
1599pub fn class_display_name(key: &str) -> &str {
1601 key.rsplit('.').next().unwrap_or(key)
1602}
1603
1604pub fn brand_checked_class(ctor: &str) -> bool {
1607 matches!(ctor, "Crypto" | "CryptoKey")
1608}
1609
1610pub fn illegal_constructor(name: &str) -> bool {
1612 matches!(
1613 name,
1614 "Performance" | "Crypto" | "CryptoKey" | SUBTLE_CRYPTO_CLASS
1615 )
1616}