2021-04-25 13:23:22 -04:00
|
|
|
use crate::error::type_error;
|
|
|
|
use crate::error::AnyError;
|
2021-04-30 21:08:29 -04:00
|
|
|
use crate::include_js_files;
|
|
|
|
use crate::op_sync;
|
2021-04-25 13:23:22 -04:00
|
|
|
use crate::resources::ResourceId;
|
2021-04-30 21:08:29 -04:00
|
|
|
use crate::Extension;
|
2021-04-25 13:23:22 -04:00
|
|
|
use crate::OpState;
|
2021-05-03 08:51:32 -04:00
|
|
|
use std::io::{stderr, stdout, Write};
|
2021-04-25 13:23:22 -04:00
|
|
|
|
2021-04-30 21:08:29 -04:00
|
|
|
pub(crate) fn init_builtins() -> Extension {
|
|
|
|
Extension::builder()
|
|
|
|
.js(include_js_files!(
|
|
|
|
prefix "deno:core",
|
2021-07-02 06:18:30 -04:00
|
|
|
"00_primordials.js",
|
|
|
|
"01_core.js",
|
|
|
|
"02_error.js",
|
2021-04-30 21:08:29 -04:00
|
|
|
))
|
|
|
|
.ops(vec![
|
|
|
|
("op_close", op_sync(op_close)),
|
2021-05-02 19:30:03 -04:00
|
|
|
("op_print", op_sync(op_print)),
|
2021-04-30 21:08:29 -04:00
|
|
|
("op_resources", op_sync(op_resources)),
|
|
|
|
])
|
|
|
|
.build()
|
|
|
|
}
|
2021-04-25 13:23:22 -04:00
|
|
|
|
|
|
|
/// Return map of resources with id as key
|
|
|
|
/// and string representation as value.
|
|
|
|
pub fn op_resources(
|
|
|
|
state: &mut OpState,
|
|
|
|
_args: (),
|
2021-05-08 08:37:42 -04:00
|
|
|
_: (),
|
2021-04-25 13:23:22 -04:00
|
|
|
) -> Result<Vec<(ResourceId, String)>, AnyError> {
|
|
|
|
let serialized_resources = state
|
|
|
|
.resource_table
|
|
|
|
.names()
|
|
|
|
.map(|(rid, name)| (rid, name.to_string()))
|
|
|
|
.collect();
|
|
|
|
Ok(serialized_resources)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Remove a resource from the resource table.
|
|
|
|
pub fn op_close(
|
|
|
|
state: &mut OpState,
|
|
|
|
rid: Option<ResourceId>,
|
2021-05-08 08:37:42 -04:00
|
|
|
_: (),
|
2021-04-25 13:23:22 -04:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
// TODO(@AaronO): drop Option after improving type-strictness balance in serde_v8
|
|
|
|
let rid = rid.ok_or_else(|| type_error("missing or invalid `rid`"))?;
|
2021-08-15 07:29:19 -04:00
|
|
|
state.resource_table.close(rid)?;
|
2021-04-25 13:23:22 -04:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2021-05-02 19:30:03 -04:00
|
|
|
|
|
|
|
/// Builtin utility to print to stdout/stderr
|
|
|
|
pub fn op_print(
|
|
|
|
_state: &mut OpState,
|
2021-05-15 09:22:57 -04:00
|
|
|
msg: String,
|
|
|
|
is_err: bool,
|
2021-05-02 19:30:03 -04:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
if is_err {
|
2021-06-21 22:39:59 -04:00
|
|
|
stderr().write_all(msg.as_bytes())?;
|
2021-05-03 08:51:32 -04:00
|
|
|
stderr().flush().unwrap();
|
2021-05-02 19:30:03 -04:00
|
|
|
} else {
|
2021-06-21 22:39:59 -04:00
|
|
|
stdout().write_all(msg.as_bytes())?;
|
2021-05-02 19:30:03 -04:00
|
|
|
stdout().flush().unwrap();
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|