feat(core) deno_core::extension! macro to simplify extension registration (#18210)

This implements two macros to simplify extension registration and centralize a lot of the boilerplate as a base for future improvements:

* `deno_core::ops!` registers a block of `#[op]`s, optionally with type
parameters, useful for places where we share lists of ops
* `deno_core::extension!` is used to register an extension, and creates
two methods that can be used at runtime/snapshot generation time:
`init_ops` and `init_ops_and_esm`.

---------

Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
This commit is contained in:
Matt Mastracci 2023-03-17 12:22:15 -06:00 committed by GitHub
parent 0bc6bf5d33
commit e55b448730
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
53 changed files with 1690 additions and 1851 deletions

64
ext/cache/lib.rs vendored
View file

@ -7,13 +7,10 @@ use std::sync::Arc;
use async_trait::async_trait;
use deno_core::error::AnyError;
use deno_core::include_js_files;
use deno_core::op;
use deno_core::serde::Deserialize;
use deno_core::serde::Serialize;
use deno_core::ByteString;
use deno_core::Extension;
use deno_core::ExtensionBuilder;
use deno_core::OpState;
use deno_core::Resource;
use deno_core::ResourceId;
@ -23,46 +20,27 @@ pub use sqlite::SqliteBackedCache;
#[derive(Clone)]
pub struct CreateCache<C: Cache + 'static>(pub Arc<dyn Fn() -> C>);
fn ext() -> ExtensionBuilder {
Extension::builder_with_deps(
env!("CARGO_PKG_NAME"),
&["deno_webidl", "deno_web", "deno_url", "deno_fetch"],
)
}
fn ops<CA: Cache + 'static>(
ext: &mut ExtensionBuilder,
maybe_create_cache: Option<CreateCache<CA>>,
) -> &mut ExtensionBuilder {
ext
.ops(vec![
op_cache_storage_open::decl::<CA>(),
op_cache_storage_has::decl::<CA>(),
op_cache_storage_delete::decl::<CA>(),
op_cache_put::decl::<CA>(),
op_cache_match::decl::<CA>(),
op_cache_delete::decl::<CA>(),
])
.state(move |state| {
if let Some(create_cache) = maybe_create_cache.clone() {
state.put(create_cache);
}
})
}
pub fn init_ops_and_esm<CA: Cache + 'static>(
maybe_create_cache: Option<CreateCache<CA>>,
) -> Extension {
ops::<CA>(&mut ext(), maybe_create_cache)
.esm(include_js_files!("01_cache.js",))
.build()
}
pub fn init_ops<CA: Cache + 'static>(
maybe_create_cache: Option<CreateCache<CA>>,
) -> Extension {
ops::<CA>(&mut ext(), maybe_create_cache).build()
}
deno_core::extension!(deno_cache,
deps = [ deno_webidl, deno_web, deno_url, deno_fetch ],
parameters=[CA: Cache],
ops = [
op_cache_storage_open<CA>,
op_cache_storage_has<CA>,
op_cache_storage_delete<CA>,
op_cache_put<CA>,
op_cache_match<CA>,
op_cache_delete<CA>,
],
esm = [ "01_cache.js" ],
config = {
maybe_create_cache: Option<CreateCache<CA>>,
},
state = |state, maybe_create_cache| {
if let Some(create_cache) = maybe_create_cache {
state.put(create_cache);
}
},
);
pub fn get_declaration() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("lib.deno_cache.d.ts")