diff --git a/Cargo.lock b/Cargo.lock index 1998e45c2..19d5fbe22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -138,12 +138,6 @@ dependencies = [ "libc", ] -[[package]] -name = "anes" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "735d4f398ca57cfa2880225c2bf81c3b9af3be5bb22e44ae70118dad38713e84" - [[package]] name = "anstream" version = "0.6.9" @@ -440,12 +434,6 @@ dependencies = [ "objc2 0.5.2", ] -[[package]] -name = "bpaf" -version = "0.9.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50fd5174866dc2fa2ddc96e8fb800852d37f064f32a45c7b7c2f8fa2c64c77fa" - [[package]] name = "browserslist-rs" version = "0.16.0" @@ -573,12 +561,6 @@ dependencies = [ "vec_map", ] -[[package]] -name = "cast" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" - [[package]] name = "cc" version = "1.0.83" @@ -628,33 +610,6 @@ dependencies = [ "windows-targets 0.52.0", ] -[[package]] -name = "ciborium" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" -dependencies = [ - "ciborium-io", - "ciborium-ll", - "serde", -] - -[[package]] -name = "ciborium-io" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" - -[[package]] -name = "ciborium-ll" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" -dependencies = [ - "ciborium-io", - "half 2.4.1", -] - [[package]] name = "clap" version = "4.5.9" @@ -734,17 +689,6 @@ dependencies = [ "objc", ] -[[package]] -name = "codspeed" -version = "2.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "450a0e9df9df1c154156f4344f99d8f6f6e69d0fc4de96ef6e2e68b2ec3bce97" -dependencies = [ - "colored", - "libc", - "serde_json", -] - [[package]] name = "color_quant" version = "1.1.0" @@ -757,16 +701,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" -[[package]] -name = "colored" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbf2150cce219b664a8a70df7a1f933836724b503f8a413af9365b4dcc4d90b8" -dependencies = [ - "lazy_static", - "windows-sys 0.48.0", -] - [[package]] name = "combine" version = "4.6.7" @@ -1017,25 +951,6 @@ dependencies = [ "napi-derive", ] -[[package]] -name = "criterion2" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7258985df1aa8b33359ee2392cbc3b7802875242cdacdda91a17a602132c24a9" -dependencies = [ - "anes", - "bpaf", - "cast", - "ciborium", - "codspeed", - "colored", - "num-traits", - "oorandom", - "serde", - "serde_json", - "walkdir", -] - [[package]] name = "critical-section" version = "1.1.2" @@ -1085,12 +1000,6 @@ version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345" -[[package]] -name = "crunchy" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" - [[package]] name = "crypto-common" version = "0.1.6" @@ -1585,15 +1494,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" -[[package]] -name = "farmfe_bench" -version = "0.0.1" -dependencies = [ - "criterion2", - "farmfe_compiler", - "farmfe_core", -] - [[package]] name = "farmfe_compiler" version = "0.0.11" @@ -2350,16 +2250,6 @@ version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" -[[package]] -name = "half" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dd08c532ae367adf81c312a4580bc67f1d0fe8bc9c460520283f4c0ff277888" -dependencies = [ - "cfg-if", - "crunchy", -] - [[package]] name = "hash32" version = "0.2.1" @@ -3570,12 +3460,6 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" -[[package]] -name = "oorandom" -version = "11.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9" - [[package]] name = "option-ext" version = "0.2.0" @@ -4427,7 +4311,7 @@ version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" dependencies = [ - "half 1.8.2", + "half", "serde", ] diff --git a/bench/CHANGELOG.md b/bench/CHANGELOG.md index 85cec0e18..4fbafde19 100644 --- a/bench/CHANGELOG.md +++ b/bench/CHANGELOG.md @@ -1,5 +1,12 @@ # bench +## 1.0.18 + +### Patch Changes + +- Updated dependencies [663dfeed] + - @farmfe/core@1.3.29 + ## 1.0.17 ### Patch Changes diff --git a/bench/package.json b/bench/package.json index d7a78eaf3..548f62fc1 100644 --- a/bench/package.json +++ b/bench/package.json @@ -1,6 +1,6 @@ { "name": "bench", - "version": "1.0.17", + "version": "1.0.18", "private": true, "description": "", "scripts": {}, diff --git a/crates/bench/Cargo.toml b/crates/bench/Cargo.toml deleted file mode 100644 index ac3f36ede..000000000 --- a/crates/bench/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "farmfe_bench" -version = "0.0.1" -edition = "2021" -authors = ["brightwu(吴明亮) <1521488775@qq.com>"] -license = "MIT" -description = "Farm Bench" -homepage = "https://farmfe.org" -repository = "https://github.com/farm-fe/farm" -documentation = "https://docs.rs/farmfe_bench" - -[dependencies] -criterion2 = { version = "0.11.0", default-features = false } -farmfe_core = { path = "../core", version = "0.6.4" } -farmfe_compiler = { path = "../compiler", version = "0.0.11" } - -[[bench]] -name = "compiler_bench" -harness = false - -[features] -codspeed = ["criterion2/codspeed"] diff --git a/crates/bench/benches/compiler_bench.rs b/crates/bench/benches/compiler_bench.rs deleted file mode 100644 index a32cd64cf..000000000 --- a/crates/bench/benches/compiler_bench.rs +++ /dev/null @@ -1,56 +0,0 @@ -// use criterion::{black_box, criterion_group, criterion_main, Criterion}; -// // use codspeed_criterion_compat::{black_box, criterion_group, criterion_main, Criterion}; - -// use farmfe_compiler::Compiler; -// use farmfe_core::{ -// config::{Config, RuntimeConfig}, -// relative_path::RelativePath, -// }; - -// fn setup_compiler() -> Compiler { -// let relative_root = RelativePath::new("./index.ts"); -// let cwd = std::env::current_dir().unwrap(); -// let react_examples_root = relative_root.to_logical_path(cwd.clone()); - -// Compiler::new( -// Config { -// root: react_examples_root.to_string_lossy().to_string(), -// runtime: Box::new(RuntimeConfig { -// path: cwd -// .join("packages") -// .join("runtime") -// .join("src") -// .join("index.ts") -// .to_string_lossy() -// .to_string(), -// plugins: vec![], -// swc_helpers_path: cwd -// .join("packages") -// .join("core") -// .join("node_modules") -// .join("@swc") -// .join("helpers") -// .read_link() -// .unwrap() -// .to_string_lossy() -// .to_string(), -// ..Default::default() -// }), -// ..Default::default() -// }, -// vec![], -// ) -// .unwrap() -// } - -// fn bench_compiler_compile(c: &mut Criterion) { -// let mut compiler = setup_compiler(); -// c.bench_function("compiler_compile", |b| { -// b.iter(|| { -// black_box(compiler.compile().unwrap()); -// }) -// }); -// } - -// criterion_group!(benches, bench_compiler_compile); -// criterion_main!(benches); diff --git a/crates/compiler/src/build/mod.rs b/crates/compiler/src/build/mod.rs index c3489764f..0f0aaf266 100644 --- a/crates/compiler/src/build/mod.rs +++ b/crates/compiler/src/build/mod.rs @@ -218,7 +218,7 @@ impl Compiler { if !self.context.log_store.lock().warnings().is_empty() { for warning in self.context.log_store.lock().warnings() { - println!("[warn] {}", warning); + println!("[warn] {warning}"); } } diff --git a/crates/compiler/src/generate/partial_bundling.rs b/crates/compiler/src/generate/partial_bundling.rs index 1600bf643..6587a770b 100644 --- a/crates/compiler/src/generate/partial_bundling.rs +++ b/crates/compiler/src/generate/partial_bundling.rs @@ -229,9 +229,7 @@ mod tests { let module_group_graph = module_group_graph_from_entries( &module_graph .entries - .clone() - .into_iter() - .map(|(entry, _)| entry) + .clone().into_keys() .collect(), &mut module_graph, ); @@ -311,9 +309,7 @@ mod tests { let module_group_graph = module_group_graph_from_entries( &module_graph .entries - .clone() - .into_iter() - .map(|(entry, _)| entry) + .clone().into_keys() .collect(), &mut module_graph, ); diff --git a/crates/compiler/src/lib.rs b/crates/compiler/src/lib.rs index 6d74484c0..a145a71ed 100644 --- a/crates/compiler/src/lib.rs +++ b/crates/compiler/src/lib.rs @@ -157,7 +157,7 @@ impl Compiler { .plugin_driver .write_plugin_cache(&self.context) .unwrap_or_else(|err| { - eprintln!("write plugin cache error: {:?}", err); + eprintln!("write plugin cache error: {err:?}"); }); if matches!(self.context.config.mode, Mode::Development) { diff --git a/crates/compiler/src/update/diff_and_patch_module_graph.rs b/crates/compiler/src/update/diff_and_patch_module_graph.rs index 63ef673d5..491452ce3 100644 --- a/crates/compiler/src/update/diff_and_patch_module_graph.rs +++ b/crates/compiler/src/update/diff_and_patch_module_graph.rs @@ -47,7 +47,7 @@ impl DiffResult { // added_modules: g, h for (module_id, deps_diff_result) in &self.deps_changes { - println!("{:?} -> ", module_id); + println!("{module_id:?} -> "); println!( " added: {:?}", @@ -372,7 +372,7 @@ fn diff_module_deps( let mut children_added = vec![]; if module_graph.has_module(&dep) { - panic!("The module({:?}) exists in previous module graph, this should never happen and there is a internal bug inside farm. Please report it via issues", dep); + panic!("The module({dep:?}) exists in previous module graph, this should never happen and there is a internal bug inside farm. Please report it via issues"); } for child in children { diff --git a/crates/compiler/src/update/mod.rs b/crates/compiler/src/update/mod.rs index 338b5dfb4..5ee3d5ce9 100644 --- a/crates/compiler/src/update/mod.rs +++ b/crates/compiler/src/update/mod.rs @@ -676,8 +676,8 @@ impl Compiler { &removed_modules, &cloned_context, ) { - println!("Failed to regenerate resources: {}", e); - println!("modules to regenerate: {:?}", cloned_updated_module_ids); + println!("Failed to regenerate resources: {e}"); + println!("modules to regenerate: {cloned_updated_module_ids:?}"); } finalize_resources(&cloned_context).unwrap(); diff --git a/crates/compiler/src/update/patch_module_group_graph.rs b/crates/compiler/src/update/patch_module_group_graph.rs index 4812eb57e..b3b7d64ac 100644 --- a/crates/compiler/src/update/patch_module_group_graph.rs +++ b/crates/compiler/src/update/patch_module_group_graph.rs @@ -51,7 +51,7 @@ pub fn patch_module_group_graph( let module_group_ids = { let module = module_graph .module(module_id) - .unwrap_or_else(|| panic!("module {:?} not found", module_id)); + .unwrap_or_else(|| panic!("module {module_id:?} not found")); module.module_groups.clone() }; @@ -95,7 +95,7 @@ pub fn patch_module_group_graph( for module_group_id in &previous_parent_groups { let current_module = module_graph .module(¤t_module_id) - .unwrap_or_else(|| panic!("module {:?} not found", current_module_id)); + .unwrap_or_else(|| panic!("module {current_module_id:?} not found")); if current_module.module_groups.contains(module_group_id) { continue; @@ -164,7 +164,7 @@ pub fn patch_module_group_graph( } else { let module = module_graph .module(module_id) - .unwrap_or_else(|| panic!("module {:?} not found", module_id)); + .unwrap_or_else(|| panic!("module {module_id:?} not found")); module.module_groups.clone() } }; diff --git a/crates/compiler/src/update/patch_module_group_graph/tests.rs b/crates/compiler/src/update/patch_module_group_graph/tests.rs index 023f1c746..99c78c2cb 100644 --- a/crates/compiler/src/update/patch_module_group_graph/tests.rs +++ b/crates/compiler/src/update/patch_module_group_graph/tests.rs @@ -184,9 +184,7 @@ fn test_patch_module_group_graph_3() { let mut module_group_graph = module_group_graph_from_entries( &module_graph .entries - .clone() - .into_iter() - .map(|(entry, _)| entry) + .clone().into_keys() .collect(), &mut module_graph, ); @@ -214,9 +212,7 @@ fn test_patch_module_group_graph_3() { let update_module_group_graph = module_group_graph_from_entries( &module_graph .entries - .clone() - .into_iter() - .map(|(entry, _)| entry) + .clone().into_keys() .collect(), &mut module_graph, ); @@ -297,9 +293,7 @@ fn test_patch_module_group_graph_css_modules() { let mut module_group_graph = module_group_graph_from_entries( &module_graph .entries - .clone() - .into_iter() - .map(|(entry, _)| entry) + .clone().into_keys() .collect(), &mut module_graph, ); @@ -323,9 +317,7 @@ fn test_patch_module_group_graph_css_modules() { let update_module_group_graph = module_group_graph_from_entries( &module_graph .entries - .clone() - .into_iter() - .map(|(entry, _)| entry) + .clone().into_keys() .collect(), &mut module_graph, ); diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots.rs b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots.rs index 2bcc4486c..fbc4ce9ac 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots.rs +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots.rs @@ -134,7 +134,7 @@ fn handle_enforce_resource_pots( get_resource_pot_id_for_enforce_resources(name, module_id, &module_graph) } else { let module = removed_modules.get(module_id).unwrap_or_else(|| { - panic!("can not find module {:?}", module_id); + panic!("can not find module {module_id:?}"); }); get_resource_pot_id_for_enforce_resources_by_removed_module(name, module) }; @@ -189,7 +189,7 @@ fn handle_enforce_resource_pots( // remove the resource pot if it's modules are empty for id in &affected_resource_pot_ids { let resource_pot = resource_pot_map.resource_pot_mut(id).unwrap_or_else(|| { - panic!("resource pot not found: {:?}", id); + panic!("resource pot not found: {id:?}"); }); if resource_pot.modules().is_empty() { @@ -250,8 +250,7 @@ fn diff_and_patch_resource_pot_map( .remove_resource_pot(resource_pot) .unwrap_or_else(|| { panic!( - "The resource pot {:?} should be in the resource pot map", - resource_pot + "The resource pot {resource_pot:?} should be in the resource pot map" ) }); diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs index 94edd937d..cc5da1e10 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_generate_and_diff_resource_pots.rs @@ -44,9 +44,7 @@ fn test_generate_and_diff_resource_pots() { let mut module_group_graph = module_group_graph_from_entries( &module_graph .entries - .clone() - .into_iter() - .map(|(entry, _)| entry) + .clone().into_keys() .collect(), &mut module_graph, ); @@ -103,7 +101,7 @@ fn test_generate_and_diff_resource_pots() { &context, ) .unwrap(); - println!("{:?}", resource_pot_ids); + println!("{resource_pot_ids:?}"); assert_eq!( resource_pot_ids, vec![String::from("test_custom(\"__farm_unknown\")")] @@ -248,9 +246,7 @@ fn test_generate_and_diff_resource_pots_one_module_changed() { let mut module_group_graph = module_group_graph_from_entries( &module_graph .entries - .clone() - .into_iter() - .map(|(entry, _)| entry) + .clone().into_keys() .collect(), &mut module_graph, ); diff --git a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_handle_enforce_resource_pots.rs b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_handle_enforce_resource_pots.rs index fe87bfc64..3def4f420 100644 --- a/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_handle_enforce_resource_pots.rs +++ b/crates/compiler/src/update/regenerate_resources/generate_and_diff_resource_pots/test_handle_enforce_resource_pots.rs @@ -45,9 +45,7 @@ fn test_handle_enforce_resource_pots() { let mut module_group_graph = module_group_graph_from_entries( &module_graph .entries - .clone() - .into_iter() - .map(|(entry, _)| entry) + .clone().into_keys() .collect(), &mut module_graph, ); @@ -173,9 +171,7 @@ fn test_handle_enforce_resource_pots_one_module_changed() { let mut module_group_graph = module_group_graph_from_entries( &module_graph .entries - .clone() - .into_iter() - .map(|(entry, _)| entry) + .clone().into_keys() .collect(), &mut module_graph, ); diff --git a/crates/compiler/src/update/regenerate_resources/mod.rs b/crates/compiler/src/update/regenerate_resources/mod.rs index da88366ed..4595e65ff 100644 --- a/crates/compiler/src/update/regenerate_resources/mod.rs +++ b/crates/compiler/src/update/regenerate_resources/mod.rs @@ -221,7 +221,7 @@ pub fn regenerate_resources_for_affected_module_groups( .plugin_driver .write_plugin_cache(context) .unwrap_or_else(|err| { - eprintln!("write plugin cache error: {:?}", err); + eprintln!("write plugin cache error: {err:?}"); }); write_cache(context.clone()); diff --git a/crates/compiler/tests/bundle.rs b/crates/compiler/tests/bundle.rs index 7cf5f5daa..5ec5b8149 100644 --- a/crates/compiler/tests/bundle.rs +++ b/crates/compiler/tests/bundle.rs @@ -19,7 +19,7 @@ fn test(file: String, crate_path: String) { let file_path_buf = PathBuf::from(file.clone()); let create_path_buf = PathBuf::from(crate_path); let cwd = file_path_buf.parent().unwrap(); - println!("testing test case: {:?}", cwd); + println!("testing test case: {cwd:?}"); let entry_name = "index".to_string(); @@ -110,7 +110,7 @@ fn test(file: String, crate_path: String) { if config_named.is_empty() { "".into() } else { - format!("{}.", config_named) + format!("{config_named}.") } )), ..Default::default() diff --git a/crates/compiler/tests/common/mod.rs b/crates/compiler/tests/common/mod.rs index daf09f75d..2c5c43cf2 100644 --- a/crates/compiler/tests/common/mod.rs +++ b/crates/compiler/tests/common/mod.rs @@ -225,8 +225,8 @@ pub fn get_compiler_result(compiler: &Compiler, config: &AssertCompilerResultCon String::from_utf8_lossy(&resource.bytes), ), _ => ( - format!("1{}", name), - format!("//{}:\n ", name), + format!("1{name}"), + format!("//{name}:\n "), String::from_utf8_lossy(&resource.bytes), ), }) @@ -236,7 +236,7 @@ pub fn get_compiler_result(compiler: &Compiler, config: &AssertCompilerResultCon let result_file_str = result .iter() - .map(|(_, name, content)| format!("{}{}", name, content)) + .map(|(_, name, content)| format!("{name}{content}")) .collect::>() .join("\n\n"); diff --git a/crates/compiler/tests/css.rs b/crates/compiler/tests/css.rs index c21556651..82b5b1f06 100644 --- a/crates/compiler/tests/css.rs +++ b/crates/compiler/tests/css.rs @@ -10,7 +10,7 @@ use crate::common::{assert_compiler_result, create_css_compiler}; fn css_modules() { fixture!("tests/fixtures/css/modules/**/*.ts", |file, crate_path| { let cwd = file.parent().unwrap(); - println!("cwd: {:?}", cwd); + println!("cwd: {cwd:?}"); let entry_name = "index".to_string(); diff --git a/crates/compiler/tests/external.rs b/crates/compiler/tests/external.rs index 538b5b7eb..ecb9a806a 100644 --- a/crates/compiler/tests/external.rs +++ b/crates/compiler/tests/external.rs @@ -10,7 +10,7 @@ fn test(file: String, crate_path: String) { let file_path_buf = PathBuf::from(file.clone()); let create_path_buf = PathBuf::from(crate_path); let cwd = file_path_buf.parent().unwrap(); - println!("testing test case: {:?}", cwd); + println!("testing test case: {cwd:?}"); let entry_name = "index".to_string(); let normolized_file = file.replace('\\', "/"); diff --git a/crates/compiler/tests/minify.rs b/crates/compiler/tests/minify.rs index 75b93f053..3d22e9ef3 100644 --- a/crates/compiler/tests/minify.rs +++ b/crates/compiler/tests/minify.rs @@ -12,7 +12,7 @@ fn minify_script_test() { "tests/fixtures/minify/script/**/index.ts", |file, crate_path| { let cwd = file.parent().unwrap(); - println!("testing minify: {:?}", cwd); + println!("testing minify: {cwd:?}"); let entry_name = "index".to_string(); let compiler = create_compiler( @@ -34,7 +34,7 @@ fn minify_css_test() { "tests/fixtures/minify/css/**/index.ts", |file, crate_path| { let cwd = file.parent().unwrap(); - println!("testing minify: {:?}", cwd); + println!("testing minify: {cwd:?}"); let entry_name = "index".to_string(); let compiler = create_compiler( @@ -56,7 +56,7 @@ fn minify_html_test() { "tests/fixtures/minify/html/**/index.html", |file, crate_path| { let cwd = file.parent().unwrap(); - println!("testing minify: {:?}", cwd); + println!("testing minify: {cwd:?}"); let entry_name = "index".to_string(); let compiler = create_compiler( diff --git a/crates/compiler/tests/partial_bundling.rs b/crates/compiler/tests/partial_bundling.rs index f65c1376e..e802296db 100644 --- a/crates/compiler/tests/partial_bundling.rs +++ b/crates/compiler/tests/partial_bundling.rs @@ -12,7 +12,7 @@ fn partial_bundling_test() { "tests/fixtures/partial_bundling/**/index.ts", |file, crate_path| { let cwd = file.parent().unwrap(); - println!("testing tree shake: {:?}", cwd); + println!("testing tree shake: {cwd:?}"); let entry_name = "index".to_string(); let compiler = create_compiler( diff --git a/crates/compiler/tests/runtime.rs b/crates/compiler/tests/runtime.rs index c6c0f4059..1e3011d14 100644 --- a/crates/compiler/tests/runtime.rs +++ b/crates/compiler/tests/runtime.rs @@ -19,7 +19,7 @@ fn test(file: String, crate_path: String) { let file_path_buf = PathBuf::from(file.clone()); let create_path_buf = PathBuf::from(crate_path); let cwd = file_path_buf.parent().unwrap(); - println!("testing test case: {:?}", cwd); + println!("testing test case: {cwd:?}"); let entry_name = "index".to_string(); diff --git a/crates/compiler/tests/script.rs b/crates/compiler/tests/script.rs index 3cca342fa..cdfc0ad95 100644 --- a/crates/compiler/tests/script.rs +++ b/crates/compiler/tests/script.rs @@ -11,7 +11,7 @@ fn script_test(file: String, crate_path: String) { let file_path_buf = PathBuf::from(file.clone()); let create_path_buf = PathBuf::from(crate_path); let cwd = file_path_buf.parent().unwrap(); - println!("testing test case: {:?}", cwd); + println!("testing test case: {cwd:?}"); let entry_name = "index".to_string(); diff --git a/crates/compiler/tests/tree_shake.rs b/crates/compiler/tests/tree_shake.rs index f6a9b4c67..296edfcbd 100644 --- a/crates/compiler/tests/tree_shake.rs +++ b/crates/compiler/tests/tree_shake.rs @@ -29,7 +29,7 @@ fn tree_shake_test() { "tests/fixtures/tree_shake/**/index.ts", |file, crate_path| { let cwd = file.parent().unwrap(); - println!("testing tree shake: {:?}", cwd); + println!("testing tree shake: {cwd:?}"); let entry_name = "index".to_string(); let compiler = create_compiler( @@ -52,7 +52,7 @@ fn tree_shake_development() { |file, crate_path| { let cwd = file.parent().unwrap(); let entry_name = "index".to_string(); - println!("testing tree shake: {:?}", cwd); + println!("testing tree shake: {cwd:?}"); let compiler = create_compiler_with_args(cwd.into(), crate_path, |mut config, plguin| { config.input = HashMap::from([(entry_name.clone(), "./index.ts".to_string())]); @@ -73,7 +73,7 @@ fn tree_shake_html_entry() { "tests/fixtures/tree_shake/html_entry/**/index.html", |file, crate_path| { let cwd = file.parent().unwrap(); - println!("testing tree shake: {:?}", cwd); + println!("testing tree shake: {cwd:?}"); let entry_name = "index".to_string(); let compiler = create_compiler( @@ -153,7 +153,7 @@ fn tree_shake_changed_ast() { "tests/fixtures/tree_shake/changed_ast/entry.ts", |file, crate_path| { let cwd = file.parent().unwrap(); - println!("testing tree shake: {:?}", cwd); + println!("testing tree shake: {cwd:?}"); let entry_name = "index".to_string(); let compiler = create_compiler_with_plugins( diff --git a/crates/compiler/tests/update.rs b/crates/compiler/tests/update.rs index 2eee3ea7d..ddfeaeb3c 100644 --- a/crates/compiler/tests/update.rs +++ b/crates/compiler/tests/update.rs @@ -81,7 +81,7 @@ fn asset_update_result_code( let immutable_code = &result.immutable_resources; let output = cwd.join(name.unwrap_or("").to_string() + ".output.js"); - let code = format!("{}\n{}", mutable_code, immutable_code); + let code = format!("{mutable_code}\n{immutable_code}"); if !output.exists() { std::fs::write(output, code).unwrap(); } else { @@ -356,7 +356,7 @@ fn update_lazy_compilation() { compiler.compile().unwrap(); let update_file = cwd.join("dep.ts").to_string_lossy().to_string(); - let update_module_id = format!("{}{}", update_file, DYNAMIC_VIRTUAL_SUFFIX); + let update_module_id = format!("{update_file}{DYNAMIC_VIRTUAL_SUFFIX}"); let result = compiler .update( vec![(update_module_id.clone(), UpdateType::Updated)], @@ -369,7 +369,7 @@ fn update_lazy_compilation() { assert_eq!(result.added_module_ids, vec!["dep.ts".into()]); assert_eq!( result.updated_module_ids, - vec![format!("dep.ts{}", DYNAMIC_VIRTUAL_SUFFIX).into()] + vec![format!("dep.ts{DYNAMIC_VIRTUAL_SUFFIX}").into()] ); assert_eq!(result.removed_module_ids.len(), 0); } @@ -393,7 +393,7 @@ fn update_lazy_compilation_node() { compiler.compile().unwrap(); let update_file = cwd.join("dep.ts").to_string_lossy().to_string(); - let update_module_id = format!("{}{}", update_file, DYNAMIC_VIRTUAL_SUFFIX); + let update_module_id = format!("{update_file}{DYNAMIC_VIRTUAL_SUFFIX}"); let result = compiler .update( vec![(update_module_id.clone(), UpdateType::Updated)], @@ -406,7 +406,7 @@ fn update_lazy_compilation_node() { assert_eq!(result.added_module_ids, vec!["dep.ts".into()]); assert_eq!( result.updated_module_ids, - vec![format!("dep.ts{}", DYNAMIC_VIRTUAL_SUFFIX).into()] + vec![format!("dep.ts{DYNAMIC_VIRTUAL_SUFFIX}").into()] ); assert_eq!(result.removed_module_ids.len(), 0); diff --git a/crates/core/src/cache/cache_store.rs b/crates/core/src/cache/cache_store.rs index 02da18c8e..d8d2e6634 100644 --- a/crates/core/src/cache/cache_store.rs +++ b/crates/core/src/cache/cache_store.rs @@ -9,7 +9,7 @@ use std::{ use crate::config::Mode; -const FARM_CACHE_VERSION: &str = "0.4.8"; +const FARM_CACHE_VERSION: &str = "0.4.9"; const FARM_CACHE_MANIFEST_FILE: &str = "farm-cache.json"; // TODO make CacheStore a trait and implement DiskCacheStore or RemoteCacheStore or more. diff --git a/crates/core/src/cache/module_cache/immutable_modules.rs b/crates/core/src/cache/module_cache/immutable_modules.rs index 616ed22b5..f4a1722f8 100644 --- a/crates/core/src/cache/module_cache/immutable_modules.rs +++ b/crates/core/src/cache/module_cache/immutable_modules.rs @@ -28,7 +28,7 @@ pub struct CachedPackage { impl CachedPackage { pub fn gen_key(name: &str, version: &str) -> String { - format!("{}@{}", name, version) + format!("{name}@{version}") } pub fn key(&self) -> String { diff --git a/crates/core/src/config/bool_or_obj.rs b/crates/core/src/config/bool_or_obj.rs index 054552747..57bccecd7 100644 --- a/crates/core/src/config/bool_or_obj.rs +++ b/crates/core/src/config/bool_or_obj.rs @@ -68,6 +68,6 @@ mod tests { let value = json!("value"); let value: BoolOrObj = serde_json::from_value(value).unwrap(); assert!(matches!(value, BoolOrObj::Obj(_))); - println!("{:?}", value); + println!("{value:?}"); } } diff --git a/crates/core/src/config/custom.rs b/crates/core/src/config/custom.rs index c1407a974..22ba5e1bb 100644 --- a/crates/core/src/config/custom.rs +++ b/crates/core/src/config/custom.rs @@ -29,7 +29,7 @@ pub fn get_config_external_record(config: &Config) -> ExternalConfig { } let external: HashMap = serde_json::from_str(val) - .unwrap_or_else(|_| panic!("failed parse record external {:?}", val)); + .unwrap_or_else(|_| panic!("failed parse record external {val:?}")); let mut external_config = ExternalConfig::new(); diff --git a/crates/core/src/config/external.rs b/crates/core/src/config/external.rs index 6996653e7..63c0c26a4 100644 --- a/crates/core/src/config/external.rs +++ b/crates/core/src/config/external.rs @@ -92,6 +92,6 @@ mod tests { ) .unwrap(); - println!("{:#?}", value); + println!("{value:#?}"); } } diff --git a/crates/core/src/config/persistent_cache.rs b/crates/core/src/config/persistent_cache.rs index 91bdf5b0f..8ef6f38ba 100644 --- a/crates/core/src/config/persistent_cache.rs +++ b/crates/core/src/config/persistent_cache.rs @@ -83,7 +83,7 @@ impl PersistentCacheConfig { .into_iter() .map(|k| { let v = cloned_obj.envs.get(k).unwrap(); - format!("{}={}", k, v) + format!("{k}={v}") }) .collect::>() .join("&"); diff --git a/crates/core/src/module/mod.rs b/crates/core/src/module/mod.rs index 37c646379..0f8272514 100644 --- a/crates/core/src/module/mod.rs +++ b/crates/core/src/module/mod.rs @@ -609,7 +609,7 @@ impl ToString for ModuleType { fn to_string(&self) -> String { match *self { Self::Custom(ref s) => s.to_string(), - _ => AsLowerCamelCase(format!("{:?}", self)).to_string(), + _ => AsLowerCamelCase(format!("{self:?}")).to_string(), } } } @@ -707,7 +707,7 @@ impl ModuleId { let (resolved_path, query) = p.split_once('?').unwrap_or((p, "")); if !query.is_empty() { - return (resolved_path.to_string(), format!("?{}", query)); + return (resolved_path.to_string(), format!("?{query}")); } (p.to_string(), query.to_string()) diff --git a/crates/core/src/module/module_graph.rs b/crates/core/src/module/module_graph.rs index 35ae68392..cfcc25ada 100644 --- a/crates/core/src/module/module_graph.rs +++ b/crates/core/src/module/module_graph.rs @@ -140,7 +140,7 @@ impl ModuleGraph { let i = self .id_index_map .get(module_id) - .unwrap_or_else(|| panic!("module_id {:?} should in the module graph", module_id)); + .unwrap_or_else(|| panic!("module_id {module_id:?} should in the module graph")); let mut edges = self .g .neighbors_directed(*i, EdgeDirection::Outgoing) @@ -162,7 +162,7 @@ impl ModuleGraph { let i = self .id_index_map .get(module_id) - .unwrap_or_else(|| panic!("module_id {:?} should in the module graph", module_id)); + .unwrap_or_else(|| panic!("module_id {module_id:?} should in the module graph")); let mut edges = self .g .neighbors_directed(*i, EdgeDirection::Outgoing) @@ -288,7 +288,7 @@ impl ModuleGraph { let index = self .id_index_map .remove(module_id) - .unwrap_or_else(|| panic!("module_id {:?} should in the module graph", module_id)); + .unwrap_or_else(|| panic!("module_id {module_id:?} should in the module graph")); if !module_id.query_string().is_empty() { if let Some(ids) = self @@ -404,11 +404,11 @@ impl ModuleGraph { let from = self .id_index_map .get(from) - .unwrap_or_else(|| panic!("module_id {:?} should in the module graph", from)); + .unwrap_or_else(|| panic!("module_id {from:?} should in the module graph")); let to = self .id_index_map .get(to) - .unwrap_or_else(|| panic!("module_id {:?} should in the module graph", to)); + .unwrap_or_else(|| panic!("module_id {to:?} should in the module graph")); if let Some(edge_index) = self.g.find_edge(*from, *to) { self.g.edge_weight(edge_index) @@ -432,7 +432,7 @@ impl ModuleGraph { let i = self .id_index_map .get(module_id) - .unwrap_or_else(|| panic!("module_id {:?} should in the module graph", module_id)); + .unwrap_or_else(|| panic!("module_id {module_id:?} should in the module graph")); let mut edges = self .g .neighbors_directed(*i, EdgeDirection::Outgoing) @@ -481,7 +481,7 @@ impl ModuleGraph { let i = self .id_index_map .get(module_id) - .unwrap_or_else(|| panic!("module_id {:?} should in the module graph", module_id)); + .unwrap_or_else(|| panic!("module_id {module_id:?} should in the module graph")); let mut edges = self .g .neighbors_directed(*i, EdgeDirection::Incoming) @@ -635,11 +635,11 @@ impl ModuleGraph { let i = self .id_index_map .remove(to) - .unwrap_or_else(|| panic!("module_id {:?} should in the module graph", to)); + .unwrap_or_else(|| panic!("module_id {to:?} should in the module graph")); let edge_index = self .g .find_edge(*self.id_index_map.get(from).unwrap(), i) - .unwrap_or_else(|| panic!("edge {:?} -> {:?} should in the module graph", from, to)); + .unwrap_or_else(|| panic!("edge {from:?} -> {to:?} should in the module graph")); let edge = self.g.remove_edge(edge_index).unwrap(); let module = self.g.remove_node(i).unwrap(); @@ -715,7 +715,7 @@ mod tests { &from.into(), &to.into(), ModuleGraphEdgeDataItem { - source: format!("./{}", to), + source: format!("./{to}"), kind: ResolveKind::Import, order, }, @@ -729,7 +729,7 @@ mod tests { &from.into(), &to.into(), ModuleGraphEdgeDataItem { - source: format!("./{}", to), + source: format!("./{to}"), kind: ResolveKind::DynamicImport, order, }, diff --git a/crates/core/src/module/module_group.rs b/crates/core/src/module/module_group.rs index 03738d036..fb162a2f3 100644 --- a/crates/core/src/module/module_group.rs +++ b/crates/core/src/module/module_group.rs @@ -36,7 +36,7 @@ impl ModuleGroupGraph { let module_group_id = module_group.id.clone(); if self.has(&module_group_id) { - panic!("module group already exists: {:?}", module_group_id); + panic!("module group already exists: {module_group_id:?}"); } let node_index = self.g.add_node(module_group); diff --git a/crates/core/src/resource/mod.rs b/crates/core/src/resource/mod.rs index d50719db6..1f1f588dd 100644 --- a/crates/core/src/resource/mod.rs +++ b/crates/core/src/resource/mod.rs @@ -28,7 +28,7 @@ impl ToString for ResourceType { match *self { Self::Custom(ref s) => s.to_string(), Self::Asset(ref s) => s.to_string(), - _ => AsLowerCamelCase(format!("{:?}", self)).to_string(), + _ => AsLowerCamelCase(format!("{self:?}")).to_string(), } } } diff --git a/crates/core/src/resource/resource_pot.rs b/crates/core/src/resource/resource_pot.rs index 918ff94d2..cad63812d 100644 --- a/crates/core/src/resource/resource_pot.rs +++ b/crates/core/src/resource/resource_pot.rs @@ -276,7 +276,7 @@ impl From for ResourcePotType { impl ToString for ResourcePotType { fn to_string(&self) -> String { - format!("{:?}", self).to_lowercase() + format!("{self:?}").to_lowercase() } } diff --git a/crates/create-farm-rs/src/lib.rs b/crates/create-farm-rs/src/lib.rs index 9df95a9e9..6a21aa707 100644 --- a/crates/create-farm-rs/src/lib.rs +++ b/crates/create-farm-rs/src/lib.rs @@ -174,14 +174,14 @@ where handle_brand_text(&format!( " cd {} \n", if project_name.contains(' ') { - format!("\"{}\"", project_name) + format!("\"{project_name}\"") } else { project_name.to_string() } )); } if let Some(cmd) = pkg_manager.install_cmd() { - handle_brand_text(&format!(" {} \n", cmd)); + handle_brand_text(&format!(" {cmd} \n")); } handle_brand_text(&format!(" {} \n", get_run_cmd(&pkg_manager, &template))); diff --git a/crates/create-farm-rs/src/template.rs b/crates/create-farm-rs/src/template.rs index fef841daf..720ed4260 100644 --- a/crates/create-farm-rs/src/template.rs +++ b/crates/create-farm-rs/src/template.rs @@ -176,9 +176,9 @@ impl Display for Template { Template::Preact => write!(f, "preact"), Template::Nestjs => write!(f, "nestjs"), Template::Tauri(None) => write!(f, "tauri"), - Template::Tauri(Some(sub_template)) => write!(f, "tauri-{}", sub_template), + Template::Tauri(Some(sub_template)) => write!(f, "tauri-{sub_template}"), Template::Electron(None) => write!(f, "electron"), - Template::Electron(Some(sub_template)) => write!(f, "electron-{}", sub_template), + Template::Electron(Some(sub_template)) => write!(f, "electron-{sub_template}"), } } } diff --git a/crates/create-farm-rs/src/utils/colors.rs b/crates/create-farm-rs/src/utils/colors.rs index 36312253f..88e690dd4 100644 --- a/crates/create-farm-rs/src/utils/colors.rs +++ b/crates/create-farm-rs/src/utils/colors.rs @@ -51,7 +51,7 @@ pub fn create_formatter<'a>(open: &'a str, close: &'a str, replace: Option<&'a s result.push_str(close); result } else { - format!("{}{}{}", open, string, close) + format!("{open}{string}{close}") } } } @@ -68,13 +68,13 @@ pub fn replace_close(string: &str, close: &str, replace: &str, index: usize) -> replace_close(&end[next_index..], close, replace, next_index) ) } else { - format!("{}{}", start, replace) + format!("{start}{replace}") } } pub fn reset(s: &str) -> String { if is_color_enabled() { - format!("\x1b[0m{}", s) + format!("\x1b[0m{s}") } else { s.to_string() } @@ -355,12 +355,12 @@ pub fn handle_brand_text(text: &str) { BRAND_GRADIENT_COLORS2, ], ); - println!("{}", gradient_string); + println!("{gradient_string}"); } pub fn brand_text(text: &str) -> String { let gradient_string = gradient_string( - &format!("\n{} \n", text), + &format!("\n{text} \n"), &[ BRAND_GRADIENT_COLORS, interpolate_color(&BRAND_GRADIENT_COLORS, &BRAND_GRADIENT_COLORS2, 0.2), diff --git a/crates/node/src/lib.rs b/crates/node/src/lib.rs index 193a1796e..980a7e8cf 100644 --- a/crates/node/src/lib.rs +++ b/crates/node/src/lib.rs @@ -139,7 +139,7 @@ impl JsCompiler { for js_plugin_object in js_plugins { let js_plugin = Arc::new( JsPluginAdapter::new(&env, js_plugin_object) - .unwrap_or_else(|e| panic!("load js plugin error: {:?}", e)), + .unwrap_or_else(|e| panic!("load js plugin error: {e:?}")), ) as _; plugins_adapters.push(js_plugin); } @@ -150,7 +150,7 @@ impl JsCompiler { let rust_plugin = Arc::new( RustPluginAdapter::new(&rust_plugin_path, &config, rust_plugin_options) - .unwrap_or_else(|e| panic!("load rust plugin error: {:?}", e)), + .unwrap_or_else(|e| panic!("load rust plugin error: {e:?}")), ) as _; plugins_adapters.push(rust_plugin); } @@ -158,7 +158,7 @@ impl JsCompiler { Ok(Self { compiler: Arc::new( Compiler::new(config, plugins_adapters) - .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{}", e)))?, + .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{e}")))?, ), }) } @@ -172,7 +172,7 @@ impl JsCompiler { self.compiler.thread_pool.spawn(move || { match compiler .trace_dependencies() - .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{}", e))) + .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{e}"))) { Ok(deps) => { promise.resolve(Box::new(|_| Ok(deps))); @@ -195,7 +195,7 @@ impl JsCompiler { self.compiler.thread_pool.spawn(move || { match compiler .trace_module_graph() - .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{}", e))) + .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{e}"))) { Ok(graph) => { promise.resolve(Box::new(|_| Ok(graph.into()))); @@ -219,7 +219,7 @@ impl JsCompiler { self.compiler.thread_pool.spawn(move || { match compiler .compile() - .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{}", e))) + .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{e}"))) { Ok(_) => { promise.resolve(Box::new(|e| e.get_undefined())); @@ -253,7 +253,7 @@ impl JsCompiler { self .compiler .compile() - .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{}", e)))?; + .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{e}")))?; Ok(()) } @@ -289,7 +289,7 @@ impl JsCompiler { sync, generate_update_resource, ) - .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{}", e))) + .map_err(|e| napi::Error::new(Status::GenericFailure, format!("{e}"))) { Ok(res) => { let js_update_result = JsUpdateResult { diff --git a/crates/node/src/plugin_adapters/js_plugin_adapter/context.rs b/crates/node/src/plugin_adapters/js_plugin_adapter/context.rs index 030867a0b..57899d3bf 100644 --- a/crates/node/src/plugin_adapters/js_plugin_adapter/context.rs +++ b/crates/node/src/plugin_adapters/js_plugin_adapter/context.rs @@ -161,13 +161,13 @@ unsafe extern "C" fn resolve(env: napi_env, info: napi_callback_info) -> napi_va let resolved = ctx .plugin_driver .resolve(¶m, &ctx, &hook_context) - .map_err(|e| Error::new(Status::GenericFailure, format!("{}", e))); + .map_err(|e| Error::new(Status::GenericFailure, format!("{e}"))); match resolved { Ok(resolved) => promise.resolve(Box::new(move |e| e.to_js_value(&resolved))), Err(err) => promise.reject(Error::new( Status::GenericFailure, - format!("can not resolve {:?}: {:?}", param, err), + format!("can not resolve {param:?}: {err:?}"), )), } }); diff --git a/crates/node/src/plugin_adapters/js_plugin_adapter/mod.rs b/crates/node/src/plugin_adapters/js_plugin_adapter/mod.rs index ed92e1407..9dc092bd4 100644 --- a/crates/node/src/plugin_adapters/js_plugin_adapter/mod.rs +++ b/crates/node/src/plugin_adapters/js_plugin_adapter/mod.rs @@ -399,8 +399,7 @@ impl Plugin for JsPluginAdapter { pub fn get_named_property(env: &Env, obj: &JsObject, field: &str) -> Result { if obj.has_named_property(field).map_err(|e| { CompilationError::NAPIError(format!( - "Get field {} of config object failed. {:?}", - field, e + "Get field {field} of config object failed. {e:?}" )) })? { unsafe { @@ -410,20 +409,18 @@ pub fn get_named_property(env: &Env, obj: &JsObject, field: &s .get_named_property::(field) .map_err(|e| { CompilationError::NAPIError(format!( - "Get field {} of config object failed. {:?}", - field, e + "Get field {field} of config object failed. {e:?}" )) })? .raw(), ) .map_err(|e| { - CompilationError::NAPIError(format!("Transform config field {} failed. {:?}", field, e)) + CompilationError::NAPIError(format!("Transform config field {field} failed. {e:?}")) }) } } else { Err(CompilationError::NAPIError(format!( - "Invalid Config: the config object does not have field {}", - field + "Invalid Config: the config object does not have field {field}" ))) } } diff --git a/crates/node/src/plugin_adapters/js_plugin_adapter/thread_safe_js_plugin_hook.rs b/crates/node/src/plugin_adapters/js_plugin_adapter/thread_safe_js_plugin_hook.rs index 29746bf52..ad8d850b1 100644 --- a/crates/node/src/plugin_adapters/js_plugin_adapter/thread_safe_js_plugin_hook.rs +++ b/crates/node/src/plugin_adapters/js_plugin_adapter/thread_safe_js_plugin_hook.rs @@ -174,8 +174,7 @@ unsafe extern "C" fn call_js_cb { sender .send(Err(CompilationError::NAPIError(format!( - "Invalid hook return, except object. {:?}", - e + "Invalid hook return, except object. {e:?}" )))) .unwrap(); return; @@ -198,8 +197,7 @@ unsafe extern "C" fn call_js_cb( .map(|r| Some(r)) .map_err(|e| { CompilationError::NAPIError(format!( - "Invalid hook return, can not transform it to rust struct. {:?}", - e + "Invalid hook return, can not transform it to rust struct. {e:?}" )) }); @@ -418,7 +415,7 @@ unsafe extern "C" fn catch_cb( .get_named_property::("stack") .unwrap(); - format!("{}\n{}", message, stack) + format!("{message}\n{stack}") } else if is_string { // get the string value rejected_value diff --git a/crates/node/src/plugin_adapters/rust_plugin_adapter/mod.rs b/crates/node/src/plugin_adapters/rust_plugin_adapter/mod.rs index dd13617bf..d0c603902 100644 --- a/crates/node/src/plugin_adapters/rust_plugin_adapter/mod.rs +++ b/crates/node/src/plugin_adapters/rust_plugin_adapter/mod.rs @@ -31,7 +31,7 @@ impl RustPluginAdapter { pub fn new(plugin_path: &String, config: &Config, options: String) -> Result { let (plugin, _lib) = unsafe { load_rust_plugin(plugin_path, config, options).map_err(|e| { - CompilationError::GenericError(format!("Load rust plugin {} failed. {:?}", plugin_path, e)) + CompilationError::GenericError(format!("Load rust plugin {plugin_path} failed. {e:?}")) })? }; diff --git a/crates/plugin_bundle/src/lib.rs b/crates/plugin_bundle/src/lib.rs index f2247e07a..dccc11ffe 100644 --- a/crates/plugin_bundle/src/lib.rs +++ b/crates/plugin_bundle/src/lib.rs @@ -3,7 +3,6 @@ use std::{collections::HashMap, sync::Arc}; use farmfe_core::{ - config::TargetEnv, enhanced_magic_string::bundle::Bundle, parking_lot::Mutex, plugin::Plugin, diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_analyzer.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_analyzer.rs index e8903c921..66b3246fc 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_analyzer.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/bundle/bundle_analyzer.rs @@ -782,7 +782,7 @@ impl<'a> BundleAnalyzer<'a> { let local_var = module_analyzer_manager .module_global_uniq_name .namespace_name(source) - .to_result(format!("not found module {:?} namespace named", source))?; + .to_result(format!("not found module {source:?} namespace named"))?; let local_name = self.bundle_variable.borrow().render_name(local_var); @@ -1006,7 +1006,7 @@ impl<'a> BundleAnalyzer<'a> { let module = self .module_graph .module(module_id) - .unwrap_or_else(|| panic!("Module not found: {:?}", module_id)); + .unwrap_or_else(|| panic!("Module not found: {module_id:?}")); let module_analyzer = module_analyzer_manager.module_analyzer_mut_unchecked(module_id); let comments: SingleThreadedComments = module.meta.as_script().comments.clone().into(); @@ -1046,8 +1046,7 @@ impl<'a> BundleAnalyzer<'a> { let code = String::from_utf8(code_bytes).map_err(|err| { CompilationError::GenericError(format!( - "failed to convert code bytes to string, origin error: {}", - err + "failed to convert code bytes to string, origin error: {err}" )) })?; diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/common.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/common.rs index 6e1f85c2d..923bbb212 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/common.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/common.rs @@ -50,7 +50,7 @@ pub fn parse_module_item(string: &str) -> Result { .parse_module_item() .map_err(|msg| CompilationError::ParseError { resolved_path: "unknown temp parser".to_string(), - msg: format!("failed parse content, cause: {:#?}", msg), + msg: format!("failed parse content, cause: {msg:#?}"), }) } diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/mod.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/mod.rs index 040934a26..8b28ae0ea 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/mod.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/mod.rs @@ -193,8 +193,7 @@ impl<'a> SharedBundle<'a> { .map(Ok) .unwrap_or_else(|| { Err(CompilationError::GenericError(format!( - "get resource pot {:?} failed", - resource_pot_id + "get resource pot {resource_pot_id:?} failed" ))) })?; diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/dynamic_import.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/dynamic_import.rs index 64f53f394..f6fc37768 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/targets/dynamic_import.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/targets/dynamic_import.rs @@ -11,7 +11,7 @@ const FARM_BUNDLE_REFERENCE_SLOT_PREFIX: &str = "__FARM_BUNDLE_REFERENCE_SLOT__: // TODO: replace bundle reference slot fn with_bundle_reference_slot_name(bundle_id: &String) -> String { - format!("{}{}", FARM_BUNDLE_REFERENCE_SLOT_PREFIX, bundle_id) + format!("{FARM_BUNDLE_REFERENCE_SLOT_PREFIX}{bundle_id}") } /// diff --git a/crates/plugin_bundle/src/resource_pot_to_bundle/uniq_name.rs b/crates/plugin_bundle/src/resource_pot_to_bundle/uniq_name.rs index aa8bade74..c30b80251 100644 --- a/crates/plugin_bundle/src/resource_pot_to_bundle/uniq_name.rs +++ b/crates/plugin_bundle/src/resource_pot_to_bundle/uniq_name.rs @@ -53,7 +53,7 @@ impl UniqName { if let Some(mut count) = self.name_count_map.get_mut(&base_uniq_name).cloned() { loop { - uniq_name = format!("{}${}", base_uniq_name, count); + uniq_name = format!("{base_uniq_name}${count}"); if !self.name_count_map.contains_key(&uniq_name) { break; diff --git a/crates/plugin_css/src/lib.rs b/crates/plugin_css/src/lib.rs index 762ce97d4..7bbdd22c4 100644 --- a/crates/plugin_css/src/lib.rs +++ b/crates/plugin_css/src/lib.rs @@ -149,7 +149,7 @@ impl Plugin for FarmPluginCssResolve { }; // try relative path first if !source.starts_with('.') { - if let Some(res) = resolve_css(format!("./{}", source)) { + if let Some(res) = resolve_css(format!("./{source}")) { return Ok(Some(res)); } } @@ -637,7 +637,7 @@ impl Plugin for FarmPluginCss { }), ); bundle.add_source(magic_module, None).map_err(|e| { - CompilationError::GenericError(format!("failed to add source to bundle: {:?}", e)) + CompilationError::GenericError(format!("failed to add source to bundle: {e:?}")) })?; } @@ -652,7 +652,7 @@ impl Plugin for FarmPluginCss { ..Default::default() }) .map_err(|e| { - CompilationError::GenericError(format!("failed to generate source map: {:?}", e)) + CompilationError::GenericError(format!("failed to generate source map: {e:?}")) })?, ) .map(|v| { @@ -799,7 +799,7 @@ fn transform_css_module_indent_name( context: HashMap, ) -> String { context.iter().fold(indent_name, |acc, (key, value)| { - acc.replace(&format!("[{}]", key), value) + acc.replace(&format!("[{key}]"), value) }) } diff --git a/crates/plugin_css/src/source_replacer.rs b/crates/plugin_css/src/source_replacer.rs index c44c091e5..721d28bcb 100644 --- a/crates/plugin_css/src/source_replacer.rs +++ b/crates/plugin_css/src/source_replacer.rs @@ -1,7 +1,12 @@ use std::collections::HashMap; use farmfe_core::{ - config::AliasItem, module::{module_graph::ModuleGraph, ModuleId}, plugin::ResolveKind, resource::{Resource, ResourceOrigin}, swc_common::DUMMY_SP, swc_css_ast::{AtRulePrelude, ImportHref, Rule, Str, Stylesheet, Url, UrlValue}, swc_ecma_ast::Key + config::AliasItem, + module::{module_graph::ModuleGraph, ModuleId}, + plugin::ResolveKind, + resource::{Resource, ResourceOrigin}, + swc_common::DUMMY_SP, + swc_css_ast::{AtRulePrelude, ImportHref, Rule, Str, Stylesheet, Url, UrlValue}, }; use farmfe_toolkit::{ resolve::path_start_with_alias::is_start_with_alias, diff --git a/crates/plugin_css/tests/analyze_deps.rs b/crates/plugin_css/tests/analyze_deps.rs index 734e9d59b..3acb11f47 100644 --- a/crates/plugin_css/tests/analyze_deps.rs +++ b/crates/plugin_css/tests/analyze_deps.rs @@ -1,7 +1,7 @@ use std::{collections::HashMap, sync::Arc}; use farmfe_core::{ - config::{Config, ResolveConfig}, + config::{AliasItem, Config, ResolveConfig, StringOrRegex}, context::CompilationContext, module::{ModuleId, ModuleType}, plugin::{ @@ -17,10 +17,16 @@ fn analyze_deps() { fixture!("tests/fixtures/analyze_deps/basic.css", |file, cwd| { let config = Config { resolve: Box::new(ResolveConfig { - alias: HashMap::from([ - ("/@".to_string(), cwd.to_string_lossy().to_string()), - ("@".to_string(), cwd.to_string_lossy().to_string()), - ]), + alias: vec![ + AliasItem::Complex { + find: StringOrRegex::String("/@".to_string()), + replacement: cwd.to_string_lossy().to_string(), + }, + AliasItem::Complex { + find: StringOrRegex::String("@".to_string()), + replacement: cwd.to_string_lossy().to_string(), + }, + ], ..Default::default() }), ..Default::default() diff --git a/crates/plugin_css/tests/fixtures/analyze_deps/basic.css b/crates/plugin_css/tests/fixtures/analyze_deps/basic.css index a5adbe0f2..ebcc18308 100644 --- a/crates/plugin_css/tests/fixtures/analyze_deps/basic.css +++ b/crates/plugin_css/tests/fixtures/analyze_deps/basic.css @@ -19,7 +19,7 @@ div { p { background: url('@/img/logo.png'); - top: -8px/2 + 1; + /* top: -8px/2 + 1; */ } .home {filter: progid:DXImageTransform.Microsoft.Alpha(opacity=20)} diff --git a/crates/plugin_html/src/deps_analyzer.rs b/crates/plugin_html/src/deps_analyzer.rs index 1d476c850..91e970274 100644 --- a/crates/plugin_html/src/deps_analyzer.rs +++ b/crates/plugin_html/src/deps_analyzer.rs @@ -43,7 +43,7 @@ impl DepsAnalyzer { fn generate_virtual_id(&mut self, code: String, module_type: ModuleType) -> String { let id = self.html_id.to_string(); let size = self.inline_deps_map.len(); - let virtual_id = format!("{}{}_{}", HTML_INLINE_ID_PREFIX, id, size); + let virtual_id = format!("{HTML_INLINE_ID_PREFIX}{id}_{size}"); self.inline_deps_map.insert( virtual_id.clone(), diff --git a/crates/plugin_html/src/lib.rs b/crates/plugin_html/src/lib.rs index d7daa71e0..fec41181b 100644 --- a/crates/plugin_html/src/lib.rs +++ b/crates/plugin_html/src/lib.rs @@ -164,13 +164,12 @@ impl Plugin for FarmPluginHtml { ) .map_err(|e| CompilationError::TransformError { resolved_path: param.resolved_path.to_string(), - msg: format!("Load base html({}) fail. Error: {:?}", base, e), + msg: format!("Load base html({base}) fail. Error: {e:?}"), })? .ok_or(CompilationError::TransformError { resolved_path: param.resolved_path.to_string(), msg: format!( - "Load base html({}) fail: Base html file does not exist", - base + "Load base html({base}) fail: Base html file does not exist" ), })?; diff --git a/crates/plugin_html/src/resources_injector.rs b/crates/plugin_html/src/resources_injector.rs index 36341e9b3..1b6f7f1f8 100644 --- a/crates/plugin_html/src/resources_injector.rs +++ b/crates/plugin_html/src/resources_injector.rs @@ -91,7 +91,7 @@ impl<'a> ResourcesInjector<'a> { &self.already_injected_resources, ); - let script_element = create_element("script", None, vec![("src", &format!("/{}", name))]); + let script_element = create_element("script", None, vec![("src", &format!("/{name}"))]); element.children.push(Child::Element(script_element)); if let Some(resource) = resource { @@ -114,7 +114,7 @@ impl<'a> ResourcesInjector<'a> { let initial_resources_code = initial_resources .into_iter() - .map(|path| format!("'{}'", path)) + .map(|path| format!("'{path}'")) .collect::>() .join(","); @@ -152,7 +152,7 @@ impl<'a> ResourcesInjector<'a> { element.children.push(Child::Element(create_element( "script", None, - vec![("src", &format!("/{}", name))], + vec![("src", &format!("/{name}"))], ))); if let Some(resource) = resource { @@ -242,7 +242,7 @@ impl<'a> ResourcesInjector<'a> { element.children.push(Child::Element(create_element( "script", None, - vec![("src", &format!("/{}", name))], + vec![("src", &format!("/{name}"))], ))); if let Some(resource) = resource { diff --git a/crates/plugin_json/src/lib.rs b/crates/plugin_json/src/lib.rs index 403e222e6..a80384946 100644 --- a/crates/plugin_json/src/lib.rs +++ b/crates/plugin_json/src/lib.rs @@ -52,7 +52,7 @@ impl Plugin for FarmPluginJson { if matches!(param.module_type, ModuleType::Custom(ref suffix) if suffix == "json") { // if json value can not be parsed, means it's handled by other plugins if let Ok(json) = serde_json::from_str::(¶m.content) { - let js = format!("module.exports = {}", json); + let js = format!("module.exports = {json}"); return Ok(Some(farmfe_core::plugin::PluginTransformHookResult { content: js, diff --git a/crates/plugin_lazy_compilation/src/lib.rs b/crates/plugin_lazy_compilation/src/lib.rs index b0389ad24..09652d51d 100644 --- a/crates/plugin_lazy_compilation/src/lib.rs +++ b/crates/plugin_lazy_compilation/src/lib.rs @@ -172,7 +172,7 @@ impl Plugin for FarmPluginLazyCompilation { ) .replace( "'FARM_MODULE_SYSTEM'", - &format!("{}.{}", farm_global_this, FARM_MODULE_SYSTEM), + &format!("{farm_global_this}.{FARM_MODULE_SYSTEM}"), ); Ok(Some(farmfe_core::plugin::PluginLoadHookResult { @@ -190,11 +190,10 @@ impl Plugin for FarmPluginLazyCompilation { let relative_source = relative(&dir, &resolved_path); let content = format!( r#" - import _default_import from "./{0}"; + import _default_import from "./{relative_source}"; export default _default_import; - export * from "./{0}"; - "#, - relative_source + export * from "./{relative_source}"; + "# ); Ok(Some(PluginLoadHookResult { content, diff --git a/crates/plugin_minify/src/exports_minifier.rs b/crates/plugin_minify/src/exports_minifier.rs index 087588b84..92f8ea8dd 100644 --- a/crates/plugin_minify/src/exports_minifier.rs +++ b/crates/plugin_minify/src/exports_minifier.rs @@ -211,7 +211,7 @@ export { long10 } from './dep2'; codegen_module(&mut ast, EsVersion::latest(), cm, None, false, None).unwrap(); let code = String::from_utf8(code_bytes).unwrap(); - println!("{}", code); + println!("{code}"); assert_eq!( code, diff --git a/crates/plugin_minify/src/imports_minifier.rs b/crates/plugin_minify/src/imports_minifier.rs index 1204b5b0e..8467cb48a 100644 --- a/crates/plugin_minify/src/imports_minifier.rs +++ b/crates/plugin_minify/src/imports_minifier.rs @@ -71,14 +71,14 @@ impl<'a> ImportsMinifier<'a> { let mut used_ident = if *count == 0 { ident.to_string() } else { - format!("{}{}", ident, count) + format!("{ident}{count}") }; let mut count = *count; while self.imported_ident_count_map.contains_key(&used_ident) { count += 1; - used_ident = format!("{}{}", ident, count); + used_ident = format!("{ident}{count}"); } self.inc_imported_ident_count(used_ident.clone()); @@ -95,14 +95,14 @@ impl<'a> ImportsMinifier<'a> { let mut used_ident = if *count == 0 { ident.to_string() } else { - format!("{}{}", ident, count) + format!("{ident}{count}") }; let mut count = *count; while self.exported_ident_count_map.contains_key(&used_ident) { count += 1; - used_ident = format!("{}{}", ident, count); + used_ident = format!("{ident}{count}"); } self.inc_exported_ident_count(used_ident.clone()); @@ -717,7 +717,7 @@ export { hello1, hello2, default as world1 } from './dep'; codegen_module(&mut ast, EsVersion::latest(), cm, None, false, None).unwrap(); let code = String::from_utf8(code_bytes).unwrap(); - println!("{}", code); + println!("{code}"); assert_eq!( code, diff --git a/crates/plugin_partial_bundling/src/generate_module_pots.rs b/crates/plugin_partial_bundling/src/generate_module_pots.rs index e68ea5c99..b17b2609a 100644 --- a/crates/plugin_partial_bundling/src/generate_module_pots.rs +++ b/crates/plugin_partial_bundling/src/generate_module_pots.rs @@ -54,7 +54,7 @@ pub fn generate_module_pots( let page_size = modules.len() / new_module_pot_numbers; for i in 0..new_module_pot_numbers { - let new_module_pot_name = format!("{}-{}", module_pot_name, i); + let new_module_pot_name = format!("{module_pot_name}-{i}"); let new_module_pot_id = ModulePot::gen_id(&new_module_pot_name, ty.clone(), immutable); let new_module_pot = module_pot_map diff --git a/crates/plugin_partial_bundling/src/merge_module_pots.rs b/crates/plugin_partial_bundling/src/merge_module_pots.rs index d4ed1d211..f2638b2c7 100644 --- a/crates/plugin_partial_bundling/src/merge_module_pots.rs +++ b/crates/plugin_partial_bundling/src/merge_module_pots.rs @@ -353,7 +353,7 @@ fn handle_enforce_target_min_size( let final_resource_pot = resource_pot_map .get(final_resource_pot_id) - .unwrap_or_else(|| panic!("resource pot {:?} does not exist", final_resource_pot_id)); + .unwrap_or_else(|| panic!("resource pot {final_resource_pot_id:?} does not exist")); ( final_resource_pot.resource_pot_type.clone(), final_resource_pot.immutable, diff --git a/crates/plugin_resolve/src/resolver.rs b/crates/plugin_resolve/src/resolver.rs index 52e5a7b03..d993c3fec 100644 --- a/crates/plugin_resolve/src/resolver.rs +++ b/crates/plugin_resolve/src/resolver.rs @@ -391,7 +391,7 @@ impl Resolver { } else { let append_extension = |file: &PathBuf, ext: &str| { let file_name = file.file_name().unwrap().to_string_lossy().to_string(); - file.with_file_name(format!("{}.{}", file_name, ext)) + file.with_file_name(format!("{file_name}.{ext}")) }; let extensions = if let Some(ext) = &options.dynamic_extensions { ext @@ -805,7 +805,7 @@ impl Resolver { if let Some(entry_point) = entry_point { let dir = package_json_info.dir(); let entry_point = if !entry_point.starts_with("./") && !entry_point.starts_with("../") { - format!("./{}", entry_point) + format!("./{entry_point}") } else { entry_point }; diff --git a/crates/plugin_resolve/src/resolver/browser.rs b/crates/plugin_resolve/src/resolver/browser.rs index fc959f02c..fac40fd50 100644 --- a/crates/plugin_resolve/src/resolver/browser.rs +++ b/crates/plugin_resolve/src/resolver/browser.rs @@ -40,8 +40,8 @@ pub fn try_browser_map( if let Some(Value::Object(obj)) = browser_field { for (key, value) in obj { if key == sub_path - || key == format!("{}.js", sub_path) - || key == format!("{}/index.js", sub_path) + || key == format!("{sub_path}.js") + || key == format!("{sub_path}/index.js") { match value { Value::String(str) => return Some(BrowserMapResult::Str(str.clone())), diff --git a/crates/plugin_resolve/src/resolver/exports.rs b/crates/plugin_resolve/src/resolver/exports.rs index e7cd1b7f7..0d5277e87 100644 --- a/crates/plugin_resolve/src/resolver/exports.rs +++ b/crates/plugin_resolve/src/resolver/exports.rs @@ -6,7 +6,7 @@ use std::{ use farmfe_core::{ common::PackageJsonInfo, - config::{Mode, TargetEnv}, + config::{Mode}, context::CompilationContext, farm_profile_function, plugin::ResolveKind, @@ -126,8 +126,7 @@ fn exports( Some(n) => n, None => { eprintln!( - "Missing \"name\" field in package.json {:?}", - package_json_info + "Missing \"name\" field in package.json {package_json_info:?}" ); return None; } @@ -169,8 +168,7 @@ fn imports( Some(n) => n, None => { eprintln!( - "Missing \"name\" field in package.json {:?}", - package_json_info + "Missing \"name\" field in package.json {package_json_info:?}" ); return None; } @@ -270,15 +268,14 @@ fn throws(name: &str, entry: &str, condition: Option) { let message = match condition { Some(cond) if cond != 0 => { format!( - "No known conditions for \"{}\" specifier in \"{}\" package", - entry, name + "No known conditions for \"{entry}\" specifier in \"{name}\" package" ) } _ => { - format!("Missing \"{}\" specifier in \"{}\" package", entry, name) + format!("Missing \"{entry}\" specifier in \"{name}\" package") } }; - eprintln!("{}", message); + eprintln!("{message}"); } fn walk( diff --git a/crates/plugin_resolve/src/resolver/utils.rs b/crates/plugin_resolve/src/resolver/utils.rs index f8ffc1ff6..cbf0dd22e 100644 --- a/crates/plugin_resolve/src/resolver/utils.rs +++ b/crates/plugin_resolve/src/resolver/utils.rs @@ -1,11 +1,10 @@ use farmfe_core::{common::PackageJsonInfo, farm_profile_function, regex, serde_json::Value}; use once_cell::sync::Lazy; use std::{ - path::{Path, PathBuf}, + path::{PathBuf}, str::FromStr, }; -use super::NODE_MODULES; static PACKAGE_REGEX: Lazy = Lazy::new(|| regex::Regex::new(r"^(?P[^@][^/]*)|^(?P@[^/]+/[^/]+)").unwrap()); @@ -53,7 +52,7 @@ pub fn parse_package_source(source: &str) -> Option { let sub_path = source .strip_prefix(package_name) - .map(|s| format!(".{}", s)) + .map(|s| format!(".{s}")) .filter(|_| package_name != source); Some(ParsePackageSourceResult { diff --git a/crates/plugin_resolve/tests/mod.rs b/crates/plugin_resolve/tests/mod.rs index 68577b21a..be9d48377 100644 --- a/crates/plugin_resolve/tests/mod.rs +++ b/crates/plugin_resolve/tests/mod.rs @@ -1,9 +1,9 @@ use std::{collections::HashMap, sync::Arc}; use farmfe_core::{ - config::{Config, ResolveConfig}, + config::{AliasItem, Config, ResolveConfig, StringOrRegex}, context::CompilationContext, - plugin::ResolveKind, + plugin::ResolveKind, regex::Regex, }; use farmfe_plugin_resolve::resolver::{ResolveOptions, Resolver}; use farmfe_testing_helpers::fixture; @@ -198,19 +198,24 @@ fn resolve_alias() { CompilationContext::new( Config { resolve: Box::new(ResolveConfig { - alias: HashMap::from([ - ("@".to_string(), cwd.to_string_lossy().to_string()), - ("/@".to_string(), cwd.to_string_lossy().to_string()), - // long alias - ( - "@/components".to_string(), - cwd.join("components").to_string_lossy().to_string(), - ), - ( - "$__farm_regex:^/(utils)$".to_string(), - cwd.join("$1").to_string_lossy().to_string(), - ), - ]), + alias: vec![ + AliasItem::Complex { + find: StringOrRegex::String("@".to_string()), + replacement: cwd.to_string_lossy().to_string(), + }, + AliasItem::Complex { + find: StringOrRegex::String("/@".to_string()), + replacement: cwd.to_string_lossy().to_string(), + }, + AliasItem::Complex { + find: StringOrRegex::String("@/components".to_string()), + replacement: cwd.join("components").to_string_lossy().to_string(), + }, + AliasItem::Complex { + find: StringOrRegex::String("$__farm_regex:^/(utils)$".to_string()), + replacement: cwd.join("$1").to_string_lossy().to_string(), + }, + ], ..Default::default() }), ..Default::default() diff --git a/crates/plugin_runtime/src/handle_entry_resources.rs b/crates/plugin_runtime/src/handle_entry_resources.rs index 53793d7e7..98daca514 100644 --- a/crates/plugin_runtime/src/handle_entry_resources.rs +++ b/crates/plugin_runtime/src/handle_entry_resources.rs @@ -181,16 +181,15 @@ fn get_export_info_code( ExportInfoOfEntryModule::Named { name, import_as } => { if let Some(import_as) = import_as { match context.config.output.format { - ModuleFormat::CommonJs => format!("module.exports.{} = entry.{};", import_as, name), + ModuleFormat::CommonJs => format!("module.exports.{import_as} = entry.{name};"), ModuleFormat::EsModule => format!( - "var {name}=entry.{name};export {{ {} as {} }};", - name, import_as + "var {name}=entry.{name};export {{ {name} as {import_as} }};" ), } } else { match context.config.output.format { - ModuleFormat::CommonJs => format!("module.exports.{} = entry.{};", name, name), - ModuleFormat::EsModule => format!("var {name}=entry.{name};export {{ {} }};", name), + ModuleFormat::CommonJs => format!("module.exports.{name} = entry.{name};"), + ModuleFormat::EsModule => format!("var {name}=entry.{name};export {{ {name} }};"), } } } @@ -350,7 +349,7 @@ pub fn handle_entry_resources( r#"{farm_global_this}.{FARM_MODULE_SYSTEM}.setInitialLoadedResources([{initial_loaded_resources}]);"#, initial_loaded_resources = dep_resources .iter() - .map(|rn| format!("'{}'", rn)) + .map(|rn| format!("'{rn}'")) .collect::>() .join(",") ); diff --git a/crates/plugin_runtime/src/insert_runtime_plugins.rs b/crates/plugin_runtime/src/insert_runtime_plugins.rs index bbb58134b..fb64ce47b 100644 --- a/crates/plugin_runtime/src/insert_runtime_plugins.rs +++ b/crates/plugin_runtime/src/insert_runtime_plugins.rs @@ -13,7 +13,7 @@ pub fn insert_runtime_plugins(content: String, context: &Arc .iter() .enumerate() .map(|(i, plugin_path)| { - let ident = format!("{}{}", PLUGIN_VAR_PREFIX, i); + let ident = format!("{PLUGIN_VAR_PREFIX}{i}"); let import_stmt = format!( "import {} from '{}';", ident, diff --git a/crates/plugin_runtime/src/lib.rs b/crates/plugin_runtime/src/lib.rs index b0469960b..83e2f330c 100644 --- a/crates/plugin_runtime/src/lib.rs +++ b/crates/plugin_runtime/src/lib.rs @@ -8,7 +8,7 @@ use std::{ use farmfe_core::{ config::{ - config_regex::ConfigRegex, external::ExternalConfig, partial_bundling::PartialBundlingEnforceResourceConfig, AliasItem, Config, Mode, ModuleFormat, StringOrRegex, TargetEnv, FARM_MODULE_SYSTEM + config_regex::ConfigRegex, external::ExternalConfig, partial_bundling::PartialBundlingEnforceResourceConfig, AliasItem, Config, ModuleFormat, StringOrRegex, TargetEnv, FARM_MODULE_SYSTEM, }, context::CompilationContext, enhanced_magic_string::types::{MappingsOptionHires, SourceMapOptions}, @@ -79,7 +79,7 @@ impl Plugin for FarmPluginRuntime { 0, PartialBundlingEnforceResourceConfig { name: "FARM_RUNTIME".to_string(), - test: vec![ConfigRegex::new(&format!(".+{}", RUNTIME_SUFFIX))], + test: vec![ConfigRegex::new(&format!(".+{RUNTIME_SUFFIX}"))], }, ); @@ -153,7 +153,7 @@ impl Plugin for FarmPluginRuntime { source_map: None, })) } else { - panic!("unknown module type for {}", real_file_path); + panic!("unknown module type for {real_file_path}"); } } else { Ok(None) @@ -297,7 +297,7 @@ impl Plugin for FarmPluginRuntime { .chars() .map(|c| if c.is_alphanumeric() { c } else { '_' }) .collect::(); - name = format!("__farm_external_module_{}", name); + name = format!("__farm_external_module_{name}"); let import_str = if context.config.output.format == ModuleFormat::EsModule { format!("import * as {name} from {external_module:?};") @@ -337,7 +337,7 @@ impl Plugin for FarmPluginRuntime { // it's maybe from plugin .unwrap_or(source.clone()); - let source_obj = format!("window['{}']||{{}}", replace_source); + let source_obj = format!("window['{replace_source}']||{{}}"); external_objs.push(if context.config.output.format == ModuleFormat::EsModule { format!("{source:?}: ({source_obj}).default && !({source_obj}).__esModule ? {{...({source_obj}),__esModule:true}} : ({{...{source_obj}}})") } else { diff --git a/crates/plugin_runtime/src/render_resource_pot/mod.rs b/crates/plugin_runtime/src/render_resource_pot/mod.rs index 6386389d1..76574487a 100644 --- a/crates/plugin_runtime/src/render_resource_pot/mod.rs +++ b/crates/plugin_runtime/src/render_resource_pot/mod.rs @@ -74,7 +74,7 @@ pub fn resource_pot_to_runtime_object( .try_for_each(|m_id| { let module = module_graph .module(m_id) - .unwrap_or_else(|| panic!("Module not found: {:?}", m_id)); + .unwrap_or_else(|| panic!("Module not found: {m_id:?}")); let mut cache_store_key = None; diff --git a/crates/plugin_runtime/src/render_resource_pot/render_module.rs b/crates/plugin_runtime/src/render_resource_pot/render_module.rs index acee74d05..f175c954b 100644 --- a/crates/plugin_runtime/src/render_resource_pot/render_module.rs +++ b/crates/plugin_runtime/src/render_resource_pot/render_module.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, path::PathBuf, sync::Arc}; +use std::{path::PathBuf, sync::Arc}; use farmfe_core::{ context::CompilationContext, diff --git a/crates/plugin_runtime/src/render_resource_pot/source_replacer.rs b/crates/plugin_runtime/src/render_resource_pot/source_replacer.rs index 710dea193..94084c620 100644 --- a/crates/plugin_runtime/src/render_resource_pot/source_replacer.rs +++ b/crates/plugin_runtime/src/render_resource_pot/source_replacer.rs @@ -13,7 +13,7 @@ use farmfe_core::{ plugin::ResolveKind, swc_common::{Mark, DUMMY_SP}, swc_ecma_ast::{ - Bool, CallExpr, Callee, Expr, ExprOrSpread, Ident, Lit, MemberExpr, MemberProp, Number, Str, + Bool, CallExpr, Callee, Expr, ExprOrSpread, Ident, Lit, MemberExpr, MemberProp, Str, }, }; use farmfe_toolkit::{ diff --git a/crates/plugin_runtime/src/render_resource_pot/transform_async_module.rs b/crates/plugin_runtime/src/render_resource_pot/transform_async_module.rs index b2469a2f8..f46656663 100644 --- a/crates/plugin_runtime/src/render_resource_pot/transform_async_module.rs +++ b/crates/plugin_runtime/src/render_resource_pot/transform_async_module.rs @@ -198,7 +198,7 @@ impl VisitMut for FarmRequireVisitor { } fn rename_ident(name: &str) -> String { - format!("{}__f", name) + format!("{name}__f") } fn try_get_farm_require_id(expr: &Expr) -> Option { diff --git a/crates/plugin_runtime/src/render_resource_pot/transform_module_decls.rs b/crates/plugin_runtime/src/render_resource_pot/transform_module_decls.rs index e0c9a104f..a5a4ddd76 100644 --- a/crates/plugin_runtime/src/render_resource_pot/transform_module_decls.rs +++ b/crates/plugin_runtime/src/render_resource_pot/transform_module_decls.rs @@ -537,7 +537,7 @@ fn get_name_from_src(src: &str) -> String { assert!(val_name.len() > 0); - format!("_f_{}", val_name) + format!("_f_{val_name}") } fn create_var_decl_stmt(val_name_ident: Ident, init: Box) -> ModuleItem { @@ -974,7 +974,7 @@ export * from './e'; codegen_module(&mut ast, EsVersion::latest(), cm, None, false, None).unwrap(); let code = String::from_utf8(code_bytes).unwrap(); - println!("{}", code); + println!("{code}"); assert_eq!( code, @@ -1073,7 +1073,7 @@ export const f = 1, h = 2; codegen_module(&mut ast, EsVersion::latest(), cm, None, false, None).unwrap(); let code = String::from_utf8(code_bytes).unwrap(); - println!("{}", code); + println!("{code}"); assert_eq!( code, diff --git a/crates/plugin_script/src/swc_plugins.rs b/crates/plugin_script/src/swc_plugins.rs index f60859c32..8902f43eb 100644 --- a/crates/plugin_script/src/swc_plugins.rs +++ b/crates/plugin_script/src/swc_plugins.rs @@ -47,7 +47,7 @@ pub fn init_plugin_module_cache_once(config: &farmfe_core::config::Config) { let path = if let FileName::Real(value) = resolved_path.filename { value } else { - panic!("Failed to resolve plugin path: {:?}", resolved_path); + panic!("Failed to resolve plugin path: {resolved_path:?}"); }; // store_bytes_from_path which swc uses will cause deadlock, so we read and cache the plugin module bytecode manually diff --git a/crates/plugin_static_assets/src/lib.rs b/crates/plugin_static_assets/src/lib.rs index f69f6bc8f..e9328902b 100644 --- a/crates/plugin_static_assets/src/lib.rs +++ b/crates/plugin_static_assets/src/lib.rs @@ -9,7 +9,7 @@ use std::{ use base64::engine::{general_purpose, Engine}; use farmfe_core::{ cache_item, - config::{Config, TargetEnv}, + config::{Config}, context::{CompilationContext, EmitFileParams}, deserialize, module::ModuleType, @@ -174,8 +174,7 @@ impl Plugin for FarmPluginStaticAssets { let mime_type_str = mime_type.to_string(); let content = format!( - "export default \"data:{};base64,{}\"", - mime_type_str, file_base64 + "export default \"data:{mime_type_str};base64,{file_base64}\"" ); return Ok(Some(farmfe_core::plugin::PluginTransformHookResult { @@ -227,18 +226,17 @@ impl Plugin for FarmPluginStaticAssets { let assets_path = if !context.config.output.public_path.is_empty() { let normalized_public_path = context.config.output.public_path.trim_end_matches("/"); - format!("{}/{}", normalized_public_path, resource_name) + format!("{normalized_public_path}/{resource_name}") } else { - format!("/{}", resource_name) + format!("/{resource_name}") }; let content = if context.config.output.target_env.is_node() { format!( - "export default new URL(/* {} */{:?}, import.meta.url)", - FARM_IGNORE_ACTION_COMMENT, assets_path + "export default new URL(/* {FARM_IGNORE_ACTION_COMMENT} */{assets_path:?}, import.meta.url)" ) } else { - format!("export default {:?};", assets_path) + format!("export default {assets_path:?};") }; context.emit_file(EmitFileParams { diff --git a/crates/plugin_tree_shake/src/statement_graph.rs b/crates/plugin_tree_shake/src/statement_graph.rs index df5fa4141..b5ecafa5a 100644 --- a/crates/plugin_tree_shake/src/statement_graph.rs +++ b/crates/plugin_tree_shake/src/statement_graph.rs @@ -215,7 +215,7 @@ impl ToString for UsedStatementIdent { UsedStatementIdent::Default => "default".to_string(), UsedStatementIdent::SwcIdent(id) => format!("{}{:?}", id.0, id.1), UsedStatementIdent::ExportAll => "*".to_string(), - UsedStatementIdent::InExportAll(id) => format!("*({})", id), + UsedStatementIdent::InExportAll(id) => format!("*({id})"), } } } diff --git a/crates/plugin_tree_shake/src/statement_graph/analyze_statement_side_effects/test.rs b/crates/plugin_tree_shake/src/statement_graph/analyze_statement_side_effects/test.rs index 29d85f901..76415437d 100644 --- a/crates/plugin_tree_shake/src/statement_graph/analyze_statement_side_effects/test.rs +++ b/crates/plugin_tree_shake/src/statement_graph/analyze_statement_side_effects/test.rs @@ -94,7 +94,7 @@ fn write_top_level_var() { top_level_mark, &SingleThreadedComments::default(), ); - println!("{:?}", side_effects); + println!("{side_effects:?}"); assert!(matches!( side_effects, super::StatementSideEffects::WriteTopLevelVar(_) @@ -157,7 +157,7 @@ fn access_global_var() { top_level_mark, &SingleThreadedComments::default(), ); - println!("{:?}", side_effects); + println!("{side_effects:?}"); assert!(matches!( side_effects, super::StatementSideEffects::WriteTopLevelVar(_) @@ -297,7 +297,7 @@ comp(); let item_2 = &module.body[1]; let side_effects = super::analyze_statement_side_effects(item_2, unresolved_mark, top_level_mark, &comments); - println!("{:?}", side_effects); + println!("{side_effects:?}"); assert!(matches!( side_effects, super::StatementSideEffects::NoSideEffects @@ -306,7 +306,7 @@ comp(); let item_3 = &module.body[2]; let side_effects = super::analyze_statement_side_effects(item_3, unresolved_mark, top_level_mark, &comments); - println!("{:?}", side_effects); + println!("{side_effects:?}"); assert!(matches!( side_effects, super::StatementSideEffects::UnclassifiedSelfExecuted @@ -328,7 +328,7 @@ var _c; let item_2 = &module.body[1]; let side_effects = super::analyze_statement_side_effects(item_2, unresolved_mark, top_level_mark, &comments); - println!("{:?}", side_effects); + println!("{side_effects:?}"); assert!(matches!( side_effects, super::StatementSideEffects::NoSideEffects @@ -337,7 +337,7 @@ var _c; let item_3 = &module.body[2]; let side_effects = super::analyze_statement_side_effects(item_3, unresolved_mark, top_level_mark, &comments); - println!("{:?}", side_effects); + println!("{side_effects:?}"); assert!(matches!( side_effects, super::StatementSideEffects::WriteTopLevelVar(_) @@ -361,7 +361,7 @@ fn object_lit_assign() { let item_2 = &module.body[1]; let side_effects = super::analyze_statement_side_effects(item_2, unresolved_mark, top_level_mark, &comments); - println!("{:?}", side_effects); + println!("{side_effects:?}"); assert!(matches!( side_effects, super::StatementSideEffects::ReadTopLevelVar(_) @@ -370,7 +370,7 @@ fn object_lit_assign() { let item_3 = &module.body[2]; let side_effects = super::analyze_statement_side_effects(item_3, unresolved_mark, top_level_mark, &comments); - println!("{:?}", side_effects); + println!("{side_effects:?}"); assert!(matches!( side_effects, super::StatementSideEffects::WriteTopLevelVar(_) diff --git a/crates/plugin_tree_shake/tests/remove_useless_stmts.rs b/crates/plugin_tree_shake/tests/remove_useless_stmts.rs index 1e4b218f3..e58f65136 100644 --- a/crates/plugin_tree_shake/tests/remove_useless_stmts.rs +++ b/crates/plugin_tree_shake/tests/remove_useless_stmts.rs @@ -88,7 +88,7 @@ export default 'default'; let bytes = codegen_module(swc_module, EsVersion::EsNext, cm, None, false, None).unwrap(); let result = String::from_utf8(bytes).unwrap(); - println!("{}", result); + println!("{result}"); let expect = r#"import { aValue } from './foo'; const a = aValue; const c = 3; diff --git a/crates/plugin_tree_shake/tests/tree_shake_module.rs b/crates/plugin_tree_shake/tests/tree_shake_module.rs index 42197e6f7..81d82f9c7 100644 --- a/crates/plugin_tree_shake/tests/tree_shake_module.rs +++ b/crates/plugin_tree_shake/tests/tree_shake_module.rs @@ -406,7 +406,7 @@ export * from './bar'; assert_eq!(result[0].stmt_id, 0); assert_eq!(result[0].source, "./foo"); assert_eq!(result[0].used_stmt_idents.as_partial().len(), 2); - println!("{:?}", result); + println!("{result:?}"); assert!(result[0] .used_stmt_idents .contains(&UsedExportsIdent::SwcIdent("b".to_string()))); diff --git a/crates/swc_transformer_import_glob/src/lib.rs b/crates/swc_transformer_import_glob/src/lib.rs index c89afdcdc..1a944d34c 100644 --- a/crates/swc_transformer_import_glob/src/lib.rs +++ b/crates/swc_transformer_import_glob/src/lib.rs @@ -54,7 +54,7 @@ pub fn transform_import_meta_glob( for (index, meta_info) in visitor.import_globs.into_iter().enumerate() { for (glob_index, globed_source) in meta_info.globed_sources.into_iter().enumerate() { let globed_source = if let Some(query) = &meta_info.query { - format!("{}?{}", globed_source, query) + format!("{globed_source}?{query}") } else { globed_source }; @@ -75,14 +75,14 @@ pub fn transform_import_meta_glob( farmfe_core::swc_ecma_ast::ImportDefaultSpecifier { span: DUMMY_SP, local: farmfe_core::swc_ecma_ast::Ident::new( - format!("__glob__{}_{}", index, glob_index).into(), + format!("__glob__{index}_{glob_index}").into(), DUMMY_SP, ), }, )], src: Box::new(farmfe_core::swc_ecma_ast::Str { span: DUMMY_SP, - value: format!("{}?url", globed_source).into(), + value: format!("{globed_source}?url").into(), raw: None, }), type_only: false, @@ -138,7 +138,7 @@ fn create_eager_named_import( farmfe_core::swc_ecma_ast::ImportNamedSpecifier { span: DUMMY_SP, local: farmfe_core::swc_ecma_ast::Ident::new( - format!("__glob__{}_{}", index, glob_index).into(), + format!("__glob__{index}_{glob_index}").into(), DUMMY_SP, ), imported: Some(farmfe_core::swc_ecma_ast::ModuleExportName::Ident( @@ -171,7 +171,7 @@ fn create_eager_namespace_import( farmfe_core::swc_ecma_ast::ImportStarAsSpecifier { span: DUMMY_SP, local: farmfe_core::swc_ecma_ast::Ident::new( - format!("__glob__{}_{}", index, glob_index).into(), + format!("__glob__{index}_{glob_index}").into(), DUMMY_SP, ), }, @@ -196,7 +196,7 @@ fn create_eager_default_import(index: usize, glob_index: usize, globed_source: & farmfe_core::swc_ecma_ast::ImportDefaultSpecifier { span: DUMMY_SP, local: farmfe_core::swc_ecma_ast::Ident::new( - format!("__glob__{}_{}", index, glob_index).into(), + format!("__glob__{index}_{glob_index}").into(), DUMMY_SP, ), }, @@ -383,7 +383,7 @@ impl<'a> ImportGlobVisitor<'a> { .unwrap_or_else(|| source.to_string()); if negative { - format!("!{}", result) + format!("!{result}") } else { result } @@ -404,7 +404,7 @@ impl<'a> ImportGlobVisitor<'a> { }; let source = if !source.starts_with('.') && !source.starts_with('/') { - format!("./{}", source) + format!("./{source}") } else { source.to_string() }; @@ -486,7 +486,7 @@ impl<'a> ImportGlobVisitor<'a> { let rel_source = relative(&self.root, &file); if !rel_source.starts_with('/') { - format!("/{}", rel_source) + format!("/{rel_source}") } else { rel_source } @@ -494,7 +494,7 @@ impl<'a> ImportGlobVisitor<'a> { let rel_source = relative(&self.cur_dir, &file); if !rel_source.starts_with('.') { - format!("./{}", rel_source) + format!("./{rel_source}") } else { rel_source } @@ -503,7 +503,7 @@ impl<'a> ImportGlobVisitor<'a> { let mut relative_file = relative(&self.cur_dir, &file); if !relative_file.starts_with('.') { - relative_file = format!("./{}", relative_file); + relative_file = format!("./{relative_file}"); } if negative && filtered_paths.contains_key(&relative_file) { @@ -549,7 +549,7 @@ impl<'a> ImportGlobVisitor<'a> { Some(( source.to_string(), Box::new(Expr::Ident(Ident::new( - format!("__glob__{}_{}", cur_index, entry_index).into(), + format!("__glob__{cur_index}_{entry_index}").into(), DUMMY_SP, ))), )) @@ -709,7 +709,7 @@ impl<'a> VisitMut for ImportGlobVisitor<'a> { props.push(( source.clone(), Box::new(Expr::Ident(Ident::new( - format!("__glob__{}_{}", cur_index, entry_index).into(), + format!("__glob__{cur_index}_{entry_index}").into(), DUMMY_SP, ))), )); @@ -717,8 +717,8 @@ impl<'a> VisitMut for ImportGlobVisitor<'a> { // add "./dir/foo.js": () => import('./dir/foo.js') let (rel_file, source) = if let Some(query) = &import_glob_info.query { ( - format!("{}?{}", relative_file, query), - format!("{}?{}", source, query), + format!("{relative_file}?{query}"), + format!("{source}?{query}"), ) } else { (relative_file.clone(), source.clone()) diff --git a/crates/swc_transformer_import_glob/tests/mod.rs b/crates/swc_transformer_import_glob/tests/mod.rs index 028b0adb2..92de01339 100644 --- a/crates/swc_transformer_import_glob/tests/mod.rs +++ b/crates/swc_transformer_import_glob/tests/mod.rs @@ -1,6 +1,11 @@ use std::{collections::HashMap, sync::Arc}; -use farmfe_core::{swc_common::SourceMap, swc_ecma_ast::EsVersion, swc_ecma_parser::Syntax}; +use farmfe_core::{ + config::{AliasItem, StringOrRegex}, + swc_common::SourceMap, + swc_ecma_ast::EsVersion, + swc_ecma_parser::Syntax, +}; use farmfe_swc_transformer_import_glob::transform_import_meta_glob; use farmfe_testing_helpers::fixture; use farmfe_toolkit::script::{codegen_module, parse_module, ParseScriptModuleResult}; @@ -8,10 +13,10 @@ use farmfe_toolkit::script::{codegen_module, parse_module, ParseScriptModuleResu #[test] fn test_import_meta_glob() { fixture!("tests/fixtures/**/input.js", |file, _crate_path| { - println!("Testing {:?}...", file); + println!("Testing {file:?}..."); let file_content = std::fs::read_to_string(&file).unwrap(); let cm = Arc::new(SourceMap::default()); - let ParseScriptModuleResult { ast: mut ast, .. } = parse_module( + let ParseScriptModuleResult { mut ast, .. } = parse_module( file.to_string_lossy().to_string().as_str(), &file_content, Syntax::Es(Default::default()), @@ -29,16 +34,16 @@ fn test_import_meta_glob() { &mut ast, root.to_string(), dir.to_string(), - &HashMap::from([( - "@".to_string(), - file + &vec![AliasItem::Complex { + find: StringOrRegex::String("@".to_string()), + replacement: file .parent() .unwrap() .to_path_buf() .join("dir") .to_string_lossy() .to_string(), - )]), + }], ) .unwrap(); diff --git a/crates/testing_helpers/src/lib.rs b/crates/testing_helpers/src/lib.rs index b73f52493..80d5ad41a 100644 --- a/crates/testing_helpers/src/lib.rs +++ b/crates/testing_helpers/src/lib.rs @@ -48,7 +48,7 @@ pub fn construct_test_module_graph() -> ModuleGraph { &from.into(), &to.into(), ModuleGraphEdgeDataItem { - source: format!("./{}", to), + source: format!("./{to}"), kind: ResolveKind::Import, order, }, @@ -62,7 +62,7 @@ pub fn construct_test_module_graph() -> ModuleGraph { &from.into(), &to.into(), ModuleGraphEdgeDataItem { - source: format!("./{}", to), + source: format!("./{to}"), kind: ResolveKind::DynamicImport, order, }, @@ -170,7 +170,7 @@ pub fn construct_test_module_graph_complex() -> ModuleGraph { &from.into(), &to.into(), ModuleGraphEdgeDataItem { - source: format!("./{}", to), + source: format!("./{to}"), kind: ResolveKind::Import, order, }, @@ -271,6 +271,6 @@ where } if !exists { - panic!("no fixtures found under {}", pattern); + panic!("no fixtures found under {pattern}"); } } diff --git a/crates/toolkit/src/common.rs b/crates/toolkit/src/common.rs index 703b0c2c9..177796e92 100644 --- a/crates/toolkit/src/common.rs +++ b/crates/toolkit/src/common.rs @@ -182,8 +182,7 @@ pub fn load_source_original_source_map( // try load source map when load module content. if content.contains(source_map_comment_prefix) { let base64_prefix = format!( - "{}=data:application/json;base64,", - source_map_comment_prefix + "{source_map_comment_prefix}=data:application/json;base64," ); // detect that the source map is inline or not let source_map = if content.contains(&base64_prefix) { @@ -195,7 +194,7 @@ pub fn load_source_original_source_map( .map(|source_map| base64_decode(source_map.as_bytes())) } else { // external source map - let prefix = format!("{}=", source_map_comment_prefix); + let prefix = format!("{source_map_comment_prefix}="); let mut source_map_path = content.split(&prefix); let source_map_path = source_map_path.nth(1).unwrap().to_string(); let resolved_path = Path::new(resolved_path); diff --git a/crates/toolkit/src/css/mod.rs b/crates/toolkit/src/css/mod.rs index 545319a36..61f4b16ad 100644 --- a/crates/toolkit/src/css/mod.rs +++ b/crates/toolkit/src/css/mod.rs @@ -36,9 +36,9 @@ pub fn parse_css_stylesheet( content = regex .replace_all(&content, "filter:\"$1.Microsoft.$2\"$3") .to_string(); - // 3. replace invalid operator, eg: top: -8px/2 + 1 to top: "-8px/2 + 1" using regex. fix #1748 - let regex = Regex::new(r#":\s*([^;{}]*?\d\s(?:\+|-|\*|/)\s\d[^;{}]*?)\s*(;|\})"#).unwrap(); - content = regex.replace_all(&content, ":\"$1\"$2").to_string(); + // // 3. replace invalid operator, eg: top: -8px/2 + 1 to top: "-8px/2 + 1" using regex. fix #1748 + // let regex = Regex::new(r#":\s*([^;{}]*?\d\s+\s\d[^;{}]*?)\s*(;|\})"#).unwrap(); + // content = regex.replace_all(&content, ":\"$1\"$2").to_string(); let (cm, source_file) = create_swc_source_map(Source { path: PathBuf::from(id), diff --git a/crates/toolkit/src/fs/mod.rs b/crates/toolkit/src/fs/mod.rs index bcca0d329..af3f883ad 100644 --- a/crates/toolkit/src/fs/mod.rs +++ b/crates/toolkit/src/fs/mod.rs @@ -17,7 +17,7 @@ pub fn read_file_utf8(path: &str) -> Result { /// read content of the path, return bytes. pub fn read_file_raw(path: &str) -> Result> { - std::fs::read(path).map_err(|e| CompilationError::GenericError(format!("{:?}", e))) + std::fs::read(path).map_err(|e| CompilationError::GenericError(format!("{e:?}"))) } pub fn transform_output_filename( diff --git a/crates/toolkit/src/get_dynamic_resources_map.rs b/crates/toolkit/src/get_dynamic_resources_map.rs index c8645338f..451344380 100644 --- a/crates/toolkit/src/get_dynamic_resources_map.rs +++ b/crates/toolkit/src/get_dynamic_resources_map.rs @@ -57,7 +57,7 @@ pub fn get_dynamic_resources_map( for r in rp.resources() { let resource = resources_map .get(r) - .unwrap_or_else(|| panic!("{} not found", r)); + .unwrap_or_else(|| panic!("{r} not found")); // Currently only support js and css if !matches!(resource.resource_type, ResourceType::Js | ResourceType::Css) { @@ -90,7 +90,7 @@ pub fn get_dynamic_resources_code( let mut dynamic_resources_index = vec![]; for (resource_name, resource_type) in resources { - let key = format!("{}{:?}", resource_name, resource_type); + let key = format!("{resource_name}{resource_type:?}"); if let Some(index) = visited_resources.get(&key) { dynamic_resources_index.push(format!("{}", *index)); @@ -99,15 +99,14 @@ pub fn get_dynamic_resources_code( match resource_type { ResourceType::Js => { - dynamic_resources.push(format!(r#"{{ path: '{}', type: 0 }}"#, resource_name)); + dynamic_resources.push(format!(r#"{{ path: '{resource_name}', type: 0 }}"#)); } ResourceType::Css => { - dynamic_resources.push(format!(r#"{{ path: '{}', type: 1 }}"#, resource_name)); + dynamic_resources.push(format!(r#"{{ path: '{resource_name}', type: 1 }}"#)); } _ => { panic!( - "unsupported type ({:?}) when injecting dynamic resources", - resource_type + "unsupported type ({resource_type:?}) when injecting dynamic resources" ) } } @@ -122,11 +121,11 @@ pub fn get_dynamic_resources_code( let mut dynamic_resources_code = dynamic_resources_code_vec .into_iter() - .map(|(id, resources_code)| format!(r#"'{}': [{}]"#, id, resources_code)) + .map(|(id, resources_code)| format!(r#"'{id}': [{resources_code}]"#)) .collect::>() .join(","); - dynamic_resources_code = format!("{{ {} }}", dynamic_resources_code); + dynamic_resources_code = format!("{{ {dynamic_resources_code} }}"); ( format!("[{}]", dynamic_resources.join(",")), diff --git a/crates/toolkit/src/html/mod.rs b/crates/toolkit/src/html/mod.rs index 881c0c421..4000276fa 100644 --- a/crates/toolkit/src/html/mod.rs +++ b/crates/toolkit/src/html/mod.rs @@ -122,8 +122,8 @@ pub fn create_attribute(name: &str, value: Option<&str>) -> Attribute { pub fn get_farm_global_this(namespace: &str, target_env: &TargetEnv) -> String { if target_env.is_node() { - format!("global['{}']", namespace) + format!("global['{namespace}']") } else { - format!("window['{}']", namespace) + format!("window['{namespace}']") } } diff --git a/crates/toolkit/src/resolve/package_json_loader.rs b/crates/toolkit/src/resolve/package_json_loader.rs index e4d7e7a92..4c0fb3d18 100644 --- a/crates/toolkit/src/resolve/package_json_loader.rs +++ b/crates/toolkit/src/resolve/package_json_loader.rs @@ -99,7 +99,7 @@ impl PackageJsonLoader { let map: HashMap = from_str(&content).map_err(|e| CompilationError::LoadPackageJsonError { package_json_path: package_json_path.to_string_lossy().to_string(), - err_message: format!("{:?}", e), + err_message: format!("{e:?}"), })?; let map_string = |v: &Value| { if let Value::String(v) = v { @@ -114,7 +114,7 @@ impl PackageJsonLoader { result.set_raw_map(from_str(&content).map_err(|e| { CompilationError::LoadPackageJsonError { package_json_path: package_json_path.to_string_lossy().to_string(), - err_message: format!("{:?}", e), + err_message: format!("{e:?}"), } })?); result.set_raw(content); diff --git a/crates/toolkit/src/resolve/path_start_with_alias.rs b/crates/toolkit/src/resolve/path_start_with_alias.rs index 1d5cea044..51f5b6c16 100644 --- a/crates/toolkit/src/resolve/path_start_with_alias.rs +++ b/crates/toolkit/src/resolve/path_start_with_alias.rs @@ -61,15 +61,24 @@ mod test { fn test() { let cwd = PathBuf::from("/root/src"); - let alias = HashMap::from([ - ("/@".to_string(), cwd.to_string_lossy().to_string()), - ("@".to_string(), cwd.to_string_lossy().to_string()), - ("react$".to_string(), cwd.to_string_lossy().to_string()), - ( - "$__farm_regex:^/(utils)$".to_string(), - cwd.join("$1").to_string_lossy().to_string(), - ), - ]); + let alias: Vec = vec![ + AliasItem::Complex { + find: StringOrRegex::String("/@".to_string()), + replacement: cwd.to_string_lossy().to_string(), + }, + AliasItem::Complex { + find: StringOrRegex::String("@".to_string()), + replacement: cwd.to_string_lossy().to_string(), + }, + AliasItem::Complex { + find: StringOrRegex::Regex(Regex::new("react$").unwrap()), + replacement: cwd.to_string_lossy().to_string(), + }, + AliasItem::Complex { + find: StringOrRegex::Regex(Regex::new("^/(utils)$").unwrap()), + replacement: cwd.join("$1").to_string_lossy().to_string(), + }, + ]; assert_eq!(is_start_with_alias(&alias, "/@/img/logo.png"), true); assert_eq!(is_start_with_alias(&alias, "@/img/logo.png"), true); diff --git a/crates/toolkit/src/script/mod.rs b/crates/toolkit/src/script/mod.rs index bfbfac14d..885c14546 100644 --- a/crates/toolkit/src/script/mod.rs +++ b/crates/toolkit/src/script/mod.rs @@ -97,7 +97,7 @@ pub fn parse_stmt( .parse_stmt(top_level) .map_err(|e| CompilationError::ParseError { resolved_path: id.to_string(), - msg: format!("{:?}", e), + msg: format!("{e:?}"), }) } diff --git a/crates/utils/src/hash.rs b/crates/utils/src/hash.rs index 1815d295c..5a6ae9760 100644 --- a/crates/utils/src/hash.rs +++ b/crates/utils/src/hash.rs @@ -8,7 +8,7 @@ pub fn sha256(bytes: &[u8], len: usize) -> String { // Note that calling `finalize()` consumes hasher let hash = hasher.finalize(); - format!("{:x}", hash)[..len].to_string() + format!("{hash:x}")[..len].to_string() } pub fn base64_encode(bytes: &[u8]) -> String { diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs index eb751b2ef..1ec2503ec 100644 --- a/crates/utils/src/lib.rs +++ b/crates/utils/src/lib.rs @@ -42,7 +42,7 @@ pub fn parse_query(path: &str) -> Vec<(String, String)> { let kv = pair.split('=').collect::>(); if kv.len() != 2 { - panic!("Invalid query: {}", pair); + panic!("Invalid query: {pair}"); } query.push((kv[0], kv[1])); @@ -71,7 +71,7 @@ pub fn stringify_query(query: &Vec<(String, String)>) -> String { if v == PARSE_QUERY_TRUE || v.is_empty() { qs.push(k.to_string()); } else { - qs.push(format!("{}={}", k, v)); + qs.push(format!("{k}={v}")); } } @@ -100,14 +100,14 @@ pub fn relative(from: &str, to: &str) -> String { let to = file_url_to_path(to); if !PathBuf::from(&from).is_absolute() { - panic!("from path must be absolute. from: {} to: {}", from, to); + panic!("from path must be absolute. from: {from} to: {to}"); } let rp = diff_paths(&to, &from).unwrap_or_else(|| { if !PathBuf::from(&to).is_absolute() { return PathBuf::from(&to); } - panic!("failed to get relative path from {} to {}", from, to); + panic!("failed to get relative path from {from} to {to}"); }); // make sure the relative path is platform independent @@ -138,7 +138,7 @@ pub fn relative(from: &str, to: &str) -> String { if result.is_empty() { result += &c; } else { - result = format!("{}/{}", result, c); + result = format!("{result}/{c}"); } } } diff --git a/docs/docs/quick-start.mdx b/docs/docs/quick-start.mdx index 44f0f55fc..a9d328331 100644 --- a/docs/docs/quick-start.mdx +++ b/docs/docs/quick-start.mdx @@ -26,15 +26,30 @@ You can also directly specify the project name and the template you want to use +| Template | Description | Optional Features | +|:-------:|:--------:|:-------:| +| vanilla | Vanilla JavaScript | TypeScript | +| react | react18 | TypeScript | +| vue3 | vue3 | TypeScript | +| vue2 | vue2 | TypeScript | +| svelte | svelte | TypeScript | +| solid | solid | TypeScript | +| preact | preact | TypeScript | +| lit | lit | TypeScript | +| nestjs | nestjs | TypeScript | +| tauri | tauri2 | TypeScript | +| electron | electron | TypeScript | + + ## 2. Start the Project Choose the package manager you like, install dependencies, then start the project. Then, start the project: - + -The project will start at `http://localhost:9000` by default. +> The project will start at `http://localhost:9000` by default. ## 3. Configuring the Project @@ -66,6 +81,12 @@ The built product is downgraded to `ES2017` by default, and the product will be See **[Build For Production](/docs/tutorials/build)** for details. ::: +## 4. Preview the build products + +Start preview server + + + ## Next Steps - [Why Farm?](/docs/why-farm) diff --git a/examples/refactor-react/package.json b/examples/refactor-react/package.json index 53d54bd99..82158a861 100644 --- a/examples/refactor-react/package.json +++ b/examples/refactor-react/package.json @@ -2,6 +2,7 @@ "name": "react-template", "version": "1.0.0", "type": "module", + "private": true, "scripts": { "dev": "farm", "start": "farm start --debug", diff --git a/examples/refactor-react/src/main.tsx b/examples/refactor-react/src/main.tsx index 17c551c1d..9e0b12deb 100644 --- a/examples/refactor-react/src/main.tsx +++ b/examples/refactor-react/src/main.tsx @@ -3,8 +3,8 @@ import "./main.css"; import reactLogo from "/react.svg"; import FarmLogo from "./assets/logo.png"; // import { a } from './a.js' -// import { Button } from 'antd' -// import { HappyProvider } from '@ant-design/happy-work-theme'; +import { Button } from 'antd' +import { HappyProvider } from '@ant-design/happy-work-theme'; export function Main() { const [count, setCount] = useState(0); // console.log(a); @@ -19,13 +19,16 @@ export function Main() { React logo - {/* */} - {/* */} - {/* */} + + + + + +

