Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions turbopack/crates/turbopack-core/src/compile_time_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,14 @@ pub enum InputRelativeConstant {
FileName,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue)]
pub enum CjsPathConstant {
// The project relative directory name of the source file
DirName,
// The project relative file name of the source file.
FileName,
}

#[turbo_tasks::value]
#[derive(Debug, Clone)]
pub enum FreeVarReference {
Expand All @@ -239,6 +247,7 @@ pub enum FreeVarReference {
Member(RcStr, RcStr),
Value(CompileTimeDefineValue),
InputRelative(InputRelativeConstant),
CjsPath(CjsPathConstant),
Error(RcStr),
}

Expand Down
35 changes: 29 additions & 6 deletions turbopack/crates/turbopack-ecmascript/src/references/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1555,9 +1555,15 @@ async fn compile_time_info_for_module_options(
.or_insert(rcstr!("string").into());
free_var_references
.entry(vec![DefinableNameSegment::Name(dir_name)])
.or_insert(FreeVarReference::InputRelative(
InputRelativeConstant::DirName,
));
.or_insert(if is_esm {
FreeVarReference::InputRelative(
InputRelativeConstant::DirName,
)
} else {
FreeVarReference::CjsPath(
CjsPathConstant::DirName,
)
});
let file_name = rcstr!("__filename");

free_var_references
Expand All @@ -1568,9 +1574,15 @@ async fn compile_time_info_for_module_options(
.or_insert(rcstr!("string").into());
free_var_references
.entry(vec![DefinableNameSegment::Name(file_name)])
.or_insert(FreeVarReference::InputRelative(
InputRelativeConstant::FileName,
));
.or_insert(if is_esm {
FreeVarReference::InputRelative(
InputRelativeConstant::FileName,
)
} else {
FreeVarReference::CjsPath(
CjsPathConstant::FileName,
)
});

// Compiletime rewrite the nodejs `global` to `__turbopack_context_.g` which is a shortcut for
// `globalThis` that cannot be shadowed by a local variable.
Expand Down Expand Up @@ -2897,6 +2909,17 @@ async fn handle_free_var_reference(
ast_path.to_vec().into(),
));
}
FreeVarReference::CjsPath(kind) => {
let source_path = state.origin.origin_path().owned().await?;
let source_path = match kind {
CjsPathConstant::DirName => source_path.parent(),
CjsPathConstant::FileName => source_path,
};
analysis.add_code_gen(ConstantValueCodeGen::new(
as_abs_path(source_path).into(),
ast_path.to_vec().into(),
));
}
}
Ok(true)
}
Expand Down
Loading