From 40008c73bb3b0b146b3539929ab5bd826db4c5e3 Mon Sep 17 00:00:00 2001 From: David Sherret Date: Mon, 24 Jul 2023 15:35:13 -0400 Subject: refactor(ext/node): CjsCodeAnalyzer - analyze_cjs optionally pass source text (#19896) --- ext/node/analyze.rs | 48 +++++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 23 deletions(-) (limited to 'ext/node/analyze.rs') diff --git a/ext/node/analyze.rs b/ext/node/analyze.rs index d811122d5..cf292d82f 100644 --- a/ext/node/analyze.rs +++ b/ext/node/analyze.rs @@ -29,10 +29,15 @@ pub struct CjsAnalysis { pub trait CjsCodeAnalyzer { /// Analyzes CommonJs code for exports and reexports, which is /// then used to determine the wrapper ESM module exports. + /// + /// Note that the source is provided by the caller when the caller + /// already has it. If the source is needed by the implementation, + /// then it can use the provided source, or otherwise load it if + /// necessary. fn analyze_cjs( &self, specifier: &ModuleSpecifier, - source: &str, + maybe_source: Option<&str>, ) -> Result; } @@ -73,7 +78,9 @@ impl NodeCodeTranslator { let mut temp_var_count = 0; let mut handled_reexports: HashSet = HashSet::default(); - let analysis = self.cjs_code_analyzer.analyze_cjs(specifier, source)?; + let analysis = self + .cjs_code_analyzer + .analyze_cjs(specifier, Some(source))?; let mut source = vec![ r#"import {createRequire as __internalCreateRequire} from "node:module"; @@ -100,7 +107,7 @@ impl NodeCodeTranslator { handled_reexports.insert(reexport.to_string()); - // First, resolve relate reexport specifier + // First, resolve the reexport specifier let resolved_reexport = self.resolve( &reexport, &referrer, @@ -110,35 +117,30 @@ impl NodeCodeTranslator { NodeResolutionMode::Execution, permissions, )?; - // Second, read the source code from disk + + // Second, resolve its exports and re-exports let reexport_specifier = ModuleSpecifier::from_file_path(&resolved_reexport).unwrap(); - let reexport_file_text = self - .fs - .read_to_string(&resolved_reexport) - .map_err(AnyError::from) + let analysis = self + .cjs_code_analyzer + .analyze_cjs(&reexport_specifier, None) .with_context(|| { format!( - "Could not find '{}' ({}) referenced from {}", + "Could not load '{}' ({}) referenced from {}", reexport, reexport_specifier, referrer ) })?; - { - let analysis = self - .cjs_code_analyzer - .analyze_cjs(&reexport_specifier, &reexport_file_text)?; - for reexport in analysis.reexports { - reexports_to_handle.push_back((reexport, reexport_specifier.clone())); - } - - all_exports.extend( - analysis - .exports - .into_iter() - .filter(|e| e.as_str() != "default"), - ); + for reexport in analysis.reexports { + reexports_to_handle.push_back((reexport, reexport_specifier.clone())); } + + all_exports.extend( + analysis + .exports + .into_iter() + .filter(|e| e.as_str() != "default"), + ); } source.push(format!( -- cgit v1.2.3