Skip to content

Commit

Permalink
fix: avoid break change
Browse files Browse the repository at this point in the history
  • Loading branch information
shulandmimi committed May 6, 2024
1 parent 57dfbc6 commit 63630db
Show file tree
Hide file tree
Showing 15 changed files with 335 additions and 210 deletions.
24 changes: 12 additions & 12 deletions crates/compiler/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ pub fn create_css_compiler(
..Default::default()
},
mode: Mode::Production,
external: ExternalConfig(vec![
ExternalConfigItem::Default(ConfigRegex::new("^react-refresh$")),
ExternalConfigItem::Default(ConfigRegex::new("^module$")),
]),
external: vec![
ConfigRegex::new("^react-refresh$"),
ConfigRegex::new("^module$"),
],
sourcemap: SourcemapConfig::Bool(false),
css: css_config,
lazy_compilation: false,
Expand Down Expand Up @@ -128,10 +128,10 @@ pub fn create_compiler(
..Default::default()
},
mode: Mode::Production,
external: ExternalConfig(vec![
ExternalConfigItem::Default(ConfigRegex::new("^react-refresh$")),
ExternalConfigItem::Default(ConfigRegex::new("^module$")),
]),
external: vec![
ConfigRegex::new("^react-refresh$"),
ConfigRegex::new("^module$"),
],
sourcemap: SourcemapConfig::Bool(false),
lazy_compilation: false,
progress: false,
Expand Down Expand Up @@ -180,10 +180,10 @@ pub fn create_compiler_with_plugins(
swc_helpers_path,
..Default::default()
},
external: ExternalConfig(vec![
ExternalConfigItem::Default(ConfigRegex::new("^react-refresh$")),
ExternalConfigItem::Default(ConfigRegex::new("^module$")),
]),
external: vec![
ConfigRegex::new("^react-refresh$"),
ConfigRegex::new("^module$"),
],
sourcemap: SourcemapConfig::Bool(false),
lazy_compilation: false,
progress: false,
Expand Down
27 changes: 16 additions & 11 deletions crates/compiler/tests/external.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ use crate::common::{assert_compiler_result, create_compiler_with_args};
use std::{collections::HashMap, path::PathBuf};

use farmfe_core::config::{
config_regex::ConfigRegex,
external::{ExternalConfig, ExternalConfigItem, ExternalObject},
ModuleFormat, TargetEnv,
config_regex::ConfigRegex, custom::CUSTOM_CONFIG_EXTERNAL_RECORD, ModuleFormat, TargetEnv,
};

