Unverified Commit 7905cb4c authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: write symlinks to access transitive `serverExternalPackages`

 (#86375)

Closes PACK-5936

This alleviates a long-standing painpoint of `serverExternalPackages`. If you are using
`some-utility` which uses `lodash`, and you have to make `lodash` a `serverExternalPackages`, then
you'd have to add the correct version of `lodash` to your application's dependencies in package.json.

This is not very ergonomic as it leaks the internal implementation of your direct dependencies (you
shoudln't have to care about their transitive dependencies). And it's easy to run into a situation
where it's impossible to satisfy all dependencies, if you'd have to add two conflicting versions of `lodash` for example.

Instead, Turbopack now emits symlinks like

```
.next/node_modules/lodash-98e63531e9336dd0@ -> ../../../../node_modules/.pnpm/lodash@4.17.20/node_modules/lodash
.next/node_modules/lodash-ee4fa714b6d81ca3@ -> ../../../../node_modules/.pnpm/lodash@3.10.1/node_modules/lodash
```

.so that `.next/server/chunks/29adj2sd9.js` can then contain a `require("lodash-98e63531e9336dd0")`
and alway get the correct version (and without the user having to declare them).
parent 0683859c
......@@ -199,7 +199,6 @@ pub async fn get_server_resolve_options_context(
external_packages.retain(|item| !transpiled_packages.contains(item));
let server_external_packages_plugin = ExternalCjsModulesResolvePlugin::new(
project_path.clone(),
project_path.root().owned().await?,
ExternalPredicate::Only(ResolvedVc::cell(external_packages)).cell(),
*next_config.import_externals().await?,
......@@ -225,7 +224,6 @@ pub async fn get_server_resolve_options_context(
server_external_packages_plugin
} else {
ExternalCjsModulesResolvePlugin::new(
project_path.clone(),
project_path.root().owned().await?,
ExternalPredicate::AllExcept(ResolvedVc::cell(transpiled_packages)).cell(),
*next_config.import_externals().await?,
......
......@@ -41,7 +41,6 @@ pub enum ExternalPredicate {
/// possible to resolve them at runtime.
#[turbo_tasks::value]
pub(crate) struct ExternalCjsModulesResolvePlugin {
project_path: FileSystemPath,
root: FileSystemPath,
predicate: ResolvedVc<ExternalPredicate>,
import_externals: bool,
......@@ -51,13 +50,11 @@ pub(crate) struct ExternalCjsModulesResolvePlugin {
impl ExternalCjsModulesResolvePlugin {
#[turbo_tasks::function]
pub fn new(
project_path: FileSystemPath,
root: FileSystemPath,
predicate: ResolvedVc<ExternalPredicate>,
import_externals: bool,
) -> Vc<Self> {
ExternalCjsModulesResolvePlugin {
project_path,
root,
predicate,
import_externals,
......@@ -259,104 +256,9 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
};
break result_from_original_location;
};
let node_resolved = resolve(
self.project_path.clone(),
reference_type.clone(),
request,
node_resolve_options,
);
let Some(result) = *node_resolved.first_source().await? else {
// this can't resolve with node.js from the project directory, so bundle it
return unable_to_externalize(vec![
StyledString::Text(
"The request could not be resolved by Node.js from the project \
directory.\nPackages that should be external need to be installed in the \
project directory, so they can be resolved from the output files.\nTry to \
install it into the project directory by running "
.into(),
),
StyledString::Code(format!("npm install {package}").into()),
StyledString::Text(rcstr!(" from the project directory.")),
]);
};
if result_from_original_location != result {
let package_json_file =
find_context_file(result.ident().path().await?.parent(), package_json(), false);
let package_json_from_original_location = find_context_file(
result_from_original_location.ident().path().await?.parent(),
package_json(),
false,
);
let FindContextFileResult::Found(package_json_file, _) = &*package_json_file.await?
else {
return unable_to_externalize(vec![StyledString::Text(
"The package.json of the package resolved from the project directory can't be \
found."
.into(),
)]);
};
let FindContextFileResult::Found(package_json_from_original_location, _) =
&*package_json_from_original_location.await?
else {
return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json of the package can't be found."
))]);
};
let FileJsonContent::Content(package_json_file) =
&*package_json_file.read_json().await?
else {
return unable_to_externalize(vec![StyledString::Text(
"The package.json of the package resolved from project directory can't be \
parsed."
.into(),
)]);
};
let FileJsonContent::Content(package_json_from_original_location) =
&*package_json_from_original_location.read_json().await?
else {
return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json of the package can't be parsed."
))]);
};
let (Some(name), Some(version)) = (
package_json_file.get("name").and_then(|v| v.as_str()),
package_json_file.get("version").and_then(|v| v.as_str()),
) else {
return unable_to_externalize(vec![StyledString::Text(rcstr!(
"The package.json of the package has no name or version."
))]);
};
let (Some(name2), Some(version2)) = (
package_json_from_original_location
.get("name")
.and_then(|v| v.as_str()),
package_json_from_original_location
.get("version")
.and_then(|v| v.as_str()),
) else {
return unable_to_externalize(vec![StyledString::Text(
"The package.json of the package resolved from project directory has no name \
or version."
.into(),
)]);
};
if (name, version) != (name2, version2) {
// this can't resolve with node.js from the original location, so bundle it
return unable_to_externalize(vec![StyledString::Text(
format!(
"The package resolves to a different version when requested from the \
project directory ({version}) compared to the package requested from the \
importing module ({version2}).\nMake sure to install the same version of \
the package in both locations."
)
.into(),
)]);
}
}
let path = result.ident().path().owned().await?;
let file_type = get_file_type(path.clone(), &path).await?;
let path = result_from_original_location.ident().path().await?;
let file_type = get_file_type((*path).clone(), &path).await?;
let external_type = match (file_type, is_esm) {
(FileType::UnsupportedExtension, _) => {
......@@ -375,18 +277,19 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
(FileType::CommonJs, false) => ExternalType::CommonJs,
(FileType::CommonJs, true) => {
// It would be more efficient to use an CJS external instead of an ESM external,
// but we need to verify if that would be correct (as in resolves to the same file).
// but we need to verify if that would be correct (as in resolves to the same
// file).
let node_resolve_options =
node_cjs_resolve_options(lookup_path.root().owned().await?);
let node_resolved = resolve(
self.project_path.clone(),
lookup_path.clone(),
reference_type.clone(),
request,
node_resolve_options,
);
let resolves_equal = if let Some(result) = *node_resolved.first_source().await? {
let cjs_path = result.ident().path().owned().await?;
cjs_path == path
cjs_path == *path
} else {
false
};
......@@ -407,7 +310,8 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
// ecmascript with esm is always external
(FileType::EcmaScriptModule, true) => ExternalType::EcmaScriptModule,
(FileType::EcmaScriptModule, false) => {
// even with require() this resolves to a ESM, which would break node.js, bundle it
// even with require() this resolves to a ESM, which would break node.js, bundle
// it
return unable_to_externalize(vec![StyledString::Text(
"The package seems invalid. require() resolves to a EcmaScript module, which \
would result in an error in Node.js."
......@@ -416,11 +320,14 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
}
};
let target = result_from_original_location.ident().path().owned().await?;
Ok(ResolveResultOption::some(*ResolveResult::primary(
ResolveResultItem::External {
name: request_str.into(),
ty: external_type,
traced: ExternalTraced::Traced,
target: Some(target),
},
)))
}
......
......@@ -254,6 +254,7 @@ impl AfterResolvePlugin for NextExternalResolvePlugin {
name: specifier.clone(),
ty: ExternalType::CommonJs,
traced: ExternalTraced::Traced,
target: None,
},
))))
}
......
export default function Root({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
import depA from 'dep-a'
import depB from 'dep-b'
export default function page() {
return (
<body>
<p>
depA: {depA}, depB: {depB.join(', ')}
</p>
</body>
)
}
import lodash from 'lodash'
export default lodash.VERSION
{
"name": "dep-a",
"version": "1.0.0",
"dependencies": {
"lodash": "3.10.1"
}
}
import lodash from 'lodash'
import pkg from 'lodash/package.json'
export default [lodash.VERSION, pkg.version]
{
"name": "dep-b",
"version": "1.0.0",
"dependencies": {
"lodash": "4.17.21"
}
}
import glob from 'glob'
import path from 'path'
import fs from 'fs/promises'
import { nextTestSetup } from 'e2e-utils'
describe('externals-transitive', () => {
const { next, isTurbopack, isNextDeploy, isNextStart } = nextTestSetup({
files: __dirname,
dependencies: require('./package.json').dependencies,
})
it('uses the right version of transitive externals', async () => {
const $ = await next.render$('/')
const body = $('body > p').text().trim()
expect(body).toEqual(`depA: 3.10.1, depB: 4.17.21, 4.17.21`)
if (!isNextDeploy) {
const files = glob.sync('**/*.js', {
cwd: path.join(next.testDir, next.distDir, 'server'),
})
let isLodashBundled = false
for (const file of files) {
const content = await next.readFile(
path.join(next.distDir, 'server', file)
)
isLodashBundled =
isLodashBundled ||
// Code
content.includes('__lodash_hash_undefined__') ||
// Package.json
content.includes('Lodash modular utilities.')
}
if (isTurbopack) {
// Assert that lodash wasn't bundled. Turbopack creates symlinks to be able to access
// transitive dependencies at runtime.
expect(isLodashBundled).toBe(false)
let symlinks = (
await fs.readdir(
path.join(next.testDir, next.distDir, 'node_modules')
)
).filter((file) => file.startsWith('lodash-'))
expect(symlinks.length).toBeGreaterThanOrEqual(2)
if (isNextStart) {
// Lists the two symlinks in the NFT
const trace = (await next.readJSON(
'.next/server/app/page.js.nft.json'
)) as { files: string[] }
for (let symlink of symlinks) {
expect(trace.files).toContain(`../../node_modules/${symlink}`)
}
}
} else {
// Webpack ends up bundling lodash in dep-a
expect(isLodashBundled).toBe(true)
}
}
})
})
module.exports = {
serverExternalPackages: ['lodash'],
experimental: {
turbopackModuleIds: 'named',
turbopackMinify: false,
turbopackScopeHoisting: false,
},
}
{
"dependencies": {
"dep-a": "file:./dep-a",
"dep-b": "file:./dep-b",
"lodash": "3.10.1"
}
}
......@@ -37,7 +37,7 @@ describe('default', () => {
}
// we don't know the name of the minified `__turbopack_external_require__`, so we just check the content.
expect(allBundles).toContain('"external-package"')
expect(allBundles).toMatch(/"external-package(-[0-9a-f]+)?"/)
expect(allBundles).not.toContain('"external-package content"')
} else {
const output = await fs.readFile(
......
......@@ -43,6 +43,7 @@ describe('Required Server Files', () => {
if (
file === 'server' ||
file === 'required-server-files.json' ||
file === 'node_modules' ||
requiredFilesManifest.files.includes(join('.next', file))
) {
continue
......
......@@ -444,6 +444,9 @@ pub enum ResolveResultItem {
name: RcStr,
ty: ExternalType,
traced: ExternalTraced,
/// The file path to the resolved file. Passing a value will create a symlink in the output
/// root to be able to access potentially transitive dependencies.
target: Option<FileSystemPath>,
},
Ignore,
Error(ResolvedVc<RcStr>),
......@@ -524,10 +527,19 @@ impl ValueToString for ResolveResult {
name: s,
ty,
traced,
target,
} => {
result.push_str("external ");
result.push_str(s);
write!(result, " ({ty}, {traced})")?;
write!(
result,
" ({ty}, {traced}, {:?})",
if let Some(target) = target {
Some(target.value_to_string().await?)
} else {
None
}
)?;
}
ResolveResultItem::Ignore => {
result.push_str("ignore");
......@@ -656,8 +668,13 @@ impl ResolveResult {
request,
match item {
ResolveResultItem::Source(source) => asset_fn(source).await?,
ResolveResultItem::External { name, ty, traced } => {
if traced == ExternalTraced::Traced {
ResolveResultItem::External {
name,
ty,
traced,
target,
} => {
if traced == ExternalTraced::Traced || target.is_some() {
// Should use map_primary_items instead
bail!("map_module doesn't handle traced externals");
}
......@@ -2009,6 +2026,7 @@ async fn resolve_internal_inline(
name: uri,
ty: ExternalType::Url,
traced: ExternalTraced::Untraced,
target: None,
},
)
}
......@@ -2026,6 +2044,7 @@ async fn resolve_internal_inline(
name: uri,
ty: ExternalType::Url,
traced: ExternalTraced::Untraced,
target: None,
},
)
}
......@@ -2751,13 +2770,17 @@ async fn resolve_import_map_result(
))
}
}
ImportMapResult::External { name, ty, traced } => {
Some(*ResolveResult::primary(ResolveResultItem::External {
name: name.clone(),
ty: *ty,
traced: *traced,
}))
}
ImportMapResult::External {
name,
ty,
traced,
target,
} => Some(*ResolveResult::primary(ResolveResultItem::External {
name: name.clone(),
ty: *ty,
traced: *traced,
target: target.clone(),
})),
ImportMapResult::AliasExternal {
name,
ty,
......@@ -2793,6 +2816,7 @@ async fn resolve_import_map_result(
name: name.clone(),
ty: *ty,
traced: *traced,
target: None,
}))
} else {
None
......
......@@ -138,6 +138,7 @@ pub enum ReplacedImportMapping {
name_override: Option<RcStr>,
ty: ExternalType,
traced: ExternalTraced,
target: Option<FileSystemPath>,
},
PrimaryAlternativeExternal {
name: Option<RcStr>,
......@@ -198,6 +199,8 @@ impl AliasTemplate for Vc<ImportMapping> {
name_override: name.clone(),
ty: *ty,
traced: *traced,
// TODO
target: None,
},
ImportMapping::PrimaryAlternativeExternal {
name,
......@@ -246,12 +249,14 @@ impl AliasTemplate for Vc<ImportMapping> {
.cloned(),
ty: *ty,
traced: *traced,
target: None,
}
} else {
ReplacedImportMapping::External {
name_override: None,
ty: *ty,
traced: *traced,
target: None,
}
}
}
......@@ -410,6 +415,7 @@ pub enum ImportMapResult {
name: RcStr,
ty: ExternalType,
traced: ExternalTraced,
target: Option<FileSystemPath>,
},
AliasExternal {
name: RcStr,
......@@ -433,6 +439,7 @@ async fn import_mapping_to_result(
name_override,
ty,
traced,
target,
} => ImportMapResult::External {
name: if let Some(name) = name_override {
name.clone()
......@@ -446,6 +453,7 @@ async fn import_mapping_to_result(
},
ty: *ty,
traced: *traced,
target: target.clone(),
},
ReplacedImportMapping::PrimaryAlternativeExternal {
name,
......
use std::{fmt::Display, io::Write};
use std::{borrow::Cow, fmt::Display, io::Write};
use anyhow::Result;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::{FileContent, FileSystem, VirtualFileSystem, glob::Glob, rope::RopeBuilder};
use turbo_tasks_fs::{
FileContent, FileSystem, FileSystemPath, LinkType, VirtualFileSystem, glob::Glob,
rope::RopeBuilder,
};
use turbo_tasks_hash::{encode_hex, hash_xxh3_hash64};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{AsyncModuleInfo, ChunkItem, ChunkType, ChunkableModule, ChunkingContext},
ident::{AssetIdent, Layer},
module::Module,
module_graph::ModuleGraph,
output::OutputAssetsReference,
output::{
OutputAsset, OutputAssets, OutputAssetsReference, OutputAssetsReferences,
OutputAssetsWithReferenced,
},
raw_module::RawModule,
reference::{ModuleReference, ModuleReferences, TracedModuleReference},
reference_type::ReferenceType,
......@@ -84,20 +91,65 @@ impl Display for CachedExternalType {
#[turbo_tasks::value]
pub struct CachedExternalModule {
request: RcStr,
target: Option<FileSystemPath>,
external_type: CachedExternalType,
analyze_mode: CachedExternalTracingMode,
}
/// For a given package folder inside of node_modules, generate a unique hashed package name.
///
/// E.g. `/path/to/node_modules/@swc/core` becomes `@swc/core-1149fa2b3c4d5e6f`
fn hashed_package_name(folder: &FileSystemPath) -> String {
let hash = encode_hex(hash_xxh3_hash64(&folder.path));
let parent = folder.parent();
let parent = parent.file_name();
let pkg = folder.file_name();
if parent.starts_with('@') {
format!("{parent}/{pkg}-{hash}")
} else {
format!("{pkg}-{hash}")
}
}
impl CachedExternalModule {
/// Rewrites `self.request` to include the hashed package name if `self.target` is set.
pub fn request(&self) -> Cow<'_, str> {
if let Some(target) = &self.target {
let hashed_package = hashed_package_name(target);
let request = if self.request.starts_with('@') {
// Potentially strip off `@org/...`
self.request.split_once('/').unwrap().1
} else {
&*self.request
};
if let Some((_, subpath)) = request.split_once('/') {
// `pkg/subpath` case
Cow::Owned(format!("{hashed_package}/{subpath}"))
} else {
// `pkg` case
Cow::Owned(hashed_package)
}
} else {
Cow::Borrowed(&*self.request)
}
}
}
#[turbo_tasks::value_impl]
impl CachedExternalModule {
#[turbo_tasks::function]
pub fn new(
request: RcStr,
target: Option<FileSystemPath>,
external_type: CachedExternalType,
analyze_mode: CachedExternalTracingMode,
) -> Vc<Self> {
Self::cell(CachedExternalModule {
request,
target,
external_type,
analyze_mode,
})
......@@ -112,7 +164,16 @@ impl CachedExternalModule {
writeln!(
code,
"const mod = await {TURBOPACK_EXTERNAL_IMPORT}({});",
StringifyJs(&self.request)
StringifyJs(&self.request())
)?;
}
CachedExternalType::EcmaScriptViaRequire | CachedExternalType::CommonJs => {
let request = self.request();
writeln!(
code,
"const mod = {TURBOPACK_EXTERNAL_REQUIRE}({}, () => require({}));",
StringifyJs(&request),
StringifyJs(&request)
)?;
}
CachedExternalType::Global => {
......@@ -180,14 +241,6 @@ impl CachedExternalModule {
writeln!(code, "const mod = undefined;")?;
}
}
CachedExternalType::EcmaScriptViaRequire | CachedExternalType::CommonJs => {
writeln!(
code,
"const mod = {TURBOPACK_EXTERNAL_REQUIRE}({}, () => require({}));",
StringifyJs(&self.request),
StringifyJs(&self.request)
)?;
}
}
writeln!(code)?;
......@@ -213,16 +266,26 @@ impl CachedExternalModule {
}
}
/// A separate turbotask to create only a single VirtualFileSystem
#[turbo_tasks::function]
fn externals_fs_root() -> Vc<FileSystemPath> {
VirtualFileSystem::new_with_name(rcstr!("externals")).root()
}
#[turbo_tasks::value_impl]
impl Module for CachedExternalModule {
#[turbo_tasks::function]
async fn ident(&self) -> Result<Vc<AssetIdent>> {
let fs = VirtualFileSystem::new_with_name(rcstr!("externals"));
Ok(AssetIdent::from_path(fs.root().await?.join(&self.request)?)
let mut ident = AssetIdent::from_path(externals_fs_root().await?.join(&self.request)?)
.with_layer(Layer::new(rcstr!("external")))
.with_modifier(self.request.clone())
.with_modifier(self.external_type.to_string().into()))
.with_modifier(self.external_type.to_string().into());
if let Some(target) = &self.target {
ident = ident.with_modifier(target.value_to_string().owned().await?);
}
Ok(ident)
}
#[turbo_tasks::function]
......@@ -379,7 +442,31 @@ pub struct CachedExternalModuleChunkItem {
}
#[turbo_tasks::value_impl]
impl OutputAssetsReference for CachedExternalModuleChunkItem {}
impl OutputAssetsReference for CachedExternalModuleChunkItem {
#[turbo_tasks::function]
async fn references(&self) -> Result<Vc<OutputAssetsWithReferenced>> {
let module = self.module.await?;
let assets = if let Some(target) = &module.target {
ResolvedVc::cell(vec![ResolvedVc::upcast(
ExternalsSymlinkAsset::new(
*self.chunking_context,
hashed_package_name(target).into(),
module.target.clone().unwrap(),
)
.to_resolved()
.await?,
)])
} else {
OutputAssets::empty_resolved()
};
Ok(OutputAssetsWithReferenced {
assets,
referenced_assets: OutputAssets::empty_resolved(),
references: OutputAssetsReferences::empty_resolved(),
}
.cell())
}
}
#[turbo_tasks::value_impl]
impl ChunkItem for CachedExternalModuleChunkItem {
......@@ -472,3 +559,73 @@ impl Module for ModuleWithoutSelfAsync {
// Don't override and use default is_self_async that always returns false
}
#[derive(Debug)]
#[turbo_tasks::value(shared)]
pub struct ExternalsSymlinkAsset {
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
hashed_package: RcStr,
target: FileSystemPath,
}
#[turbo_tasks::value_impl]
impl ExternalsSymlinkAsset {
#[turbo_tasks::function]
pub fn new(
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
hashed_package: RcStr,
target: FileSystemPath,
) -> Vc<Self> {
ExternalsSymlinkAsset {
chunking_context,
hashed_package,
target,
}
.cell()
}
}
#[turbo_tasks::value_impl]
impl OutputAssetsReference for ExternalsSymlinkAsset {}
#[turbo_tasks::value_impl]
impl OutputAsset for ExternalsSymlinkAsset {
#[turbo_tasks::function]
async fn path(&self) -> Result<Vc<FileSystemPath>> {
Ok(self
.chunking_context
.output_root()
.await?
.join("node_modules")?
.join(&self.hashed_package)?
.cell())
}
}
#[turbo_tasks::value_impl]
impl Asset for ExternalsSymlinkAsset {
#[turbo_tasks::function]
async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
let this = self.await?;
// path: [output]/bench/app-router-server/.next/node_modules/lodash-ee4fa714b6d81ca3
// target: [project]/node_modules/.pnpm/lodash@3.10.1/node_modules/lodash
let output_root_to_project_root = this.chunking_context.output_root_to_root_path().await?;
let project_root_to_target = &this.target.path;
let path = self.path().await?;
let path_to_output_root = path
.parent()
.get_relative_path_to(&*this.chunking_context.output_root().await?)
.context("path must be inside output root")?;
let target = format!(
"{path_to_output_root}/{output_root_to_project_root}/{project_root_to_target}",
)
.into();
Ok(AssetContent::Redirect {
target,
link_type: LinkType::DIRECTORY,
}
.cell())
}
}
......@@ -898,8 +898,36 @@ impl AssetContext for ModuleAssetContext {
ProcessResult::Ignore => ModuleResolveResultItem::Ignore,
}
}
ResolveResultItem::External { name, ty, traced } => {
ResolveResultItem::External {
name,
ty,
traced,
target,
} => {
let replacement = if replace_externals {
// Determine the package folder, `target` is the full path to the
// resolved file.
let target = if let Some(mut target) = target {
loop {
let parent = target.parent();
if parent.is_root() {
break;
}
if parent.file_name() == "node_modules" {
break;
}
if parent.file_name().starts_with("@")
&& parent.parent().file_name() == "node_modules"
{
break;
}
target = parent;
}
Some(target)
} else {
None
};
let analyze_mode = if traced == ExternalTraced::Traced
&& let Some(options) = &self
.module_options_context()
......@@ -907,15 +935,22 @@ impl AssetContext for ModuleAssetContext {
.enable_externals_tracing
{
// result.affecting_sources can be ignored for tracing, as this
// request will later be resolved relative to tracing_root
// anyway.
// request will later be resolved relative to tracing_root (or
// the .next/node_modules/lodash-1238123 symlink) anyway.
let options = options.await?;
let origin = PlainResolveOrigin::new(
Vc::upcast(externals_tracing_module_context(
*options.compile_time_info,
)),
options.tracing_root.join("_")?,
// If target is specified, a symlink will be created to
// make the folder
// itself available, but we still need to trace
// resolving the individual file(s) inside the package.
target
.as_ref()
.unwrap_or(&options.tracing_root)
.join("_")?,
);
CachedExternalTracingMode::Traced {
origin: ResolvedVc::upcast(origin.to_resolved().await?),
......@@ -924,7 +959,8 @@ impl AssetContext for ModuleAssetContext {
CachedExternalTracingMode::Untraced
};
replace_external(&name, ty, import_externals, analyze_mode).await?
replace_external(&name, ty, target, import_externals, analyze_mode)
.await?
} else {
None
};
......@@ -1051,6 +1087,7 @@ pub async fn emit_assets_into_dir_operation(
pub async fn replace_external(
name: &RcStr,
ty: ExternalType,
target: Option<FileSystemPath>,
import_externals: bool,
analyze_mode: CachedExternalTracingMode,
) -> Result<Option<ModuleResolveResultItem>> {
......@@ -1071,7 +1108,7 @@ pub async fn replace_external(
}
};
let module = CachedExternalModule::new(name.clone(), external_type, analyze_mode)
let module = CachedExternalModule::new(name.clone(), target, external_type, analyze_mode)
.to_resolved()
.await?;
......
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