Unverified Commit 3abe2518 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: fix NFT of readFileSync of relative path (#84155)

Tests are missing

Previously, `readFileSync("./data/foo.txt")` was relative to the current file, not relative to `process.cwd()`
parent 43500816
......@@ -998,7 +998,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(),
))
......
......@@ -358,7 +358,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>> {
......@@ -367,7 +367,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')
})
})
......@@ -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,
......@@ -69,7 +69,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),
......@@ -103,9 +103,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),
......
......@@ -12,7 +12,6 @@ use turbopack_core::{
ModuleResolveResult, RequestKey,
pattern::{Pattern, PatternMatch, read_matches},
},
source::Source,
};
#[turbo_tasks::value]
......@@ -58,20 +57,20 @@ 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 })
}
}
async fn resolve_reference_from_dir(
parent_path: FileSystemPath,
context_dir: FileSystemPath,
path: Vc<Pattern>,
) -> Result<Vc<ModuleResolveResult>> {
let path_ref = path.await?;
......@@ -83,7 +82,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()),
......@@ -96,7 +95,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()),
......@@ -149,12 +148,11 @@ 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?)
);
resolve_reference_from_dir(parent_path, *self.path)
resolve_reference_from_dir(self.context_dir.clone(), *self.path)
.instrument(span)
.await
}
......
......@@ -2,31 +2,31 @@ use anyhow::Result;
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
chunk::{ChunkableModuleReference, ChunkingType, ChunkingTypeOption},
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>,
pub collect_affecting_sources: bool,
context_dir: FileSystemPath,
path: ResolvedVc<Pattern>,
collect_affecting_sources: bool,
}
#[turbo_tasks::value_impl]
impl FileSourceReference {
#[turbo_tasks::function]
pub fn new(
source: ResolvedVc<Box<dyn Source>>,
context_dir: FileSystemPath,
path: ResolvedVc<Pattern>,
collect_affecting_sources: bool,
) -> Vc<Self> {
Self::cell(FileSourceReference {
source,
context_dir,
path,
collect_affecting_sources,
})
......@@ -37,15 +37,13 @@ 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.context_dir.clone(),
*self.path,
self.collect_affecting_sources,
/* force_in_lookup_dir */ false,
......
......@@ -351,7 +351,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(),
......
......@@ -186,9 +186,13 @@ async fn node_file_trace_operation(package_root: RcStr, input: RcStr) -> Result<
let input_dir = workspace_fs.root().owned().await?;
let input = input_dir.join(&input)?;
let source = FileSource::new(input);
let source = FileSource::new(input.clone());
let environment = Environment::new(ExecutionEnvironment::NodeJsLambda(
NodeJsEnvironment::default().resolved_cell(),
NodeJsEnvironment {
cwd: ResolvedVc::cell(Some(input.parent())),
..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