Skip to content

Commit

Permalink
feat: binding ContextReplacementPlugin
Browse files Browse the repository at this point in the history
  • Loading branch information
SyMind committed Sep 10, 2024
1 parent f113b53 commit 558cf00
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 36 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 15 additions & 1 deletion crates/node_binding/src/plugins/interceptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ use rspack_core::{
NormalModuleFactoryResolveHook, NormalModuleFactoryResolveResult, ResourceData, RuntimeGlobals,
Scheme,
};
use rspack_error::miette::IntoDiagnostic;
use rspack_hash::RspackHash;
use rspack_hook::{Hook, Interceptor};
use rspack_napi::threadsafe_function::ThreadsafeFunction;
Expand Down Expand Up @@ -1507,19 +1508,31 @@ impl ContextModuleFactoryBeforeResolve for ContextModuleFactoryBeforeResolveTap
let js_result = match result {
BeforeResolveResult::Ignored => JsContextModuleFactoryBeforeResolveResult::A(false),
BeforeResolveResult::Data(d) => {
let reg_exp = match d.reg_exp {
Some(js_regex) => Some(js_regex.try_into().into_diagnostic()?),
None => None,
};
JsContextModuleFactoryBeforeResolveResult::B(JsContextModuleFactoryBeforeResolveData {
context: d.context,
request: d.request,
reg_exp,
recursive: d.recursive,
})
}
};
match self.function.call_with_promise(js_result).await {
Ok(js_result) => match js_result {
napi::bindgen_prelude::Either::A(_) => Ok(BeforeResolveResult::Ignored),
napi::bindgen_prelude::Either::B(d) => {
let reg_exp = match d.reg_exp {
Some(js_regex) => Some(js_regex.try_into()?),
None => None,
};
let data = BeforeResolveData {
context: d.context,
request: d.request,
reg_exp,
recursive: d.recursive,
};
Ok(BeforeResolveResult::Data(Box::new(data)))
}
Expand All @@ -1544,6 +1557,7 @@ impl ContextModuleFactoryAfterResolve for ContextModuleFactoryAfterResolveTap {
context: d.context.to_owned(),
request: d.request.to_owned(),
reg_exp: d.reg_exp.clone().map(|r| r.into()),
recursive: d.recursive,
})
}
};
Expand All @@ -1558,7 +1572,7 @@ impl ContextModuleFactoryAfterResolve for ContextModuleFactoryAfterResolveTap {
Some(r) => Some(r.try_into()?),
None => None,
},
recursive: todo!(),
recursive: d.recursive,
};
Ok(AfterResolveResult::Data(Box::new(data)))
}
Expand Down
2 changes: 2 additions & 0 deletions crates/rspack_binding_options/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ ignored = ["tracing"]
[dependencies]
async-trait = { workspace = true }
derivative = { workspace = true }
futures = { workspace = true }
glob = { workspace = true }
napi = { workspace = true, features = ["async", "tokio_rt", "serde-json", "anyhow"] }
napi-derive = { workspace = true }
Expand All @@ -35,6 +36,7 @@ rspack_napi_macros = { version = "0.1.0", path = "../rspack_n
rspack_paths = { version = "0.1.0", path = "../rspack_paths" }
rspack_plugin_asset = { version = "0.1.0", path = "../rspack_plugin_asset" }
rspack_plugin_banner = { version = "0.1.0", path = "../rspack_plugin_banner" }
rspack_plugin_context_replacement = { version = "0.1.0", path = "../rspack_plugin_context_replacement" }
rspack_plugin_copy = { version = "0.1.0", path = "../rspack_plugin_copy" }
rspack_plugin_css = { version = "0.1.0", path = "../rspack_plugin_css" }
rspack_plugin_devtool = { version = "0.1.0", path = "../rspack_plugin_devtool" }
Expand Down
13 changes: 10 additions & 3 deletions crates/rspack_binding_options/src/options/raw_builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use rspack_ids::{
use rspack_napi::NapiResultExt;
use rspack_plugin_asset::AssetPlugin;
use rspack_plugin_banner::BannerPlugin;
use rspack_plugin_context_replacement::ContextReplacementPlugin;
use rspack_plugin_copy::{CopyRspackPlugin, CopyRspackPluginOptions};
use rspack_plugin_css::CssPlugin;
use rspack_plugin_devtool::{
Expand Down Expand Up @@ -92,9 +93,9 @@ use self::{
};
use crate::{
plugins::{CssExtractRspackAdditionalDataPlugin, JsLoaderRspackPlugin},
JsLoaderRunner, RawDynamicEntryPluginOptions, RawEvalDevToolModulePluginOptions,
RawExternalItemWrapper, RawExternalsPluginOptions, RawHttpExternalsRspackPluginOptions,
RawSourceMapDevToolPluginOptions, RawSplitChunksOptions,
JsLoaderRunner, RawContextReplacementPluginOptions, RawDynamicEntryPluginOptions,
RawEvalDevToolModulePluginOptions, RawExternalItemWrapper, RawExternalsPluginOptions,
RawHttpExternalsRspackPluginOptions, RawSourceMapDevToolPluginOptions, RawSplitChunksOptions,
};

#[napi(string_enum)]
Expand Down Expand Up @@ -162,6 +163,7 @@ pub enum BuiltinPluginName {
RuntimeChunkPlugin,
SizeLimitsPlugin,
NoEmitOnErrorsPlugin,
ContextReplacementPlugin,

// rspack specific plugins
// naming format follow XxxRspackPlugin
Expand Down Expand Up @@ -507,6 +509,11 @@ impl BuiltinPlugin {
BuiltinPluginName::NoEmitOnErrorsPlugin => {
plugins.push(NoEmitOnErrorsPlugin::default().boxed());
}
BuiltinPluginName::ContextReplacementPlugin => {
let raw_options = downcast_into::<RawContextReplacementPluginOptions>(self.options)?;
let options = raw_options.try_into()?;
plugins.push(ContextReplacementPlugin::new(options).boxed());
}
}
Ok(())
}
Expand Down
37 changes: 37 additions & 0 deletions crates/rspack_binding_options/src/plugins/context_replacement.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use napi_derive::napi;
use rspack_binding_values::RawRegex;
use rspack_error::Error;
use rspack_plugin_context_replacement::ContextReplacementPluginOptions;
use rspack_regex::RspackRegex;

#[napi(object, object_to_js = false)]
pub struct RawContextReplacementPluginOptions {
pub resource_reg_exp: RawRegex,
pub new_content_resource: Option<String>,
pub new_content_recursive: Option<bool>,
pub new_content_reg_exp: Option<RawRegex>,
// new_content_callback
}

impl TryFrom<RawContextReplacementPluginOptions> for ContextReplacementPluginOptions {
type Error = Error;

fn try_from(val: RawContextReplacementPluginOptions) -> Result<Self, Self::Error> {
let new_content_reg_exp = match val.new_content_reg_exp {
Some(js_regex) => {
let regex = RspackRegex::with_flags(&js_regex.source, &js_regex.flags)?;
Some(regex)
}
None => None,
};
Ok(Self {
resource_reg_exp: RspackRegex::with_flags(
&val.resource_reg_exp.source,
&val.resource_reg_exp.flags,
)?,
new_content_resource: val.new_content_resource,
new_content_recursive: val.new_content_recursive,
new_content_reg_exp,
})
}
}
3 changes: 3 additions & 0 deletions crates/rspack_binding_options/src/plugins/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
mod context_replacement;
mod css_extract_additional_data;
mod js_loader;

pub use context_replacement::*;
pub(super) use css_extract_additional_data::CssExtractRspackAdditionalDataPlugin;
pub(super) use js_loader::{JsLoaderRspackPlugin, JsLoaderRunner};
3 changes: 3 additions & 0 deletions crates/rspack_binding_values/src/context_module_factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use crate::RawRegex;
pub struct JsContextModuleFactoryBeforeResolveData {
pub context: String,
pub request: Option<String>,
pub reg_exp: Option<RawRegex>,
pub recursive: bool,
}

pub type JsContextModuleFactoryBeforeResolveResult =
Expand All @@ -18,6 +20,7 @@ pub struct JsContextModuleFactoryAfterResolveData {
pub context: String,
pub request: String,
pub reg_exp: Option<RawRegex>,
pub recursive: bool,
}

pub type JsContextModuleFactoryAfterResolveResult =
Expand Down
49 changes: 18 additions & 31 deletions crates/rspack_plugin_context_replacement/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use derivative::Derivative;
use futures::future::BoxFuture;
use rspack_core::{
AfterResolveResult, ApplyContext, BeforeResolveResult, CompilerOptions,
ContextModuleFactoryAfterResolve, ContextModuleFactoryBeforeResolve, Plugin, PluginContext,
Expand All @@ -8,20 +7,11 @@ use rspack_error::Result;
use rspack_hook::{plugin, plugin_hook};
use rspack_regex::RspackRegex;

enum ResolveResult {
Before(BeforeResolveResult),
After(AfterResolveResult),
}

pub type ContentCallback =
Box<dyn Fn(&mut ResolveResult) -> BoxFuture<'static, Result<()>> + Sync + Send>;

pub struct ContextReplacementPluginOptions {
resource_reg_exp: RspackRegex,
new_content_resource: Option<String>,
new_content_recursive: Option<bool>,
new_content_reg_exp: Option<RspackRegex>,
new_content_callback: Option<ContentCallback>,
pub resource_reg_exp: RspackRegex,
pub new_content_resource: Option<String>,
pub new_content_recursive: Option<bool>,
pub new_content_reg_exp: Option<RspackRegex>,
}

#[plugin]
Expand All @@ -32,8 +22,6 @@ pub struct ContextReplacementPlugin {
new_content_resource: Option<String>,
new_content_recursive: Option<bool>,
new_content_reg_exp: Option<RspackRegex>,
#[derivative(Debug = "ignore")]
new_content_callback: Option<ContentCallback>,
}

impl ContextReplacementPlugin {
Expand All @@ -43,7 +31,6 @@ impl ContextReplacementPlugin {
options.new_content_resource,
options.new_content_recursive,
options.new_content_reg_exp,
options.new_content_callback,
)
}
}
Expand All @@ -61,13 +48,13 @@ async fn cmf_before_resolve(&self, mut result: BeforeResolveResult) -> Result<Be
if let Some(new_content_reg_exp) = &self.new_content_reg_exp {
data.reg_exp = Some(new_content_reg_exp.clone());
}
if let Some(new_content_callback) = &self.new_content_callback {
// new_content_callback(&mut result).await?;
} else {
// for (const d of result.dependencies) {
// if (d.critical) d.critical = false;
// }
}
// if let Some(new_content_callback) = &self.new_content_after_resolve_callback {
// // new_content_callback(&mut result).await?;
// } else {
// // for (const d of result.dependencies) {
// // if (d.critical) d.critical = false;
// // }
// }
}
}

Expand Down Expand Up @@ -96,13 +83,13 @@ async fn cmf_after_resolve(&self, mut result: AfterResolveResult) -> Result<Afte
if let Some(new_content_reg_exp) = &self.new_content_reg_exp {
data.reg_exp = Some(new_content_reg_exp.clone());
}
if let Some(new_content_callback) = &self.new_content_callback {
// new_content_callback(&mut result).await?;
} else {
// for (const d of result.dependencies) {
// if (d.critical) d.critical = false;
// }
}
// if let Some(new_content_callback) = &self.new_content_callback {
// // new_content_callback(&mut result).await?;
// } else {
// // for (const d of result.dependencies) {
// // if (d.critical) d.critical = false;
// // }
// }
}
}
Ok(result)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub enum ModuleFilenameTemplate {
Fn(ModuleFilenameTemplateFn),
}

type AppendFn = Box<dyn for<'a> Fn(PathData) -> BoxFuture<'static, Result<String>> + Sync + Send>;
type AppendFn = Box<dyn Fn(PathData) -> BoxFuture<'static, Result<String>> + Sync + Send>;

pub enum Append {
String(String),
Expand Down

0 comments on commit 558cf00

Please sign in to comment.