Farm + react

Edit src/main.tsx and save to test HMR diff --git a/examples/tailwind/src/App.tsx b/examples/tailwind/src/App.tsx index a474075ef..754a94ec9 100644 --- a/examples/tailwind/src/App.tsx +++ b/examples/tailwind/src/App.tsx @@ -17,7 +17,7 @@ const App = () => { Edit src/App.tsx and save to reload.

- + @@ -21,9 +21,9 @@ import home from "./pages/index.vue"; import aboute from "../deps/node_modules/my-ui/index.vue"; import { Button as TinyButton, Modal } from '@opentiny/vue' -function btnClick() { - Modal.alert({ message: '最大化显示', fullscreen: true }) -} +// function btnClick() { +// Modal.alert({ message: '最大化显示', fullscreen: true }) +// } import test1 from './components/test1.vue'; import test from './components/test.vue'; diff --git a/examples/vue3/package.json b/examples/vue3/package.json index 457c96969..5b89008df 100644 --- a/examples/vue3/package.json +++ b/examples/vue3/package.json @@ -1,6 +1,7 @@ { "name": "farm", "version": "1.0.0", + "private": true, "scripts": { "dev": "farm start", "start": "farm start", diff --git a/js-plugins/electron/src/index.ts b/js-plugins/electron/src/index.ts index ac3bb5fdc..c5574b897 100644 --- a/js-plugins/electron/src/index.ts +++ b/js-plugins/electron/src/index.ts @@ -49,7 +49,7 @@ export default function farmElectronPlugin( configureServer(server) { isDev = true; - server.server?.once('listening', () => { + server.httpServer?.once('listening', () => { // Used in electron/main.ts for during dev process.env.FARM_DEV_SERVER_URL = resolveServerUrl(server); @@ -163,7 +163,7 @@ function resolveFarmConfig( } function resolveServerUrl(server: Server) { - const addressInfo = server.server?.address(); + const addressInfo = server.httpServer?.address(); const isAddressInfo = (x: any): x is AddressInfo => x?.address; if (isAddressInfo(addressInfo)) { diff --git a/js-plugins/solid/package.json b/js-plugins/solid/package.json index c5515fa5f..d20c37b06 100644 --- a/js-plugins/solid/package.json +++ b/js-plugins/solid/package.json @@ -39,7 +39,7 @@ "solid-js": "^1.7.8" }, "peerDependencies": { - "@farmfe/core": "workspace:^1.3.28" + "@farmfe/core": "workspace:^1.3.29" }, "files": [ "build" diff --git a/js-plugins/vue/package.json b/js-plugins/vue/package.json index f32f4121b..bc1008b78 100644 --- a/js-plugins/vue/package.json +++ b/js-plugins/vue/package.json @@ -50,7 +50,7 @@ "source-map": "^0.7.4" }, "peerDependencies": { - "@farmfe/core": "workspace:^1.3.28", + "@farmfe/core": "workspace:^1.3.29", "less": "*", "sass": "*", "stylus": "*" diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index ee6667916..f7b48c38d 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,5 +1,11 @@ # @farmfe/core +## 1.3.29 + +### Patch Changes + +- 663dfeed: Revert change of replacing invalid css + ## 1.3.28 ### Patch Changes diff --git a/packages/core/package.json b/packages/core/package.json index e27d066c4..dd2e70ca5 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@farmfe/core", - "version": "1.3.28", + "version": "1.3.29", "main": "dist/index.js", "types": "dist/index.d.ts", "type": "module", @@ -64,7 +64,7 @@ "build:rs:profile": "cross-env FARM_PROFILE=1 npm run build:rs -- --features profile", "prepublishOnly": "napi prepublish -t npm && FARM_PUBLISH=true npm run build:cjs", "clean": "rimraf dist tsconfig.build.tsbuildinfo", - "version": "napi version", + "napi:version": "napi version", "artifacts": "napi artifacts", "type-check": "tsc -p tsconfig.build.json" }, diff --git a/packages/core/src/config/env.ts b/packages/core/src/config/env.ts index d2e5d840a..5de34545b 100644 --- a/packages/core/src/config/env.ts +++ b/packages/core/src/config/env.ts @@ -7,7 +7,6 @@ * https://github.com/vitejs/vite/blob/main/LICENSE * */ - import fs from 'node:fs'; import path from 'node:path'; diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts index 27ffb478b..aa7687f1e 100644 --- a/packages/core/src/config/schema.ts +++ b/packages/core/src/config/schema.ts @@ -6,6 +6,21 @@ import { fromZodError } from 'zod-validation-error'; import type { UserConfig } from './types.js'; +const TARGET_ENV = { + BROWSER: 'browser', + NODE: 'node', + NODE_LEGACY: 'node-legacy', + NODE_NEXT: 'node-next', + NODE16: 'node16', + BROWSER_LEGACY: 'browser-legacy', + BROWSER_ESNEXT: 'browser-esnext', + BROWSER_ES2015: 'browser-es2015', + BROWSER_ES2017: 'browser-es2017', + LIBRARY: 'library', + LIBRARY_BROWSER: 'library-browser', + LIBRARY_NODE: 'library-node' +} as const; + const baseRewriteSchema = z.union([ z.record(z.string(), z.string()), z @@ -14,8 +29,8 @@ const baseRewriteSchema = z.union([ .returns(z.union([z.string(), z.promise(z.string())])) ]); -// const stringRewriteSchema = baseRewriteSchema; -// const functionRewriteSchema = baseRewriteSchema; +const stringRewriteSchema = baseRewriteSchema; +const functionRewriteSchema = baseRewriteSchema; const pathFilterSchema = z.union([ z.string(), @@ -36,20 +51,7 @@ const outputSchema = z publicPath: z.string().optional(), assetsFilename: z.string().optional(), targetEnv: z - .enum([ - 'browser', - 'node', - 'node-legacy', - 'node-next', - 'node16', - 'browser-legacy', - 'browser-esnext', - 'browser-es2015', - 'browser-es2017', - 'library', - 'library-browser', - 'library-node' - ]) + .enum(Object.values(TARGET_ENV) as [string, ...string[]]) .optional(), format: z.enum(['cjs', 'esm']).optional() }) @@ -131,22 +133,6 @@ const serverSchema = z }) .strict(); -const previewServerSchema = z.object({ - host: z.union([z.string(), z.boolean()]).optional(), - port: z.number().positive().int().optional(), - strictPort: z.boolean().optional(), - open: z.boolean().optional(), - // cors: z.boolean().optional(), - headers: z.record(z.string()).optional(), - output: z.object({ - path: z.string().optional(), - publicPath: z.string().optional() - }), - distDir: z.string().optional(), - // TODO any type - https: z.any().optional() -}); - const aliasItemSchema = z.object({ find: z.union([z.string(), z.instanceof(RegExp)]), replacement: z.string(), @@ -182,7 +168,7 @@ const compilationConfigSchema = z externalNodeBuiltins: z .union([z.boolean(), z.array(z.string())]) .optional(), - mode: z.enum(['development', 'production']).optional(), + mode: z.string().optional(), watch: z .union([ z.boolean(), @@ -419,7 +405,6 @@ const FarmConfigSchema = z mode: z.string().optional(), watch: z.boolean().optional(), server: serverSchema.optional(), - preview: previewServerSchema.optional(), // TODO ANY type customLogger: z.any().optional() }) diff --git a/packages/core/src/config/types.ts b/packages/core/src/config/types.ts index 8b76641d4..a38476678 100644 --- a/packages/core/src/config/types.ts +++ b/packages/core/src/config/types.ts @@ -70,16 +70,12 @@ export interface UserServerConfig { } export interface UserPreviewServerConfig { - host?: string | boolean; - port?: number; - strictPort?: boolean; - open?: boolean; - // cors?: boolean | cors.Options; - headers?: OutgoingHttpHeaders; // write static output file output?: { path?: string; publicPath?: string }; distDir?: string; https?: SecureServerOptions; + port?: number; + host?: string | boolean; } export type NormalizedServerConfig = Required< @@ -129,8 +125,6 @@ export interface UserConfig { compilation?: Pick; /** config related to dev server */ server?: UserServerConfig; - /** config related to preview server */ - preview?: UserPreviewServerConfig; /** Files under this dir will always be treated as static assets. serve it in dev, and copy it to output.path when build */ logger?: Logger; } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c7ada1d99..bdba8dd60 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -28,7 +28,6 @@ import { import { handlerWatcher } from './watcher/index.js'; import type { FarmCliOptions } from './config/types.js'; -import { PreviewServer } from './server/preview.js'; export async function start( inlineConfig?: FarmCliOptions & UserConfig @@ -101,25 +100,7 @@ export async function build( } // TODO preview method -export async function preview( - inlineConfig?: FarmCliOptions & UserConfig -): Promise { - inlineConfig = inlineConfig ?? {}; - // setProcessEnv('production'); - - const previewServer = new PreviewServer(inlineConfig); - try { - await previewServer.createServer(); - - previewServer.listen(); - } catch (error) { - previewServer.logger.error('Failed to start the preview server', { - exit: false, - error - }); - } -} -// export async function preview(inlineConfig: FarmCliOptions & UserConfig = {}) {} +export async function preview(inlineConfig: FarmCliOptions & UserConfig = {}) {} export async function clean( rootPath: string, diff --git a/packages/core/src/server/preview.ts b/packages/core/src/server/preview.ts index f18e09e71..cb0ff5c3b 100644 --- a/packages/core/src/server/preview.ts +++ b/packages/core/src/server/preview.ts @@ -1,160 +1 @@ -import { ServerOptions } from 'node:https'; -import path from 'node:path'; -import connect from 'connect'; -import { resolveConfig } from '../config/index.js'; -import { mergeConfig } from '../config/mergeConfig.js'; -import { - FarmCliOptions, - ResolvedUserConfig, - UserConfig, - UserPreviewServerConfig -} from '../config/types.js'; -import { resolveServerUrls } from '../utils/http.js'; -import { Logger, printServerUrls } from '../utils/logger.js'; -import { CommonServerOptions, httpServer } from './http.js'; - -class PreviewServer extends httpServer { - previewOptions: UserPreviewServerConfig; - httpsOptions: ServerOptions; - publicPath?: string; - publicDir?: string; - resolvedUserConfig: ResolvedUserConfig; - logger: Logger; - middlewares: connect.Server; - - // TODO: add annotations - constructor(readonly inlineConfig: FarmCliOptions & UserConfig) { - super(); - } - - // TODO: move this method to base class, - // this function is duplicated with [Server]. - protected async httpServerStart(serverOptions: { - port: number; - strictPort: boolean | undefined; - host: string | undefined; - }): Promise { - if (!this.httpServer) { - throw new Error('httpServer is not initialized'); - } - - let { port, strictPort, host } = serverOptions; - - return new Promise((resolve, reject) => { - const onError = (e: Error & { code?: string }) => { - if (e.code === 'EADDRINUSE') { - if (strictPort) { - this.httpServer.removeListener('error', onError); - reject(new Error(`Port ${port} is already in use`)); - } else { - this.logger.info(`Port ${port} is in use, trying another one...`); - this.httpServer.listen(++port, host); - } - } else { - this.httpServer.removeListener('error', onError); - reject(e); - } - }; - - this.httpServer.on('error', onError); - - this.httpServer.listen(port, host, () => { - this.httpServer.removeListener('error', onError); - resolve(port); - }); - }); - } - async createServer() { - this.resolvedUserConfig = await resolveConfig( - this.inlineConfig, - 'preview', - 'production', - 'production' - ); - this.logger = this.resolvedUserConfig.logger; - - this.#resolvePreviewOptions(); - - this.httpsOptions = await this.resolveHttpsConfig( - this.previewOptions.https - ); - // this.publicFiles - this.middlewares = connect(); - // this.httpServer = this.previewOptions.middlewareMode - // ? null - // : await this.resolveHttpServer( - // this.previewOptions as CommonServerOptions, - // this.middlewares, - // this.httpsOptions - // ); - } - - async listen(): Promise { - if (!this.httpServer) { - throw new Error('Server not created'); - } - const { host, port, open, strictPort } = this.previewOptions; - - try { - await this.httpServerStart({ - port, - strictPort, - // TODO: Check hosts (Why is it a boolean?) - host: typeof host === 'string' ? host : undefined - }); - - await this.displayServerUrls(); - - if (open) { - // Run openBrowser function - // await this.openBrowser(port); - } - } catch (e) { - // this.logger.error(e); - // process.exit(1); - } - } - - #resolvePreviewOptions() { - this.previewOptions = mergeConfig( - this.resolvedUserConfig.server, - // @ts-ignore - this.resolvedUserConfig.preview - ); - - const { root, compilation, server } = this.resolvedUserConfig; - - const relativePath = - this.previewOptions.output.path || compilation.output.path; - const distDir = - this.previewOptions.distDir || path.resolve(root, relativePath); - this.publicPath = - this.previewOptions.output?.publicPath || compilation.output.publicPath; - this.publicDir = - this.previewOptions.distDir || compilation.assets.publicDir; - } - - // TODO: maybe migrate to utils? This method is - // duplicated with [Server] too. - async displayServerUrls() { - this.resolvedUrls = await resolveServerUrls( - this.httpServer, - this.resolvedUserConfig, - // this.publicPath - ); - - if (this.resolvedUrls) { - printServerUrls( - this.resolvedUrls, - this.previewOptions.host, - this.resolvedUserConfig.logger - ); - } else { - throw new Error( - 'cannot print server URLs before server.listen is called.' - ); - } - } -} - -export { PreviewServer }; +export {}; diff --git a/packages/core/src/types/swc-config.ts b/packages/core/src/types/swc-config.ts index aa2789a2c..947763da9 100644 --- a/packages/core/src/types/swc-config.ts +++ b/packages/core/src/types/swc-config.ts @@ -25,21 +25,21 @@ export interface ScriptParseConfig { } export interface ScriptDecoratorsConfig { - legacyDecorator?: boolean; - decoratorMetadata?: boolean; + legacyDecorator: boolean; + decoratorMetadata: boolean; /** * The version of the decorator proposal to use. 2021-12 or 2022-03 * @default 2021-12 */ - decoratorVersion?: '2021-12' | '2022-03' | null; + decoratorVersion: '2021-12' | '2022-03' | null; /** * @default [] */ - includes?: string[]; + includes: string[]; /** * @default ["node_modules/"] */ - excludes?: string[]; + excludes: string[]; } /** diff --git a/packages/runtime-plugin-hmr/src/index.ts b/packages/runtime-plugin-hmr/src/index.ts index 82f2c3f24..a1ec77ef3 100644 --- a/packages/runtime-plugin-hmr/src/index.ts +++ b/packages/runtime-plugin-hmr/src/index.ts @@ -1,7 +1,6 @@ /** * HMR client as a Farm Runtime Plugin */ -import type { Plugin } from '@farmfe/runtime'; import { HmrClient } from './hmr-client'; import { createHotContext } from './hot-module-state'; @@ -9,11 +8,11 @@ let hmrClient: HmrClient; export default { name: 'farm-runtime-hmr-client-plugin', - bootstrap(moduleSystem) { + bootstrap(moduleSystem: any) { hmrClient = new HmrClient(moduleSystem); hmrClient.connect(); }, - moduleCreated(module) { + moduleCreated(module: any) { // create a hot context for each module module.meta.hot = createHotContext(module.id, hmrClient); } diff --git a/packages/runtime-plugin-hmr/src/overlay.ts b/packages/runtime-plugin-hmr/src/overlay.ts index 7633a5043..d07462424 100644 --- a/packages/runtime-plugin-hmr/src/overlay.ts +++ b/packages/runtime-plugin-hmr/src/overlay.ts @@ -398,7 +398,7 @@ hue-6-2: #e6c07b const errorAlert = ( message: string, description: string, - type: string + _type: string ) => /*html*/ `
@@ -425,7 +425,7 @@ const warnAlert = (description: string, type = 'warn') => /*html*/ ` `; const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g; -const codeframeRE = /^(?:>?\s*\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm; +// const codeframeRE = /^(?:>?\s*\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm; // Allow `ErrorOverlay` to extend `HTMLElement` even in environments where // `HTMLElement` was not originally defined. @@ -527,7 +527,7 @@ export class ErrorOverlay extends HTMLElement { return hljs.highlightAuto(code).value; } - renderMessages(messages: any[], links: boolean) { + renderMessages(messages: any[], _link: any) { const messageContainer = this.root.querySelector('.message-container')!; messageContainer.innerHTML = ''; if (typeof messages === 'string') { @@ -570,7 +570,7 @@ export class ErrorOverlay extends HTMLElement { return; } - messages.forEach((msg, index) => { + messages.forEach((msg) => { const messageElement = document.createElement('div'); messageElement.className = 'error-message'; msg = parseIfJSON(msg); diff --git a/packages/runtime-plugin-import-meta/src/index.ts b/packages/runtime-plugin-import-meta/src/index.ts index 1a92ec465..c7779557f 100644 --- a/packages/runtime-plugin-import-meta/src/index.ts +++ b/packages/runtime-plugin-import-meta/src/index.ts @@ -1,4 +1,4 @@ -import type { ModuleSystem, Plugin } from '@farmfe/runtime'; +import type { ModuleSystem } from '@farmfe/runtime'; const __global_this__ = typeof globalThis !== 'undefined' ? globalThis : window; @@ -8,7 +8,7 @@ export default { bootstrap(system: ModuleSystem) { this._moduleSystem = system; }, - moduleCreated(module) { + moduleCreated(module: any) { const publicPath = this._moduleSystem.publicPaths?.[0] || ""; const isSSR = this._moduleSystem.targetEnv === "node"; const { location } = __global_this__; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e1159acd3..af8cc2f3e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -844,7 +844,7 @@ importers: version: 10.1.2(chokidar@3.6.0)(typescript@5.4.5) '@nestjs/testing': specifier: ^10.0.0 - version: 10.3.10(@nestjs/common@10.3.10(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/core@10.3.10)(@nestjs/platform-express@10.3.10) + version: 10.3.10(@nestjs/common@10.3.10(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/core@10.3.10(@nestjs/common@10.3.10(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/platform-express@10.3.10)(encoding@0.1.13)(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/platform-express@10.3.10(@nestjs/common@10.3.10(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/core@10.3.10)) '@types/express': specifier: ^4.17.17 version: 4.17.21 @@ -2319,7 +2319,7 @@ importers: version: 1.17.6(vite@5.2.8(@types/node@22.5.0)(less@4.2.0)(lightningcss@1.25.1)(sass@1.74.1)(terser@5.31.1)) vite-plugin-vue-inspector: specifier: /Users/adny/vue/vite-plugin-vue-inspector/packages/core - version: link:../../../../../../../Users/adny/vue/vite-plugin-vue-inspector/packages/core + version: link:../../../../vue/vite-plugin-vue-inspector/packages/core examples/x-data-spreadsheet: dependencies: @@ -25278,7 +25278,7 @@ snapshots: transitivePeerDependencies: - chokidar - '@nestjs/testing@10.3.10(@nestjs/common@10.3.10(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/core@10.3.10)(@nestjs/platform-express@10.3.10)': + '@nestjs/testing@10.3.10(@nestjs/common@10.3.10(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/core@10.3.10(@nestjs/common@10.3.10(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/platform-express@10.3.10)(encoding@0.1.13)(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/platform-express@10.3.10(@nestjs/common@10.3.10(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/core@10.3.10))': dependencies: '@nestjs/common': 10.3.10(reflect-metadata@0.2.2)(rxjs@7.8.1) '@nestjs/core': 10.3.10(@nestjs/common@10.3.10(reflect-metadata@0.2.2)(rxjs@7.8.1))(@nestjs/platform-express@10.3.10)(encoding@0.1.13)(reflect-metadata@0.2.2)(rxjs@7.8.1) diff --git a/rust-plugins/sass/src/lib.rs b/rust-plugins/sass/src/lib.rs index da0a97f73..06ac3f054 100755 --- a/rust-plugins/sass/src/lib.rs +++ b/rust-plugins/sass/src/lib.rs @@ -165,12 +165,12 @@ impl Importer for ImporterCollection { url } else { Url::from_file_path(url) - .map_err(|_| Exception::new(format!("parse raw {:?} to Url failed.", url)))? + .map_err(|_| Exception::new(format!("parse raw {url:?} to Url failed.")))? } } else { let resolved_path = RelativePath::new(url).to_logical_path(&self.context.config.root); Url::from_file_path(&resolved_path) - .map_err(|_| Exception::new(format!("parse {:?} to Url failed.", resolved_path)))? + .map_err(|_| Exception::new(format!("parse {resolved_path:?} to Url failed.")))? }; Ok(Some(url)) @@ -330,7 +330,7 @@ fn get_os() -> &'static str { "linux" => "linux", "macos" => "darwin", "windows" => "win32", - os => panic!("dart-sass-embed is not supported OS: {}", os), + os => panic!("dart-sass-embed is not supported OS: {os}"), } } @@ -339,7 +339,7 @@ fn get_arch() -> &'static str { "x86" => "ia32", "x86_64" => "x64", "aarch64" => "arm64", - arch => panic!("dart-sass-embed is not supported arch: {}", arch), + arch => panic!("dart-sass-embed is not supported arch: {arch}"), } } diff --git a/rust-plugins/sass/src/rebase_urls.rs b/rust-plugins/sass/src/rebase_urls.rs index 72c88f613..97a6ac766 100644 --- a/rust-plugins/sass/src/rebase_urls.rs +++ b/rust-plugins/sass/src/rebase_urls.rs @@ -169,7 +169,7 @@ mod tests { fn replace() { let content = "a { b: url('c'); d: url('e');".to_string(); let result = super::replace(content, &CSS_URL_RE, |raw, matched| { - return Ok(raw.replace(matched, "'matched'")); + Ok(raw.replace(matched, "'matched'")) }) .unwrap(); diff --git a/rust-plugins/sass/tests/mod.rs b/rust-plugins/sass/tests/mod.rs index c2161a853..3db9df97b 100755 --- a/rust-plugins/sass/tests/mod.rs +++ b/rust-plugins/sass/tests/mod.rs @@ -3,8 +3,7 @@ use std::{collections::HashMap, fs, io::Write, path::PathBuf, sync::Arc}; use farmfe_compiler::Compiler; use farmfe_core::{ config::{ - bool_or_obj::BoolOrObj, preset_env::PresetEnvConfig, Config, ResolveConfig, RuntimeConfig, - SourcemapConfig, + bool_or_obj::BoolOrObj, preset_env::PresetEnvConfig, AliasItem, Config, ResolveConfig, RuntimeConfig, SourcemapConfig, StringOrRegex }, context::CompilationContext, module::ModuleType, @@ -62,7 +61,7 @@ fn normalize_css(css: &str) -> String { #[test] fn test_with_compiler() { fixture!("tests/fixtures/**/*/index.scss", |file, crate_path| { - println!("testing: {:?}", file); + println!("testing: {file:?}"); let resolved_path = file.to_string_lossy().to_string(); let cwd = file.parent().unwrap(); let runtime_path = crate_path @@ -87,10 +86,12 @@ fn test_with_compiler() { tree_shaking: Box::new(BoolOrObj::Bool(false)), progress: false, resolve: Box::new(ResolveConfig { - alias: std::collections::HashMap::from([( - "@".to_string(), - cwd.to_string_lossy().to_string(), - )]), + alias: vec![ + AliasItem::Complex { + find: StringOrRegex::String("@".to_string()), + replacement: cwd.to_string_lossy().to_string(), + }, + ], ..Default::default() }), ..Default::default()