use either::Either; use glob_match::glob_match; use indexmap::IndexMap; use serde::Deserialize; use std::{borrow::Cow, collections::HashSet, ffi::OsStr, path::Path, slice, sync::Arc}; use crate::{ Diagnostic, DiagnosticList, FileSystem, ImportType, PathId, SourceUrl, bundler::Bundler, namer::Namer, optimizer::Optimizer, reporter::Reporter, resolver::Resolver, transformer::Transformer, }; pub struct ParcelConfig { pub resolvers: Vec>, pub transformers: PipelineMap, pub bundler: Arc, pub namers: Vec>, pub optimizers: PipelineMap, pub compressors: PipelineMap<()>, pub reporters: Vec>, } impl ParcelConfig { pub fn read( fs: &dyn FileSystem, path: PathId, factory: &dyn PluginFactory, ) -> Result { let content = fs.read(path)?; Self::from_json(path, &content, factory) } pub fn from_json( path: PathId, json: &[u8], factory: &dyn PluginFactory, ) -> Result { // Parsed as JSON5, as in Parcel 2, so that configs may have comments. let raw: RawParcelConfig = json5::from_str(std::str::from_utf8(json)?) .map_err(|err| Diagnostic::from(err).with_url(&SourceUrl::from_path(&path)))?; raw.resolve(factory, path) } } pub struct PipelineMap(pub Vec<(String, Vec>)>); impl Default for PipelineMap { fn default() -> Self { PipelineMap(Vec::new()) } } #[derive(Default)] pub struct Plugin { pub package_name: String, pub key_path: Option, pub plugin: Arc, } impl Clone for Plugin { fn clone(&self) -> Self { Plugin { package_name: self.package_name.clone(), key_path: self.key_path.clone(), plugin: self.plugin.clone(), } } } impl PartialEq for Plugin { fn eq(&self, other: &Self) -> bool { self.package_name == other.package_name } } impl std::fmt::Debug for Plugin { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.package_name.fmt(f) } } #[derive(Clone)] pub enum PipelineNode { Plugin(Arc), Spread, } impl PipelineMap { pub fn get<'a, P: AsRef>( &'a self, path: Cow<'a, str>, pipeline: &Option

, ) -> Pipeline<'a, T> { let basename = Path::new(&*path) .file_name() .unwrap_or_else(|| OsStr::new(&*path)) .to_str() .unwrap() .to_owned(); let current = pipeline.as_ref().and_then(|pipeline| { self .0 .iter() .find(|(pattern, _)| is_match(pattern, &path, &basename, pipeline.as_ref())) .map(|(_, pipeline)| pipeline.iter()) }); Pipeline { pipelines: &self.0, path, basename: basename, // A missing named pipeline must not fall back to a default pipeline. pipeline_index: if pipeline.is_some() && current.is_none() { self.0.len() } else { 0 }, current, stack: Vec::new(), seen: HashSet::new(), } } /// Like `get`, but a named pipeline that has no entry for `path` falls back to the unnamed /// patterns rather than to no plugins. For optimizers: a bundle whose main asset was imported /// through a named pipeline, e.g. `url:./image.png`, is optimized like any other unless the /// config gives that pipeline its own optimizers. pub fn get_or_unnamed<'a, P: AsRef>( &'a self, path: Cow<'a, str>, pipeline: &Option

, ) -> Pipeline<'a, T> { let pipeline = pipeline .as_ref() .map(|pipeline| pipeline.as_ref()) .filter(|pipeline| { let basename = Path::new(&*path) .file_name() .and_then(OsStr::to_str) .unwrap_or(&path); self .0 .iter() .any(|(pattern, _)| is_match(pattern, &path, basename, pipeline)) }); self.get(path, &pipeline) } /// The pipeline to transform the file at `path` with when it is imported as `import_type`, given /// the `pipeline` it was resolved with. A JavaScript import without a named pipeline uses the /// `js` pipeline where one applies, e.g. to turn JSON into a module. A JavaScript import must /// also have a transformer, or the file would become an empty module, so it is an error if the /// pipeline has none. That includes a pattern configured with no plugins, e.g. `"*.zip": []`. /// Other imports, such as URLs, can reference any file as is. pub fn import_pipeline( &self, path: &str, pipeline: Option, import_type: ImportType, ) -> Result, Diagnostic> { if import_type != ImportType::JavaScript { return Ok(pipeline); } let has_plugins = |pipeline: &Option<&str>| self.get(Cow::Borrowed(path), pipeline).next().is_some(); if pipeline.is_none() && has_plugins(&Some("js")) { return Ok(Some("js".into())); } if has_plugins(&pipeline.as_deref()) { return Ok(pipeline); } Err(Diagnostic { origin: Some("@parcel/core".into()), ..Diagnostic::from_message(format!( "No transformers found for {}{}.", path, pipeline .map(|pipeline| format!(" with pipeline: '{}'", pipeline)) .unwrap_or_default() )) }) } pub fn named_pipelines(&self) -> impl Iterator { self .0 .iter() .filter_map(|(glob, _)| glob.split_once(':').map(|g| g.0)) } } fn is_match(pattern: &str, path: &str, basename: &str, pipeline: &str) -> bool { let (pattern_pipeline, glob) = pattern.split_once(':').unwrap_or(("", pattern)); pipeline == pattern_pipeline && (glob_match(glob, basename) || glob_match(glob, path)) } pub struct Pipeline<'a, T: ?Sized> { pipelines: &'a [(String, Vec>)], pipeline_index: usize, path: Cow<'a, str>, basename: String, current: Option>>, stack: Vec>>, seen: HashSet<*const T>, } impl<'a, T: ?Sized> Pipeline<'a, T> { pub fn change_type(&mut self, path: String, pipeline: &mut Option) { self.basename = Path::new(&path) .file_name() .unwrap_or_else(|| OsStr::new(&path)) .to_str() .unwrap() .to_owned(); self.path = Cow::Owned(path); self.stack.clear(); self.current = pipeline.as_ref().and_then(|pipeline| { self .pipelines .iter() .find(|(pattern, _)| is_match(pattern, &self.path, &self.basename, pipeline.as_ref())) .map(|(_, pipeline)| pipeline.iter()) }); // For type changes, we do fall back to a default pipeline if a named pipeline does not exist. self.pipeline_index = 0; if pipeline.is_some() && self.current.is_none() { *pipeline = None; } } fn next_pipeline(&mut self) -> Option<&'a [PipelineNode]> { while let Some((pattern, pipeline)) = self.pipelines.get(self.pipeline_index) { self.pipeline_index += 1; if is_match(pattern, &self.path, &self.basename, "") { return Some(pipeline); } } None } } impl Iterator for Pipeline<'_, T> { type Item = Arc; fn next(&mut self) -> Option { loop { if self.current.is_none() { self.current = Some(self.next_pipeline()?.iter()); } match self.current.as_mut().unwrap().next() { Some(PipelineNode::Plugin(plugin)) => { if self.seen.insert(Arc::as_ptr(plugin)) { return Some(plugin.clone()); } } Some(PipelineNode::Spread) => { if let Some(pipeline) = self.next_pipeline() { self.stack.push(self.current.take().unwrap()); self.current = Some(pipeline.iter()); } } None => { if let Some(parent) = self.stack.pop() { self.current = Some(parent); } else { return None; } } } } } } // impl Default for ParcelConfig { // fn default() -> Self { // ParcelConfig { // transformers: PipelineMap(indexmap! { // "*.{js,mjs,jsm,jsx,es6,ts,tsx}".into() => vec![PipelineNode::Plugin(PluginNode { // package_name: "@parcel/transformer-js".into(), // resolve_from: "/".into(), // key_path: None // })], // }), // resolvers: vec![], // bundler: PluginNode { // package_name: "@parcel/bundler-default".into(), // resolve_from: "/".into(), // key_path: None, // }, // namers: vec![], // runtimes: vec![], // optimizers: PipelineMap(indexmap! {}), // packagers: indexmap! {}, // validators: PipelineMap(indexmap! {}), // compressors: PipelineMap(indexmap! {}), // reporters: vec![], // } // } // } #[derive(serde::Deserialize)] #[serde(untagged)] enum PluginWithConfig { Plugin(String), Config { plugin: String, config: serde_json::Value, }, } impl PluginWithConfig { fn plugin(&self) -> &str { match self { PluginWithConfig::Plugin(p) => p, PluginWithConfig::Config { plugin, .. } => plugin, } } fn resolve< T: ?Sized, F: Fn(&str, Option) -> Result, DiagnosticList>, DiagnosticList, >( self, factory: &F, ) -> Result, DiagnosticList> { match self { PluginWithConfig::Plugin(plugin) => factory(&plugin, None), PluginWithConfig::Config { plugin, config } => factory(&plugin, Some(config)), } } } #[derive(Deserialize)] struct RawParcelConfig { extends: Option, resolvers: Option, transformers: Option, bundler: Option, namers: Option, optimizers: Option, reporters: Option, } #[derive(Deserialize)] #[serde(untagged)] enum ParcelConfigExtends { String(String), Array(Vec), } #[derive(Default, Deserialize)] #[serde(transparent)] struct RawPipeline(Vec); #[derive(Default, Deserialize)] #[serde(transparent)] struct RawPipelineMap(IndexMap); pub trait PluginFactory { fn config(&self, specifier: &str, from: PathId) -> Result; fn resolver( &self, name: &str, config: Option, from: PathId, ) -> Result, DiagnosticList>; fn transformer( &self, name: &str, config: Option, from: PathId, ) -> Result, DiagnosticList>; fn bundler( &self, name: &str, config: Option, from: PathId, ) -> Result, DiagnosticList>; fn namer( &self, name: &str, config: Option, from: PathId, ) -> Result, DiagnosticList>; fn optimizer( &self, name: &str, config: Option, from: PathId, ) -> Result, DiagnosticList>; fn reporter( &self, name: &str, config: Option, from: PathId, ) -> Result, DiagnosticList>; /// Warnings found while loading plugins, e.g. a plugin with no `engines.parcel` /// range. They are logged once the reporters are ready. fn take_warnings(&self) -> Vec { Vec::new() } } impl RawParcelConfig { fn resolve( self, factory: &dyn PluginFactory, from: PathId, ) -> Result { let extends = match self.extends { None => Vec::new(), Some(ParcelConfigExtends::String(e)) => vec![factory.config(&e, from)?], Some(ParcelConfigExtends::Array(a)) => a .into_iter() .map(|e| factory.config(&e, from)) .collect::>()?, }; let mut transformers = self .transformers .unwrap_or_default() .resolve(&|name, config| factory.transformer(name, config, from))?; let mut optimizers = self .optimizers .unwrap_or_default() .resolve(&|name, config| factory.optimizer(name, config, from))?; let bundler = if let Some(bundler) = self.bundler { Some(bundler.resolve(&|name, config| factory.bundler(name, config, from))?) } else { extends.get(0).map(|e| e.bundler.clone()) } .ok_or_else(|| Diagnostic::from_message("Config does not have a bundler".into()))?; let mut extended_resolvers = Vec::new(); let mut extended_namers = Vec::new(); let mut extended_reporters = Vec::new(); for config in extends { extended_resolvers.extend(config.resolvers); extended_namers.extend(config.namers); extended_reporters.extend(config.reporters); transformers.0.extend(config.transformers.0); optimizers.0.extend(config.optimizers.0); } Ok(ParcelConfig { resolvers: self.resolvers.unwrap_or_default().resolve_extended( &|name, config| factory.resolver(name, config, from), extended_resolvers.into_iter(), )?, transformers, bundler: bundler, namers: self.namers.unwrap_or_default().resolve_extended( &|name, config| factory.namer(name, config, from), extended_namers.into_iter(), )?, optimizers, compressors: Default::default(), reporters: self.reporters.unwrap_or_default().resolve_extended( &|name, config| factory.reporter(name, config, from), extended_reporters.into_iter(), )?, }) } } impl RawPipeline { fn resolve< T: ?Sized, F: Fn(&str, Option) -> Result, DiagnosticList>, >( self, factory: &F, ) -> Result>, DiagnosticList> { self .0 .into_iter() .map(|pkg| { if pkg.plugin() == "..." { Ok(PipelineNode::Spread) } else { Ok(PipelineNode::Plugin(pkg.resolve(factory)?)) } }) .collect() } fn resolve_extended< T: ?Sized, F: Fn(&str, Option) -> Result, DiagnosticList>, >( self, factory: &F, extends: impl Iterator>, ) -> Result>, DiagnosticList> { if self.0.is_empty() { return Ok(extends.collect()); } let mut ext = Some(extends); self .0 .into_iter() .flat_map(|pkg| { if pkg.plugin() == "..." { if let Some(ext) = std::mem::take(&mut ext) { Either::Left(ext.map(Ok)) } else { todo!() } } else { Either::Right(std::iter::once(pkg.resolve(factory))) } }) .collect() } } impl RawPipelineMap { fn resolve< T: ?Sized, F: Fn(&str, Option) -> Result, DiagnosticList>, >( self, factory: &F, ) -> Result, DiagnosticList> { Ok(PipelineMap( self .0 .into_iter() .map(|(key, pipeline)| { // TODO: error on reserved named pipeline let pipeline = pipeline.resolve(factory)?; Ok((key, pipeline)) }) .collect::>()?, )) } } #[cfg(test)] mod tests { use super::*; fn plugin(name: &str) -> PipelineNode { PipelineNode::Plugin(Arc::from(name)) } fn names(pipeline: Pipeline<'_, str>) -> Vec { pipeline.map(|plugin| plugin.to_string()).collect() } #[test] fn recursively_expands_matching_pipelines_at_spreads() { let pipelines = PipelineMap(vec![ ( "*.js".into(), vec![plugin("first"), PipelineNode::Spread, plugin("last")], ), ( "*.js".into(), vec![plugin("second"), PipelineNode::Spread, plugin("fourth")], ), ("src/*.js".into(), vec![plugin("third")]), ]); assert_eq!( names(pipelines.get::<&str>("src/app.js".into(), &None)), ["first", "second", "third", "fourth", "last"] ); } #[test] fn expands_defaults_from_a_named_pipeline() { let pipelines = PipelineMap(vec![ ( "custom:*.js".into(), vec![plugin("named"), PipelineNode::Spread], ), ("*.js".into(), vec![plugin("default")]), ]); assert_eq!( names(pipelines.get("app.js".into(), &Some("custom"))), ["named", "default"] ); assert!( pipelines .get("app.js".into(), &Some("missing")) .next() .is_none() ); } #[test] fn get_or_unnamed_falls_back_when_a_named_pipeline_has_no_entry() { let pipelines = PipelineMap(vec![ ( "data-url:*".into(), vec![PipelineNode::Spread, plugin("data-url")], ), ("*.png".into(), vec![plugin("image")]), ]); assert_eq!( names(pipelines.get_or_unnamed("a.png".into(), &Some("url"))), ["image"] ); assert_eq!( names(pipelines.get_or_unnamed("a.png".into(), &Some("data-url"))), ["image", "data-url"] ); assert_eq!( names(pipelines.get_or_unnamed::<&str>("a.png".into(), &None)), ["image"] ); } #[test] fn import_pipeline_requires_a_transformer_for_javascript_imports() { let pipelines = PipelineMap(vec![ ("js:*.json".into(), vec![plugin("json")]), ("*.js".into(), vec![plugin("js")]), ("*.zip".into(), vec![]), ]); let import = |path: &str, import_type| pipelines.import_pipeline(path, None, import_type); // JSON imported from JavaScript becomes a module; as a URL it is referenced as is. assert_eq!( import("data.json", ImportType::JavaScript).unwrap(), Some("js".into()) ); assert_eq!(import("data.json", ImportType::Url).unwrap(), None); assert_eq!(import("app.js", ImportType::JavaScript).unwrap(), None); // An empty pipeline, or no pattern at all, can't turn a file into JavaScript. assert_eq!( import("archive.zip", ImportType::JavaScript) .unwrap_err() .message, "No transformers found for archive.zip." ); assert!(import("image.png", ImportType::JavaScript).is_err()); assert_eq!(import("archive.zip", ImportType::Url).unwrap(), None); } #[test] fn change_type_continues_after_seen_plugins() { let pipelines = PipelineMap(vec![( "*.{js,css}".into(), vec![plugin("type-changer"), plugin("after")], )]); let mut pipeline = pipelines.get::<&str>("app.js".into(), &None); assert_eq!(pipeline.next().unwrap().as_ref(), "type-changer"); pipeline.change_type("app.css".into(), &mut None); assert_eq!(names(pipeline), ["after"]); } #[test] fn change_type_preserves_the_first_named_plugin() { let pipelines = PipelineMap(vec![ ( "custom:*.css".into(), vec![plugin("named-first"), plugin("named-second")], ), ("*.js".into(), vec![plugin("type-changer")]), ("*.css".into(), vec![plugin("default")]), ]); let mut pipeline = pipelines.get::<&str>("app.js".into(), &None); pipeline.next(); let mut named_pipeline = Some(hstr::Atom::from("custom")); pipeline.change_type("app.css".into(), &mut named_pipeline); assert_eq!(names(pipeline), ["named-first", "named-second"]); } #[test] fn change_type_falls_back_when_named_pipeline_is_missing() { let pipelines = PipelineMap(vec![ ("*.js".into(), vec![plugin("type-changer")]), ("*.css".into(), vec![plugin("default")]), ]); let mut pipeline = pipelines.get::<&str>("app.js".into(), &None); pipeline.next(); let mut named_pipeline = Some(hstr::Atom::from("missing")); pipeline.change_type("app.css".into(), &mut named_pipeline); assert!(named_pipeline.is_none()); assert_eq!(names(pipeline), ["default"]); } }