react-code-dataset
/
next.js
/turbopack
/crates
/turbopack-ecmascript
/src
/references
/external_module.rs
| use std::{fmt::Display, io::Write}; | |
| use anyhow::Result; | |
| use serde::{Deserialize, Serialize}; | |
| use turbo_rcstr::{RcStr, rcstr}; | |
| use turbo_tasks::{NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, Vc, trace::TraceRawVcs}; | |
| use turbo_tasks_fs::{ | |
| FileContent, FileSystem, FileSystemPath, VirtualFileSystem, glob::Glob, rope::RopeBuilder, | |
| }; | |
| use turbopack_core::{ | |
| asset::{Asset, AssetContent}, | |
| chunk::{AsyncModuleInfo, ChunkItem, ChunkType, ChunkableModule, ChunkingContext}, | |
| context::AssetContext, | |
| ident::{AssetIdent, Layer}, | |
| module::Module, | |
| module_graph::ModuleGraph, | |
| raw_module::RawModule, | |
| reference::{ModuleReference, ModuleReferences, TracedModuleReference}, | |
| reference_type::ReferenceType, | |
| resolve::parse::Request, | |
| }; | |
| use crate::{ | |
| EcmascriptModuleContent, | |
| chunk::{ | |
| EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, | |
| EcmascriptChunkType, EcmascriptExports, | |
| }, | |
| references::async_module::{AsyncModule, OptionAsyncModule}, | |
| runtime_functions::{ | |
| TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_EXTERNAL_IMPORT, TURBOPACK_EXTERNAL_REQUIRE, | |
| TURBOPACK_LOAD_BY_URL, | |
| }, | |
| utils::StringifyJs, | |
| }; | |
| pub enum CachedExternalType { | |
| CommonJs, | |
| EcmaScriptViaRequire, | |
| EcmaScriptViaImport, | |
| Global, | |
| Script, | |
| } | |
| /// Whether to add a traced reference to the external module using the given context and resolve | |
| /// origin. | |
| pub enum CachedExternalTracingMode { | |
| Untraced, | |
| Traced { | |
| externals_context: ResolvedVc<Box<dyn AssetContext>>, | |
| root_origin: FileSystemPath, | |
| }, | |
| } | |
| impl Display for CachedExternalType { | |
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
| match self { | |
| CachedExternalType::CommonJs => write!(f, "cjs"), | |
| CachedExternalType::EcmaScriptViaRequire => write!(f, "esm_require"), | |
| CachedExternalType::EcmaScriptViaImport => write!(f, "esm_import"), | |
| CachedExternalType::Global => write!(f, "global"), | |
| CachedExternalType::Script => write!(f, "script"), | |
| } | |
| } | |
| } | |
| pub struct CachedExternalModule { | |
| request: RcStr, | |
| external_type: CachedExternalType, | |
| tracing_mode: CachedExternalTracingMode, | |
| } | |
| impl CachedExternalModule { | |
| pub fn new( | |
| request: RcStr, | |
| external_type: CachedExternalType, | |
| tracing_mode: CachedExternalTracingMode, | |
| ) -> Vc<Self> { | |
| Self::cell(CachedExternalModule { | |
| request, | |
| external_type, | |
| tracing_mode, | |
| }) | |
| } | |
| pub fn content(&self) -> Result<Vc<EcmascriptModuleContent>> { | |
| let mut code = RopeBuilder::default(); | |
| match self.external_type { | |
| CachedExternalType::EcmaScriptViaImport => { | |
| writeln!( | |
| code, | |
| "const mod = await {TURBOPACK_EXTERNAL_IMPORT}({});", | |
| StringifyJs(&self.request) | |
| )?; | |
| } | |
| CachedExternalType::Global => { | |
| if self.request.is_empty() { | |
| writeln!(code, "const mod = {{}};")?; | |
| } else { | |
| writeln!( | |
| code, | |
| "const mod = globalThis[{}];", | |
| StringifyJs(&self.request) | |
| )?; | |
| } | |
| } | |
| CachedExternalType::Script => { | |
| // Parse the request format: "variableName@url" | |
| // e.g., "foo@https://test.test.com" | |
| if let Some(at_index) = self.request.find('@') { | |
| let variable_name = &self.request[..at_index]; | |
| let url = &self.request[at_index + 1..]; | |
| // Wrap the loading and variable access in a try-catch block | |
| writeln!(code, "let mod;")?; | |
| writeln!(code, "try {{")?; | |
| // First load the URL | |
| writeln!( | |
| code, | |
| " await {TURBOPACK_LOAD_BY_URL}({});", | |
| StringifyJs(url) | |
| )?; | |
| // Then get the variable from global with existence check | |
| writeln!( | |
| code, | |
| " if (typeof global[{}] === 'undefined') {{", | |
| StringifyJs(variable_name) | |
| )?; | |
| writeln!( | |
| code, | |
| " throw new Error('Variable {} is not available on global object after \ | |
| loading {}');", | |
| StringifyJs(variable_name), | |
| StringifyJs(url) | |
| )?; | |
| writeln!(code, " }}")?; | |
| writeln!(code, " mod = global[{}];", StringifyJs(variable_name))?; | |
| // Catch and re-throw errors with more context | |
| writeln!(code, "}} catch (error) {{")?; | |
| writeln!( | |
| code, | |
| " throw new Error('Failed to load external URL module {}: ' + \ | |
| (error.message || error));", | |
| StringifyJs(&self.request) | |
| )?; | |
| writeln!(code, "}}")?; | |
| } else { | |
| // Invalid format - throw error | |
| writeln!( | |
| code, | |
| "throw new Error('Invalid URL external format. Expected \"variable@url\", \ | |
| got: {}');", | |
| StringifyJs(&self.request) | |
| )?; | |
| writeln!(code, "const mod = undefined;")?; | |
| } | |
| } | |
| CachedExternalType::EcmaScriptViaRequire | CachedExternalType::CommonJs => { | |
| writeln!( | |
| code, | |
| "const mod = {TURBOPACK_EXTERNAL_REQUIRE}({}, () => require({}));", | |
| StringifyJs(&self.request), | |
| StringifyJs(&self.request) | |
| )?; | |
| } | |
| } | |
| writeln!(code)?; | |
| if self.external_type == CachedExternalType::CommonJs { | |
| writeln!(code, "module.exports = mod;")?; | |
| } else { | |
| writeln!(code, "{TURBOPACK_EXPORT_NAMESPACE}(mod);")?; | |
| } | |
| Ok(EcmascriptModuleContent { | |
| inner_code: code.build(), | |
| source_map: None, | |
| is_esm: self.external_type != CachedExternalType::CommonJs, | |
| strict: false, | |
| additional_ids: Default::default(), | |
| } | |
| .cell()) | |
| } | |
| } | |
| impl Module for CachedExternalModule { | |
| async fn ident(&self) -> Result<Vc<AssetIdent>> { | |
| let fs = VirtualFileSystem::new_with_name(rcstr!("externals")); | |
| Ok(AssetIdent::from_path(fs.root().await?.join(&self.request)?) | |
| .with_layer(Layer::new(rcstr!("external"))) | |
| .with_modifier(self.request.clone()) | |
| .with_modifier(self.external_type.to_string().into())) | |
| } | |
| async fn references(&self) -> Result<Vc<ModuleReferences>> { | |
| Ok(match &self.tracing_mode { | |
| CachedExternalTracingMode::Untraced => ModuleReferences::empty(), | |
| CachedExternalTracingMode::Traced { | |
| externals_context, | |
| root_origin, | |
| } => { | |
| let reference_type = match self.external_type { | |
| CachedExternalType::EcmaScriptViaImport => { | |
| ReferenceType::EcmaScriptModules(Default::default()) | |
| } | |
| CachedExternalType::CommonJs | CachedExternalType::EcmaScriptViaRequire => { | |
| ReferenceType::CommonJs(Default::default()) | |
| } | |
| _ => ReferenceType::Undefined, | |
| }; | |
| let external_result = externals_context | |
| .resolve_asset( | |
| root_origin.clone(), | |
| Request::parse_string(self.request.clone()), | |
| externals_context | |
| .resolve_options(root_origin.clone(), reference_type.clone()), | |
| reference_type, | |
| ) | |
| .await?; | |
| let references = external_result | |
| .affecting_sources | |
| .iter() | |
| .map(|s| Vc::upcast::<Box<dyn Module>>(RawModule::new(**s))) | |
| .chain(external_result.primary_modules_raw_iter().map(|rvc| *rvc)) | |
| .map(|s| { | |
| Vc::upcast::<Box<dyn ModuleReference>>(TracedModuleReference::new(s)) | |
| .to_resolved() | |
| }) | |
| .try_join() | |
| .await?; | |
| Vc::cell(references) | |
| } | |
| }) | |
| } | |
| fn is_self_async(&self) -> Result<Vc<bool>> { | |
| Ok(Vc::cell( | |
| self.external_type == CachedExternalType::EcmaScriptViaImport | |
| || self.external_type == CachedExternalType::Script, | |
| )) | |
| } | |
| } | |
| impl Asset for CachedExternalModule { | |
| fn content(self: Vc<Self>) -> Vc<AssetContent> { | |
| // should be `NotFound` as this function gets called to detect source changes | |
| AssetContent::file(FileContent::NotFound.cell()) | |
| } | |
| } | |
| impl ChunkableModule for CachedExternalModule { | |
| fn as_chunk_item( | |
| self: ResolvedVc<Self>, | |
| _module_graph: Vc<ModuleGraph>, | |
| chunking_context: ResolvedVc<Box<dyn ChunkingContext>>, | |
| ) -> Vc<Box<dyn ChunkItem>> { | |
| Vc::upcast( | |
| CachedExternalModuleChunkItem { | |
| module: self, | |
| chunking_context, | |
| } | |
| .cell(), | |
| ) | |
| } | |
| } | |
| impl EcmascriptChunkPlaceable for CachedExternalModule { | |
| fn get_exports(&self) -> Vc<EcmascriptExports> { | |
| if self.external_type == CachedExternalType::CommonJs { | |
| EcmascriptExports::CommonJs.cell() | |
| } else { | |
| EcmascriptExports::DynamicNamespace.cell() | |
| } | |
| } | |
| fn get_async_module(&self) -> Vc<OptionAsyncModule> { | |
| Vc::cell( | |
| if self.external_type == CachedExternalType::EcmaScriptViaImport | |
| || self.external_type == CachedExternalType::Script | |
| { | |
| Some( | |
| AsyncModule { | |
| has_top_level_await: true, | |
| import_externals: self.external_type | |
| == CachedExternalType::EcmaScriptViaImport, | |
| } | |
| .resolved_cell(), | |
| ) | |
| } else { | |
| None | |
| }, | |
| ) | |
| } | |
| fn is_marked_as_side_effect_free( | |
| self: Vc<Self>, | |
| _side_effect_free_packages: Vc<Glob>, | |
| ) -> Vc<bool> { | |
| Vc::cell(false) | |
| } | |
| } | |
| pub struct CachedExternalModuleChunkItem { | |
| module: ResolvedVc<CachedExternalModule>, | |
| chunking_context: ResolvedVc<Box<dyn ChunkingContext>>, | |
| } | |
| // Without this wrapper, VirtualFileSystem::new_with_name always returns a new filesystem | |
| fn external_fs() -> Vc<VirtualFileSystem> { | |
| VirtualFileSystem::new_with_name(rcstr!("externals")) | |
| } | |
| impl ChunkItem for CachedExternalModuleChunkItem { | |
| fn asset_ident(&self) -> Vc<AssetIdent> { | |
| self.module.ident() | |
| } | |
| fn ty(self: Vc<Self>) -> Vc<Box<dyn ChunkType>> { | |
| Vc::upcast(Vc::<EcmascriptChunkType>::default()) | |
| } | |
| fn module(&self) -> Vc<Box<dyn Module>> { | |
| Vc::upcast(*self.module) | |
| } | |
| fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { | |
| *self.chunking_context | |
| } | |
| } | |
| impl EcmascriptChunkItem for CachedExternalModuleChunkItem { | |
| fn content(self: Vc<Self>) -> Vc<EcmascriptChunkItemContent> { | |
| panic!("content() should not be called"); | |
| } | |
| fn content_with_async_module_info( | |
| &self, | |
| async_module_info: Option<Vc<AsyncModuleInfo>>, | |
| ) -> Vc<EcmascriptChunkItemContent> { | |
| let async_module_options = self | |
| .module | |
| .get_async_module() | |
| .module_options(async_module_info); | |
| EcmascriptChunkItemContent::new( | |
| self.module.content(), | |
| *self.chunking_context, | |
| async_module_options, | |
| ) | |
| } | |
| } | |