fn test(file: String, crate_path: String) {
Expand All @@ -15,7 +13,7 @@ fn test(file: String, crate_path: String) {
println!("testing test case: {:?}", cwd);

let entry_name = "index".to_string();
let normolized_file = file.replace('\\', "/");
let normolized_file = file.replace('\\', "/");
let compiler =
create_compiler_with_args(cwd.to_path_buf(), create_path_buf, |mut config, plugins| {
config.input = HashMap::from_iter(vec![(entry_name.clone(), file.clone())]);
Expand All @@ -29,14 +27,21 @@ let normolized_file = file.replace('\\', "/");
}

if normolized_file.contains("/normal/") || normolized_file.contains("/object/") || true {
config.external = ExternalConfig(vec![if normolized_file.contains("/object") {
ExternalConfigItem::Object(ExternalObject {
pattern: ConfigRegex::new("^jquery$"),
global_name: "$".to_string(),
})
if normolized_file.contains("/object") {
config
.custom
.entry(CUSTOM_CONFIG_EXTERNAL_RECORD.to_string())
.or_insert(
r#"
{
"jquery": "$"
}
"#
.to_string(),
);
} else {
ExternalConfigItem::Default(ConfigRegex::new("^jquery$"))
}]);
config.external = vec![ConfigRegex::new("^jquery$")];
}
}

if normolized_file.contains("/cjs/") || normolized_file.contains("/esm/") {
Expand Down
9 changes: 4 additions & 5 deletions crates/compiler/tests/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use common::generate_runtime;
use farmfe_compiler::{Compiler, DYNAMIC_VIRTUAL_SUFFIX};
use farmfe_core::config::bool_or_obj::BoolOrObj;
use farmfe_core::config::config_regex::ConfigRegex;
use farmfe_core::config::external::{ExternalConfig, ExternalConfigItem};
use farmfe_core::config::persistent_cache::PersistentCacheConfig;
use farmfe_core::config::TargetEnv;
use farmfe_core::config::{preset_env::PresetEnvConfig, Config, Mode, SourcemapConfig};
Expand Down Expand Up @@ -35,10 +34,10 @@ fn create_compiler_internal(
..Default::default()
},
mode: Mode::Development,
external: ExternalConfig(vec![
ExternalConfigItem::Default(ConfigRegex::new("^react-refresh$")),
ExternalConfigItem::Default(ConfigRegex::new("^module$")),
]),
external: vec![
ConfigRegex::new("^react-refresh$"),
ConfigRegex::new("^module$"),
],
sourcemap: SourcemapConfig::Bool(false),
progress: false,
lazy_compilation,
Expand Down
36 changes: 35 additions & 1 deletion crates/core/src/config/custom.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
use std::sync::Arc;
use std::{collections::HashMap, sync::Arc};

use crate::context::CompilationContext;

use super::{
config_regex::ConfigRegex,
external::{ExternalConfig, ExternalObject},
Config,
};

const CUSTOM_CONFIG_RUNTIME_ISOLATE: &str = "runtime.isolate";
pub const CUSTOM_CONFIG_EXTERNAL_RECORD: &str = "RECORD_EXTERNAL";

pub fn get_config_runtime_isolate(context: &Arc<CompilationContext>) -> bool {
if let Some(val) = context.config.custom.get(CUSTOM_CONFIG_RUNTIME_ISOLATE) {
Expand All @@ -11,3 +18,30 @@ pub fn get_config_runtime_isolate(context: &Arc<CompilationContext>) -> bool {
false
}
}

pub fn get_config_external_record(config: &Config) -> ExternalConfig {
if let Some(val) = config.custom.get(CUSTOM_CONFIG_EXTERNAL_RECORD) {
if val.is_empty() {
return ExternalConfig::new();
}

let external: HashMap<String, String> = serde_json::from_str(val)
.unwrap_or_else(|_| panic!("failed parse record external {:?}", val));

let mut external_config = ExternalConfig::new();

for (regex, name) in external {
external_config
.0
.push(super::external::ExternalConfigItem::Object(
ExternalObject {
pattern: ConfigRegex::new(&regex),
global_name: name,
},
));
}
external_config
} else {
ExternalConfig::new()
}
}
16 changes: 15 additions & 1 deletion crates/core/src/config/external.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};

use super::config_regex::ConfigRegex;
use super::{config_regex::ConfigRegex, custom::get_config_external_record, Config};

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", default)]
Expand Down Expand Up @@ -55,6 +55,20 @@ impl ExternalConfigItem {
}
}

impl From<&Config> for ExternalConfig {
fn from(config: &Config) -> Self {
let mut external_config = get_config_external_record(config);

for external in &config.external {
external_config
.0
.push(ExternalConfigItem::Default(external.clone()))
}

external_config
}
}

#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};
Expand Down
4 changes: 2 additions & 2 deletions crates/core/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub struct Config {
pub root: String,
pub mode: Mode,
pub resolve: ResolveConfig,
pub external: ExternalConfig,
pub external: Vec<ConfigRegex>,
pub define: HashMap<String, serde_json::Value>,
pub runtime: RuntimeConfig,
pub script: ScriptConfig,
Expand Down Expand Up @@ -74,7 +74,7 @@ impl Default for Config {
mode: Mode::Development,
resolve: ResolveConfig::default(),
define: HashMap::new(),
external: ExternalConfig::default(),
external: Default::default(),
runtime: Default::default(),
script: Default::default(),
css: Default::default(),
Expand Down
4 changes: 1 addition & 3 deletions crates/node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,16 +167,14 @@ impl JsCompiler {
.expect("rustPlugins should be an array of js strings")
};

let serde_value: farmfe_core::serde_json::Value = env
let config: Config = env
.from_js_value(
config
.get_named_property::<JsObject>("config")
.expect("config should exist"),
)
.expect("can not transform js config object to rust config");

let config: Config = farmfe_core::serde_json::from_value(serde_value).unwrap();

let mut plugins_adapters = vec![];

for js_plugin_object in js_plugins {
Expand Down
12 changes: 8 additions & 4 deletions crates/plugin_lazy_compilation/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashMap;

use farmfe_core::{
config::{Config, FARM_MODULE_SYSTEM},
config::{external::ExternalConfig, Config, FARM_MODULE_SYSTEM},
module::{ModuleId, ModuleType},
plugin::{Plugin, PluginHookContext, PluginLoadHookResult, PluginResolveHookParam, ResolveKind},
};
Expand Down Expand Up @@ -106,10 +106,14 @@ impl Plugin for FarmPluginLazyCompilation {
}
}

let is_external = || {
let external_config = ExternalConfig::from(&*context.config);

external_config.is_external(&param.source)
};

// if the source is imported by dynamic import and it's not external source
if matches!(param.kind, ResolveKind::DynamicImport)
&& !context.config.external.is_external(&param.source)
{
if matches!(param.kind, ResolveKind::DynamicImport) && !is_external() {
let resolve_result = context.plugin_driver.resolve(
param,
context,
Expand Down
32 changes: 28 additions & 4 deletions crates/plugin_resolve/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
use std::{collections::HashMap, path::Path, sync::Arc};
use std::{
collections::HashMap,
path::Path,
sync::{Arc, RwLock},
};

use farmfe_core::{
config::Config,
config::{external::ExternalConfig, Config},
context::CompilationContext,
error::Result,
error::{CompilationError, Result},
farm_profile_function, farm_profile_scope,
plugin::{
Plugin, PluginHookContext, PluginResolveHookParam, PluginResolveHookResult, ResolveKind,
Expand All @@ -18,13 +22,15 @@ pub mod resolver;
pub struct FarmPluginResolve {
root: String,
resolver: Resolver,
external_config: RwLock<Option<ExternalConfig>>,
}

impl FarmPluginResolve {
pub fn new(config: &Config) -> Self {
Self {
root: config.root.clone(),
resolver: Resolver::new(),
external_config: RwLock::new(None)
}
}
}
Expand All @@ -42,6 +48,24 @@ impl Plugin for FarmPluginResolve {
) -> Result<Option<PluginResolveHookResult>> {
farm_profile_function!("plugin_resolve::resolve".to_string());

let mut external_config = self
.external_config
.read()
.map_err(|_| CompilationError::GenericError("failed get lock".to_string()))?;

if external_config.is_none() {
drop(external_config);
let mut external_config_mut = self.external_config.write().unwrap();

*external_config_mut = Some(ExternalConfig::from(&*context.config));

drop(external_config_mut);

external_config = self.external_config.read().unwrap();
}

let external_config = external_config.as_ref().unwrap();

let source = &param.source;

let query = parse_query(source);
Expand Down Expand Up @@ -71,7 +95,7 @@ impl Plugin for FarmPluginResolve {
{
farm_profile_scope!("plugin_resolve::resolve::check_external".to_string());
// check external first, if the source is set as external, return it immediately
if context.config.external.is_external(source) {
if external_config.is_external(source) {
return Ok(Some(PluginResolveHookResult {
resolved_path: param.source.clone(),
external: true,
Expand Down
15 changes: 9 additions & 6 deletions crates/plugin_runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ use std::{

use farmfe_core::{
config::{
config_regex::ConfigRegex, partial_bundling::PartialBundlingEnforceResourceConfig, Config,
ModuleFormat, TargetEnv, FARM_MODULE_SYSTEM,
config_regex::ConfigRegex, external::ExternalConfig,
partial_bundling::PartialBundlingEnforceResourceConfig, Config, ModuleFormat, TargetEnv,
FARM_MODULE_SYSTEM,
},
context::CompilationContext,
enhanced_magic_string::types::SourceMapOptions,
Expand Down Expand Up @@ -389,6 +390,7 @@ impl Plugin for FarmPluginRuntime {
let async_modules = self.get_async_modules(context);
let async_modules = async_modules.downcast_ref::<HashSet<ModuleId>>().unwrap();
let module_graph = context.module_graph.read();
let external_config = ExternalConfig::from(&*context.config);
let RenderedJsResourcePot {
mut bundle,
rendered_modules,
Expand Down Expand Up @@ -444,11 +446,12 @@ impl Plugin for FarmPluginRuntime {
let mut external_objs = Vec::new();

for source in external_modules {
let replace_source = match context.config.external.find_match(&source) {
let replace_source = match external_config.find_match(&source) {
Some(v) => Ok(v.source(&source)),
None => Err(CompilationError::GenericError(
format!("cannot find external source: {:?}", source),
)),
None => Err(CompilationError::GenericError(format!(
"cannot find external source: {:?}",
source
))),
}?;

let source_obj = format!("(globalThis||window||{{}})['{}']||{{}}", replace_source);
Expand Down

0 comments on commit 63630db

Please sign in to comment.