summaryrefslogtreecommitdiff
path: root/cli/cache/parsed_source.rs
diff options
context:
space:
mode:
authorDavid Sherret <dsherret@users.noreply.github.com>2024-10-14 20:48:39 -0400
committerGitHub <noreply@github.com>2024-10-14 20:48:39 -0400
commit1a0cb5b5312941521ab021cfe9eaed498f35900b (patch)
tree2e5c58e25e8506b993ac678e83ba0c2feac37d75 /cli/cache/parsed_source.rs
parentee7d4501435f0ebd655c8b50bd6e41ca19e71abc (diff)
feat(unstable): `--unstable-detect-cjs` for respecting explicit `"type": "commonjs"` (#26149)
When using the `--unstable-detect-cjs` flag or adding `"unstable": ["detect-cjs"]` to a deno.json, it will make a JS file CJS if the closest package.json contains `"type": "commonjs"` and the file is not an ESM module (no TLA, no `import.meta`, no `import`/`export`).
Diffstat (limited to 'cli/cache/parsed_source.rs')
-rw-r--r--cli/cache/parsed_source.rs40
1 files changed, 40 insertions, 0 deletions
diff --git a/cli/cache/parsed_source.rs b/cli/cache/parsed_source.rs
index e956361f4..df6e45c35 100644
--- a/cli/cache/parsed_source.rs
+++ b/cli/cache/parsed_source.rs
@@ -5,6 +5,7 @@ use std::sync::Arc;
use deno_ast::MediaType;
use deno_ast::ModuleSpecifier;
+use deno_ast::ParseDiagnostic;
use deno_ast::ParsedSource;
use deno_core::parking_lot::Mutex;
use deno_graph::CapturingModuleParser;
@@ -149,3 +150,42 @@ impl deno_graph::ParsedSourceStore for ParsedSourceCache {
}
}
}
+
+pub struct EsmOrCjsChecker {
+ parsed_source_cache: Arc<ParsedSourceCache>,
+}
+
+impl EsmOrCjsChecker {
+ pub fn new(parsed_source_cache: Arc<ParsedSourceCache>) -> Self {
+ Self {
+ parsed_source_cache,
+ }
+ }
+
+ pub fn is_esm(
+ &self,
+ specifier: &ModuleSpecifier,
+ source: Arc<str>,
+ media_type: MediaType,
+ ) -> Result<bool, ParseDiagnostic> {
+ // todo(dsherret): add a file cache here to avoid parsing with swc on each run
+ let source = match self.parsed_source_cache.get_parsed_source(specifier) {
+ Some(source) => source.clone(),
+ None => {
+ let source = deno_ast::parse_program(deno_ast::ParseParams {
+ specifier: specifier.clone(),
+ text: source,
+ media_type,
+ capture_tokens: true, // capture because it's used for cjs export analysis
+ scope_analysis: false,
+ maybe_syntax: None,
+ })?;
+ self
+ .parsed_source_cache
+ .set_parsed_source(specifier.clone(), source.clone());
+ source
+ }
+ };
+ Ok(source.is_module())
+ }
+}