use std::{borrow::Cow, sync::Arc}; use crate::transformer::Ast; use parcel_core::*; pub mod hmr; mod library_packager; pub mod packager; mod runtime_modules; mod transformer; pub use runtime_modules::{RuntimeModule, runtime_module}; pub use transformer::JsTransformer; struct JsContent { source_size: usize, output: JsOutput, shebang: Option, directives: Vec, rsc_runtime_dep: Option, needs_filename: bool, needs_dirname: bool, /// See `crate::transformer::async_module::wrap_async_module`. esm_prologue_len: usize, /// Whether the packager wraps the module for React Refresh (see `transformer::refresh`). react_refresh: bool, } /// What a JS asset is packaged from. enum JsOutput { /// The AST, for builds whose packaging transforms it: tree shaking in production builds, /// libraries, and classic scripts (see `JsContent::keeps_ast`). Ast { ast: Ast, /// The map from an earlier transformer, composed into this asset's generated map when /// packaging. input_source_map: Option, }, /// Code generated by the transformer, which development builds package as is, so they keep /// neither the AST nor its source map in memory, and only generate each module's code once. Code(GeneratedCode), } /// A module's code, generated when it was transformed. #[derive(Clone)] struct GeneratedCode { /// Shared, so that bundles reference it rather than copying it (see `ChunkedText`). code: Arc, /// The source map of `code`, composed with the asset's input map, and without a `sourceRoot`, /// which depends on the bundle (see `bundle_source_root`). map: Option>, /// The offset of an empty line in `code` after the module's ESM prologue, where the module waits /// for its imports if it's async (see `wrap_async_module`). None if the prologue is empty, so /// the module waits before its code. prologue_end: Option, } impl GeneratedCode { /// Generates code for `ast`, which the JS transformer finalized, taking its comments as it prints /// them. fn new( mut ast: Ast, input_source_map: Option<&InputSourceMap>, source_maps: bool, esm_prologue_len: usize, ) -> Result { // With an empty line after the prologue, where the module waits for its imports if it's async. let (code, map, prologue_end) = if esm_prologue_len > 0 { let (code, map, at) = ast.to_code_split(source_maps, None, false, esm_prologue_len)?; (code, map, Some(at)) } else { let (code, map) = ast.to_code_with(&ast.comments, source_maps, None, false)?; (code, map, None) }; let map = compose_input_source_map(&ast, map, input_source_map, None)?; drop(ast); let code = String::from_utf8(code).map_err(|e| Diagnostic::from_message(e.to_string()))?; Ok(GeneratedCode { code: code.into(), map: map.map(Into::into), prologue_end, }) } } /// `map`, generated for `ast`, composed through the asset's input map, if any. fn compose_input_source_map( ast: &Ast, map: Option, input_source_map: Option<&InputSourceMap>, source_root: Option<&str>, ) -> Result, DiagnosticList> { let (Some(map), Some(input)) = (map.as_ref(), input_source_map) else { return Ok(map); }; // The parser registers the asset's own file first; macros may add more. let source = ast.source_map.files().first().map(|f| f.name.to_string()); Ok(Some(match source { Some(source) => compose_source_map(map, &source, input, source_root)?, None => map.clone(), })) } impl JsContent { /// Whether an asset is packaged from its AST, rather than from code generated when it's /// transformed (see `JsOutput`). fn keeps_ast(target: &Target) -> bool { target .flags .intersects(EnvironmentFlags::SHOULD_OPTIMIZE | EnvironmentFlags::IS_LIBRARY) || target.source_type == SourceType::Script } /// The asset's generated code, for unoptimized output, which wraps it as text: the code generated /// when it was transformed, or else code generated from its AST now. fn generated_code(&self, source_maps: bool) -> Result, DiagnosticList> { match &self.output { JsOutput::Code(generated) => Ok(Cow::Borrowed(generated)), JsOutput::Ast { ast, input_source_map, } => { // Printing takes the program apart and takes its comments, so it prints a copy. Ok(Cow::Owned(GeneratedCode::new( ast.clone(), input_source_map.as_ref(), source_maps, self.esm_prologue_len, )?)) } } } /// The asset's AST, for packaging that transforms it. fn ast(&self) -> Result<&Ast, DiagnosticList> { match &self.output { JsOutput::Ast { ast, .. } => Ok(ast), JsOutput::Code(_) => Err( Diagnostic::from_message( "A JS asset was transformed for development, but packaged for a build that needs its AST" .into(), ) .into(), ), } } /// Generates code for `ast`, this asset's AST, possibly modified for packaging, with its source /// map composed through the asset's input map. The map's `sources` are relative to the project /// root, which `source_root` is the path to (see `bundle_source_root`). fn to_code( &self, ast: &Ast, source_maps: bool, source_root: Option<&str>, minify: bool, ) -> Result<(Vec, Option), DiagnosticList> { let JsOutput::Ast { input_source_map, .. } = &self.output else { unreachable!("packaged from an AST, so it kept one (see `JsContent::ast`)"); }; let (code, map) = ast.to_code(source_maps, source_root, minify)?; let map = compose_input_source_map(ast, map, input_source_map.as_ref(), source_root)?; Ok((code, map)) } } impl std::fmt::Debug for JsContent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "JsContent") } } impl Content for JsContent { fn estimate_size(&self) -> Result { Ok(self.source_size) } fn read(&self) -> Result, Diagnostic> { match &self.output { JsOutput::Ast { ast, .. } => { let (code, _) = ast.to_code(false, None, false)?; Ok(code) } JsOutput::Code(generated) => Ok(generated.code.as_bytes().to_vec()), } } fn ty(&self) -> ContentType { parcel_core::content_type!("JsContent") } fn bundle_dependencies(&self, bundle_graph: &BundleGraph, bundle: &Bundle) -> Vec { packager::bundle_dependencies(bundle_graph, bundle) } fn embedded_assets(&self, bundle_graph: &BundleGraph, bundle: &Bundle) -> Vec { packager::embedded_assets(bundle_graph, bundle) } fn package( &self, bundle_graph: &BundleGraph, bundle: &Bundle, get_inline_bundle_content: &dyn Fn(usize) -> Result, DiagnosticList>, options: &ParcelOptions, ) -> Result, DiagnosticList> { if bundle.target.flags.contains(EnvironmentFlags::IS_LIBRARY) { self.package_library(bundle_graph, bundle, get_inline_bundle_content, options) } else { self.package_app(bundle_graph, bundle, get_inline_bundle_content, options) } } }