Unverified Commit 84de13f6 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

[backport] NFT tracing fixes #84155 and #85323 (#88124)

parent ce36aec7
......@@ -581,14 +581,7 @@ async fn validate_pages_css_imports(
.map(async |issue| {
// We allow imports of global CSS files which are inside of `node_modules`.
Ok(
if !issue
.module
.ident()
.path()
.await?
.path
.contains("/node_modules/")
{
if !issue.module.ident().path().await?.is_in_node_modules() {
Some(issue)
} else {
None
......
......@@ -994,7 +994,7 @@ impl Project {
let this = self.await?;
Ok(get_server_compile_time_info(
// `/ROOT` corresponds to `[project]/`, so we need exactly the `path` part.
format!("/ROOT/{}", self.project_path().await?.path).into(),
self.project_path(),
this.define_env.nodejs(),
self.current_node_js_version(),
))
......
......@@ -361,7 +361,7 @@ async fn next_server_free_vars(define_env: Vc<OptionEnvMap>) -> Result<Vc<FreeVa
#[turbo_tasks::function]
pub async fn get_server_compile_time_info(
cwd: RcStr,
cwd: Vc<FileSystemPath>,
define_env: Vc<OptionEnvMap>,
node_version: ResolvedVc<NodeJsVersion>,
) -> Result<Vc<CompileTimeInfo>> {
......@@ -370,7 +370,7 @@ pub async fn get_server_compile_time_info(
NodeJsEnvironment {
compile_target: CompileTarget::current().to_resolved().await?,
node_version,
cwd: ResolvedVc::cell(Some(cwd)),
cwd: ResolvedVc::cell(Some(cwd.owned().await?)),
}
.resolved_cell(),
))
......
......@@ -3,7 +3,10 @@ import path from 'path'
import 'foo'
const projectDir = process.cwd()
path.join(projectDir, 'app', 'static-from-app.txt')
path.join(projectDir, 'data', 'static-from-app-cwd.txt')
path.join('data', 'static-from-app-rel-join.txt')
path.join('data', 'static-from-app-rel-read.txt')
export default function Page() {
return 'hello'
......
import path from 'path'
const projectDir = process.cwd()
path.join(projectDir, 'app', 'static-from-pkg.txt')
path.join(projectDir, 'data', 'static-from-pkg.txt')
path.join('data', 'static-from-pkg.txt')
globalThis.myDirname = __dirname
path.join(globalThis.myDirname, 'foo.txt')
export default 'foo'
import { nextTestSetup } from 'e2e-utils'
describe('standalone mode - NFT in node_modules', () => {
describe('standalone mode - tracing', () => {
const dependencies = require('./package.json').dependencies
const { next, skipped } = nextTestSetup({
......@@ -13,10 +13,30 @@ describe('standalone mode - NFT in node_modules', () => {
return
}
it('should not trace process.cwd calls in node_modules', async () => {
it('should trace process.cwd calls in node_modules', async () => {
let trace = await next.readJSON('.next/server/app/page.js.nft.json')
expect(trace.files).toContain('../../../app/static-from-app.txt')
// should trace process.cwd and relative calls relative to the root
expect(trace.files).toContain('../../../data/static-from-app-cwd.txt')
if (process.env.IS_TURBOPACK_TEST) {
// Webpack doesn't trace these relative reference
expect(trace.files).toContain(
'../../../data/static-from-app-rel-join.txt'
)
expect(trace.files).toContain(
'../../../data/static-from-app-rel-read.txt'
)
}
if (process.env.IS_TURBOPACK_TEST) {
// Webpack doesn't trace these relative reference
expect(trace.files).toContainEqual(
expect.stringMatching(/.*\/node_modules\/foo\/foo.txt/)
)
}
// should not trace process.cwd or relative calls in node_modules (only relative to file)
expect(trace.files).not.toContain('../../../app/static-from-pkg.txt')
expect(trace.files).not.toContain('../../../foo/foo.txt')
})
})
......@@ -1048,6 +1048,10 @@ impl FileSystemPath {
self.path.is_empty()
}
pub fn is_in_node_modules(&self) -> bool {
self.path.starts_with("node_modules/") || self.path.contains("/node_modules/")
}
/// Returns the path of `inner` relative to `self`.
///
/// Note: this method always strips the leading `/` from the result.
......
......@@ -9,6 +9,7 @@ use swc_core::ecma::preset_env::{Version, Versions};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TaskInput, Vc};
use turbo_tasks_env::ProcessEnv;
use turbo_tasks_fs::FileSystemPathOption;
use crate::target::CompileTarget;
......@@ -213,7 +214,7 @@ impl Environment {
}
#[turbo_tasks::function]
pub async fn cwd(&self) -> Result<Vc<Option<RcStr>>> {
pub async fn cwd(&self) -> Result<Vc<FileSystemPathOption>> {
let env = self;
Ok(match env.execution {
ExecutionEnvironment::NodeJsBuildTime(env)
......@@ -258,7 +259,7 @@ pub struct NodeJsEnvironment {
pub compile_target: ResolvedVc<CompileTarget>,
pub node_version: ResolvedVc<NodeJsVersion>,
// user specified process.cwd
pub cwd: ResolvedVc<Option<RcStr>>,
pub cwd: ResolvedVc<FileSystemPathOption>,
}
impl Default for NodeJsEnvironment {
......
......@@ -15,7 +15,7 @@ use crate::analyzer::RequireContextValue;
pub async fn replace_well_known(
value: JsValue,
compile_time_info: Vc<CompileTimeInfo>,
define_process_cwd: bool,
allow_project_root_tracing: bool,
) -> Result<(JsValue, bool)> {
Ok(match value {
JsValue::Call(_, box JsValue::WellKnownFunction(kind), args) => (
......@@ -24,7 +24,7 @@ pub async fn replace_well_known(
JsValue::unknown_empty(false, "this is not analyzed yet"),
args,
compile_time_info,
define_process_cwd,
allow_project_root_tracing,
)
.await?,
true,
......@@ -54,7 +54,7 @@ pub async fn well_known_function_call(
_this: JsValue,
args: Vec<JsValue>,
compile_time_info: Vc<CompileTimeInfo>,
define_process_cwd: bool,
allow_project_root_tracing: bool,
) -> Result<JsValue> {
Ok(match kind {
WellKnownFunctionKind::ObjectAssign => object_assign(args),
......@@ -88,9 +88,10 @@ pub async fn well_known_function_call(
.as_str()
.into(),
WellKnownFunctionKind::ProcessCwd => {
if define_process_cwd && let Some(cwd) = &*compile_time_info.environment().cwd().await?
if allow_project_root_tracing
&& let Some(cwd) = &*compile_time_info.environment().cwd().await?
{
cwd.clone().into()
format!("/ROOT/{}", cwd.path).into()
} else {
JsValue::unknown(
JsValue::call(Box::new(JsValue::WellKnownFunction(kind)), args),
......
......@@ -429,7 +429,10 @@ struct AnalysisState<'a> {
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
compile_time_info: ResolvedVc<CompileTimeInfo>,
var_graph: &'a VarGraph,
define_process_cwd: bool,
/// Whether to allow tracing to reference files from the project root. This is used to prevent
/// random node_modules packages from tracing the entire project due to some dynamic
/// `path.join(foo, bar)` call.
allow_project_root_tracing: bool,
/// This is the current state of known values of function
/// arguments.
fun_args_values: Mutex<FxHashMap<u32, Vec<JsValue>>>,
......@@ -459,7 +462,7 @@ impl AnalysisState<'_> {
&self.free_var_references,
self.var_graph,
attributes,
self.define_process_cwd,
self.allow_project_root_tracing,
)
},
&self.fun_args_values,
......@@ -990,7 +993,7 @@ pub(crate) async fn analyse_ecmascript_module_internal(
origin,
compile_time_info,
var_graph: &var_graph,
define_process_cwd: !source.ident().path().await?.path.contains("/node_modules/"),
allow_project_root_tracing: !source.ident().path().await?.is_in_node_modules(),
fun_args_values: Default::default(),
var_cache: Default::default(),
first_import_meta: true,
......@@ -1581,6 +1584,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
compile_time_info,
ignore_dynamic_requests,
url_rewrite_behavior,
allow_project_root_tracing,
..
} = state;
fn explain_args(args: &[JsValue]) -> (String, String) {
......@@ -1697,6 +1701,24 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
return Ok(());
}
let get_traced_project_dir = async || -> Result<FileSystemPath> {
// readFileSync("./foo") should always be relative to the project root, but this is
// dangerous inside of node_modules as it can cause a lot of false positives in the tracing,
// if some package does `path.join(dynamic)`, it would include everything from the project
// root as well.
//
// Also, when there's no cwd set (i.e. in a tracing-specific module context, as we shouldn't
// assume a `process.cwd()` for all of node_modules), fallback to the source file directory.
// This still allows relative file accesses, just not from the project root.
if allow_project_root_tracing
&& let Some(cwd) = compile_time_info.environment().cwd().owned().await?
{
Ok(cwd)
} else {
Ok(source.ident().path().await?.parent())
}
};
match func {
JsValue::Alternatives {
total_nodes: _,
......@@ -1925,7 +1947,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
}
}
analysis.add_reference(
FileSourceReference::new(*source, Pattern::new(pat))
FileSourceReference::new(get_traced_project_dir().await?, Pattern::new(pat))
.to_resolved()
.await?,
);
......@@ -1972,7 +1994,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
}
}
analysis.add_reference(
FileSourceReference::new(*source, Pattern::new(pat))
DirAssetReference::new(get_traced_project_dir().await?, Pattern::new(pat))
.to_resolved()
.await?,
);
......@@ -2010,7 +2032,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
}
}
analysis.add_reference(
DirAssetReference::new(*source, Pattern::new(pat))
DirAssetReference::new(get_traced_project_dir().await?, Pattern::new(pat))
.to_resolved()
.await?,
);
......@@ -2057,9 +2079,12 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
}
if !dynamic || !ignore_dynamic_requests {
analysis.add_reference(
FileSourceReference::new(*source, Pattern::new(pat))
.to_resolved()
.await?,
FileSourceReference::new(
get_traced_project_dir().await?,
Pattern::new(pat),
)
.to_resolved()
.await?,
);
}
if show_dynamic_warning {
......@@ -2270,9 +2295,12 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
js_value_to_pattern(&linked_func_call)
};
analysis.add_reference(
DirAssetReference::new(*source, Pattern::new(abs_pattern))
.to_resolved()
.await?,
DirAssetReference::new(
get_traced_project_dir().await?,
Pattern::new(abs_pattern),
)
.to_resolved()
.await?,
);
return Ok(());
}
......@@ -2331,9 +2359,12 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
js_value_to_pattern(&linked_func_call)
};
analysis.add_reference(
DirAssetReference::new(*source, Pattern::new(abs_pattern))
.to_resolved()
.await?,
DirAssetReference::new(
get_traced_project_dir().await?,
Pattern::new(abs_pattern),
)
.to_resolved()
.await?,
);
return Ok(());
}
......@@ -2378,6 +2409,7 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
if args.len() == 2
&& let Some(JsValue::Object { parts, .. }) = args.get(1)
{
let context_dir = get_traced_project_dir().await?;
let resolved_dirs = parts
.iter()
.filter_map(|object_part| match object_part {
......@@ -2391,8 +2423,11 @@ async fn handle_call<G: Fn(Vec<Effect>) + Send + Sync>(
})
.flatten()
.map(|dir| {
DirAssetReference::new(*source, Pattern::new(Pattern::Constant(dir.into())))
.to_resolved()
DirAssetReference::new(
context_dir.clone(),
Pattern::new(Pattern::Constant(dir.into())),
)
.to_resolved()
})
.try_join()
.await?;
......@@ -2871,7 +2906,7 @@ async fn value_visitor(
>,
var_graph: &VarGraph,
attributes: &ImportAttributes,
define_process_cwd: bool,
allow_project_root_tracing: bool,
) -> Result<(JsValue, bool)> {
let (mut v, modified) = value_visitor_inner(
origin,
......@@ -2880,7 +2915,7 @@ async fn value_visitor(
free_var_references,
var_graph,
attributes,
define_process_cwd,
allow_project_root_tracing,
)
.await?;
v.normalize_shallow();
......@@ -2897,7 +2932,7 @@ async fn value_visitor_inner(
>,
var_graph: &VarGraph,
attributes: &ImportAttributes,
define_process_cwd: bool,
allow_project_root_tracing: bool,
) -> Result<(JsValue, bool)> {
let ImportAttributes { ignore, .. } = *attributes;
// This check is just an optimization
......@@ -3028,7 +3063,7 @@ async fn value_visitor_inner(
}
_ => {
let (mut v, mut modified) =
replace_well_known(v, compile_time_info, define_process_cwd).await?;
replace_well_known(v, compile_time_info, allow_project_root_tracing).await?;
modified = replace_builtin(&mut v) || modified;
modified = modified || v.make_nested_operations_unknown();
return Ok((v, modified));
......
......@@ -12,7 +12,6 @@ use turbopack_core::{
ModuleResolveResult, RequestKey,
pattern::{Pattern, PatternMatch, read_matches},
},
source::Source,
};
#[turbo_tasks::value]
......@@ -58,21 +57,21 @@ impl ValueToString for PackageJsonReference {
#[turbo_tasks::value]
#[derive(Hash, Debug)]
pub struct DirAssetReference {
pub source: ResolvedVc<Box<dyn Source>>,
pub context_dir: FileSystemPath,
pub path: ResolvedVc<Pattern>,
}
#[turbo_tasks::value_impl]
impl DirAssetReference {
#[turbo_tasks::function]
pub fn new(source: ResolvedVc<Box<dyn Source>>, path: ResolvedVc<Pattern>) -> Vc<Self> {
Self::cell(DirAssetReference { source, path })
pub fn new(context_dir: FileSystemPath, path: ResolvedVc<Pattern>) -> Vc<Self> {
Self::cell(DirAssetReference { context_dir, path })
}
}
#[turbo_tasks::function]
async fn resolve_reference_from_dir(
parent_path: FileSystemPath,
context_dir: FileSystemPath,
path: Vc<Pattern>,
) -> Result<Vc<ModuleResolveResult>> {
let path_ref = path.await?;
......@@ -84,7 +83,7 @@ async fn resolve_reference_from_dir(
let abs_matches = if let Some(abs_path) = &abs_path {
Some(
read_matches(
parent_path.root().owned().await?,
context_dir.root().owned().await?,
rcstr!("/ROOT/"),
true,
Pattern::new(abs_path.or_any_nested_file()),
......@@ -97,7 +96,7 @@ async fn resolve_reference_from_dir(
let rel_matches = if let Some(rel_path) = &rel_path {
Some(
read_matches(
parent_path,
context_dir,
rcstr!(""),
true,
Pattern::new(rel_path.or_any_nested_file()),
......@@ -150,13 +149,12 @@ async fn resolve_reference_from_dir(
impl ModuleReference for DirAssetReference {
#[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let parent_path = self.source.ident().path().await?.parent();
let span = tracing::info_span!(
"trace directory",
pattern = display(self.path.to_string().await?)
);
async {
resolve_reference_from_dir(parent_path, *self.path)
resolve_reference_from_dir(self.context_dir.clone(), *self.path)
.resolve()
.await
}
......
......@@ -2,24 +2,24 @@ use anyhow::Result;
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
reference::ModuleReference,
resolve::{ModuleResolveResult, pattern::Pattern, resolve_raw},
source::Source,
};
#[turbo_tasks::value]
#[derive(Hash, Debug)]
pub struct FileSourceReference {
pub source: ResolvedVc<Box<dyn Source>>,
pub path: ResolvedVc<Pattern>,
context_dir: FileSystemPath,
path: ResolvedVc<Pattern>,
}
#[turbo_tasks::value_impl]
impl FileSourceReference {
#[turbo_tasks::function]
pub fn new(source: ResolvedVc<Box<dyn Source>>, path: ResolvedVc<Pattern>) -> Vc<Self> {
Self::cell(FileSourceReference { source, path })
pub fn new(context_dir: FileSystemPath, path: ResolvedVc<Pattern>) -> Vc<Self> {
Self::cell(FileSourceReference { context_dir, path })
}
}
......@@ -27,17 +27,19 @@ impl FileSourceReference {
impl ModuleReference for FileSourceReference {
#[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let context_dir = self.source.ident().path().await?.parent();
let span = tracing::info_span!(
"trace file",
pattern = display(self.path.to_string().await?)
);
async {
resolve_raw(context_dir, *self.path, false)
.as_raw_module_result()
.resolve()
.await
resolve_raw(
self.context_dir.clone(),
*self.path,
/* force_in_lookup_dir */ false,
)
.as_raw_module_result()
.resolve()
.await
}
.instrument(span)
.await
......
......@@ -347,7 +347,11 @@ async fn node_file_trace_operation(
let source = FileSource::new(input);
let environment = Environment::new(ExecutionEnvironment::NodeJsLambda(
NodeJsEnvironment::default().resolved_cell(),
NodeJsEnvironment {
cwd: ResolvedVc::cell(Some(input_dir.join("tests/node-file-trace/integration")?)),
..Default::default()
}
.resolved_cell(),
));
let module_asset_context = ModuleAssetContext::new(
Default::default(),
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment