Unverified Commit 7b58e588 authored by Benjamin Woodruff ‮'s avatar Benjamin Woodruff Committed by GitHub

Turbopack: Add support for specifying additional roots (#98003)

Full motivation and plan here:
https://app.notion.com/p/vercel/Turbopack-pnpm-Global-Virtual-Store-383e06b059c480579403ddfd71cc2d40?source=copy_link

The goal is to allow `DiskFileSystem` to traverse outside of it's own
root to other configured `DiskFileSystem`s when following symlinks. We
may allow traversal in other situations in the future, but this is
limited to symlink resolution for now.

## Global Virtual Store

The motivation for this is to enable [pnpm's Global Virtual Store
feature](https://pnpm.io/global-virtual-store) (and there are other
package managers doing this, including nub and bun).

We'd expose the ability to manually configure this in `next.config.js`,
but we should also auto-configure ourselves for popular package managers
(or at least make a best effort to do so, the `PNPM_HOME` semantics can
be complicated). The `ignoreIfMissing` option is provided for this
situation: We can configure a bunch of roots automatically, and they
only actually get set up if they exist, the check for directory
existence is cheap.

## NFT changes

This requires a couple extensions to the `*.nft.json` file format:
https://github.com/vercel/next.js/pull/98469

## Related Issues

- #93556
- https://github.com/pnpm/pnpm/issues/14972
parent 469a7c55
......@@ -983,6 +983,7 @@ jobs:
test/e2e/app-dir/app/index.test.ts \
test/e2e/app-dir/app-edge/app-edge.test.ts \
test/e2e/app-dir/proxy-runtime-nodejs/proxy-runtime-nodejs.test.ts \
test/e2e/app-dir/turbopack-additional-roots/turbopack-additional-roots.test.ts \
test/development/app-dir/segment-explorer/segment-explorer.test.ts
stepName: 'test-dev-windows'
runs_on_labels: '["windows-latest-8-core-oss"]'
......
......@@ -34,6 +34,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
swc_core = { workspace = true }
tracing = { workspace = true }
tokio = { workspace = true }
turbo-bincode = { workspace = true }
turbo-rcstr = { workspace = true }
turbo-tasks = { workspace = true }
......
This diff is collapsed.
......@@ -450,7 +450,7 @@ pub async fn analyze_output_assets(
let decoded_source = urlencoding::decode(&chunk_part.source)?;
let source = if let Some(stripped) = decoded_source.strip_prefix(&prefix) {
Cow::Borrowed(stripped)
} else if decoded_source.starts_with("[project]/") {
} else if decoded_source.starts_with('[') && decoded_source.contains("]/") {
decoded_source
} else {
Cow::Owned(format!(
......
......@@ -2,6 +2,7 @@
#![feature(arbitrary_self_types_pointers)]
#![feature(impl_trait_in_assoc_type)]
mod additional_roots;
pub mod aggregate_hmr;
pub mod analyze;
mod app;
......
use anyhow::{Result, bail};
use anyhow::{Context, Result, bail};
use rustc_hash::FxHashMap;
use serde::{Serialize, Serializer, ser::SerializeTuple};
use turbo_rcstr::RcStr;
use turbo_tasks::ResolvedVc;
use turbo_tasks_fs::{FileSystem, FileSystemPath};
use turbo_unix_path::get_relative_path_to;
use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath};
use turbo_unix_path::{get_relative_path_to, sys_to_unix};
use turbopack_core::asset::AssetContent;
use crate::project::Project;
......@@ -102,6 +102,7 @@ pub(crate) struct NftJsonBuilder {
impl NftJsonBuilder {
pub async fn new(project: ResolvedVc<Project>, nft_path: &FileSystemPath) -> Result<Self> {
let project_ref = project.await?;
let mut root_configs = FxHashMap::default();
// Files not listed under `additionalRoots` have paths relative to the nft.json file, which
......@@ -109,6 +110,14 @@ impl NftJsonBuilder {
// their paths can be compared directly even when the output is outside the project.
let project_root = project.project_fs().root().owned().await?;
let output_base = nft_path.parent();
let output_file_system = ResolvedVc::try_downcast_type::<DiskFileSystem>(output_base.fs)
.context("NFT path must use a disk filesystem")?;
let output_base_path = output_file_system.await?.to_sys_path_raw(&output_base);
let output_base_path = sys_to_unix(
output_base_path
.to_str()
.context("NFT path must be valid Unicode")?,
);
root_configs.insert(
project_root.fs,
RootConfig {
......@@ -127,9 +136,26 @@ impl NftJsonBuilder {
},
);
let mut additional_roots = Vec::with_capacity(project_ref.additional_roots.len());
for (name, root) in &project_ref.additional_roots {
let file_system = root.file_system.connect().to_resolved().await?;
root_configs.insert(
ResolvedVc::upcast(file_system),
RootConfig {
base: file_system.root().owned().await?.path,
additional_root_index: Some(additional_roots.len()),
},
);
let root_path = sys_to_unix(&root.canonical_path);
additional_roots.push(AdditionalRootConfig {
name: name.clone(),
path: get_relative_path_to(&output_base_path, &root_path).into(),
});
}
Ok(Self {
root_configs,
additional_roots: Vec::new(),
additional_roots,
asset_refs: Vec::new(),
})
}
......
This diff is collapsed.
......@@ -171,6 +171,7 @@ fn main() {
encryption_key: rcstr!("deadbeef"),
env: vec![],
next_config: include_str!("../nextConfig.json").into(),
additional_roots: vec![],
preview_props: next_api::project::DraftModeOptions {
preview_mode_encryption_key: rcstr!("deadbeef"),
preview_mode_id: rcstr!("test"),
......
......@@ -1406,7 +1406,7 @@ pub async fn try_get_next_package(
context_directory.clone(),
ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined),
Request::parse(Pattern::Constant(rcstr!("next/package.json"))),
node_cjs_resolve_options(root.clone()),
node_cjs_resolve_options(),
);
if let Some(source) = result.await?.first_source() {
Ok(Vc::cell(Some(source.ident().await?.path.parent())))
......
......@@ -212,9 +212,9 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
let mut request_str = request_str.to_string();
let node_resolve_options = if is_esm {
node_esm_resolve_options(lookup_path.root().owned().await?)
node_esm_resolve_options()
} else {
node_cjs_resolve_options(lookup_path.root().owned().await?)
node_cjs_resolve_options()
};
let result_from_original_location = loop {
let node_resolved_from_original_location = resolve(
......@@ -274,8 +274,7 @@ impl AfterResolvePlugin for ExternalCjsModulesResolvePlugin {
// 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).
let node_resolve_options =
node_cjs_resolve_options(lookup_path.root().owned().await?);
let node_resolve_options = node_cjs_resolve_options();
let node_resolved = resolve(
lookup_path.clone(),
reference_type.clone(),
......
......@@ -260,7 +260,7 @@ pub async fn detect_react_compiler_target(
project_path.clone(),
ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined),
Request::parse(Pattern::Constant(rcstr!("react/package.json"))),
node_cjs_resolve_options(project_path.root().owned().await?),
node_cjs_resolve_options(),
);
let Some(source) = react_pkg_result.await?.first_source() else {
......@@ -336,7 +336,7 @@ pub async fn resolve_babel_plugin_react_compiler(
next_package.clone(),
ReferenceType::CommonJs(CommonJsReferenceSubType::Undefined),
Request::parse(Pattern::Constant(BABEL_PLUGIN_REACT_COMPILER_PACKAGE_JSON)),
node_cjs_resolve_options(project_path.root().owned().await?),
node_cjs_resolve_options(),
);
let Some(source) = babel_plugin_result.await?.first_source() else {
BabelPluginReactCompilerResolutionIssue {
......
......@@ -24,7 +24,7 @@ async fn get_typescript_options(
let tsconfigs = read_tsconfigs(
tsconfig_path.read(),
ResolvedVc::upcast(FileSource::new(tsconfig_path.clone()).to_resolved().await?),
node_cjs_resolve_options(tsconfig_path.root().owned().await?),
node_cjs_resolve_options(),
)
.await
.ok();
......@@ -36,7 +36,7 @@ async fn get_typescript_options(
Some(FindContextFileResult::Found(path, _)) => read_tsconfigs(
path.read(),
ResolvedVc::upcast(FileSource::new(path.clone()).to_resolved().await?),
node_cjs_resolve_options(path.root().owned().await?),
node_cjs_resolve_options(),
)
.await
.ok(),
......
......@@ -29,8 +29,8 @@ use next_api::{
RouteOperation,
},
project::{
DebugBuildPaths, DefineEnv, DraftModeOptions, PartialProjectOptions, Project,
ProjectContainer, ProjectOptions, WatchOptions, activate_lazy_chunk_operation,
AdditionalRootConfig, DebugBuildPaths, DefineEnv, DraftModeOptions, PartialProjectOptions,
Project, ProjectContainer, ProjectOptions, WatchOptions, activate_lazy_chunk_operation,
},
project_asset_hashes_manifest::immutable_hashes_manifest_asset_if_enabled,
route::{Endpoint, EndpointGroupKey, Route},
......@@ -148,6 +148,13 @@ pub struct NapiWatchOptions {
pub poll_interval_ms: Option<f64>,
}
#[napi(object)]
pub struct NapiAdditionalRoot {
pub key: RcStr,
pub path: RcStr,
pub ignore_if_missing: Option<bool>,
}
#[napi(object)]
pub struct NapiProjectOptions {
/// An absolute root path (Unix or Windows path) from which all files must be nested under.
......@@ -170,6 +177,9 @@ pub struct NapiProjectOptions {
/// The contents of next.config.js, serialized to JSON.
pub next_config: RcStr,
/// Additional filesystem roots from next.config.js.
pub additional_roots: Vec<NapiAdditionalRoot>,
/// A map of environment variables to use when compiling code.
pub env: Vec<NapiEnvVar>,
......@@ -226,12 +236,6 @@ pub struct NapiProjectOptions {
/// Refer to [`NapiProjectOptions`] for documentation on this struct's fields.
#[napi(object)]
pub struct NapiPartialProjectOptions {
pub root_path: Option<RcStr>,
pub project_path: Option<RcStr>,
pub watch: Option<NapiWatchOptions>,
pub next_config: Option<RcStr>,
pub env: Option<Vec<NapiEnvVar>>,
......@@ -289,8 +293,9 @@ impl From<NapiWatchOptions> for WatchOptions {
}
}
impl From<NapiProjectOptions> for ProjectOptions {
fn from(val: NapiProjectOptions) -> Self {
impl NapiProjectOptions {
fn into_project_options(self) -> ProjectOptions {
let val = self;
let NapiProjectOptions {
root_path,
project_path,
......@@ -298,6 +303,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
dist_dir: _,
watch,
next_config,
additional_roots,
env,
define_env,
dev,
......@@ -319,6 +325,14 @@ impl From<NapiProjectOptions> for ProjectOptions {
project_path,
watch: watch.into(),
next_config,
additional_roots: additional_roots
.into_iter()
.map(|root| AdditionalRootConfig {
key: root.key,
path: root.path,
ignore_if_missing: root.ignore_if_missing.unwrap_or(false),
})
.collect(),
env: env.into_iter().map(|var| (var.name, var.value)).collect(),
define_env: define_env.into(),
dev,
......@@ -341,12 +355,10 @@ impl From<NapiProjectOptions> for ProjectOptions {
}
}
impl From<NapiPartialProjectOptions> for PartialProjectOptions {
fn from(val: NapiPartialProjectOptions) -> Self {
impl NapiPartialProjectOptions {
fn into_partial_project_options(self) -> PartialProjectOptions {
let val = self;
let NapiPartialProjectOptions {
root_path,
project_path,
watch,
next_config,
env,
define_env,
......@@ -359,9 +371,6 @@ impl From<NapiPartialProjectOptions> for PartialProjectOptions {
write_routes_hashes_manifest,
} = val;
PartialProjectOptions {
root_path,
project_path,
watch: watch.map(From::from),
next_config,
env: env.map(|env| env.into_iter().map(|var| (var.name, var.value)).collect()),
define_env: define_env.map(|env| env.into()),
......@@ -408,13 +417,19 @@ pub struct ProjectInstance {
_container_gc_root: GcRoot<ProjectContainer>,
}
#[napi(ts_return_type = "Promise<{ __napiType: \"Project\" }>")]
#[napi(object, object_from_js = false)]
pub struct NapiProject {
#[napi(ts_type = "{ __napiType: \"Project\" }")]
pub project: External<ProjectInstance>,
}
#[napi(ts_return_type = "Promise<TurbopackResult<{ project: { __napiType: \"Project\" } }>>")]
pub fn project_new<'env>(
env: &'env Env,
mut options: NapiProjectOptions,
turbo_engine_options: NapiTurboEngineOptions,
napi_callbacks: NapiNextTurbopackCallbacksJsObject,
) -> napi::Result<PromiseRaw<'env, External<ProjectInstance>>> {
) -> napi::Result<PromiseRaw<'env, TurbopackResult<NapiProject>>> {
let napi_callbacks = NapiNextTurbopackCallbacks::from_js(env, napi_callbacks)?;
let (exit, exit_receiver) = ExitHandler::new_receiver();
......@@ -597,16 +612,17 @@ pub fn project_new<'env>(
});
}
let options = ProjectOptions::from(options);
let options = options.into_project_options();
let is_dev = options.dev;
let root_path = options.root_path.clone();
let (container, container_op) = turbo_tasks
let (container, container_op, initialization_issues) = turbo_tasks
.run(async move {
let container_op = ProjectContainer::new_operation(rcstr!("next.js"), is_dev);
ProjectContainer::initialize(container_op, options).await?;
let initialization_issues =
ProjectContainer::initialize(container_op, options).await?;
let container = container_op.resolve().strongly_consistent().await?;
// Return the operation itself so we can pin it below
Ok((container, container_op))
Ok((container, container_op, initialization_issues))
})
.or_else(|e| turbopack_ctx.throw_turbopack_internal_result(&e.into()))
.await?;
......@@ -647,12 +663,20 @@ pub fn project_new<'env>(
});
}
Ok(External::new(ProjectInstance {
turbopack_ctx,
container,
exit_receiver: Mutex::new(Some(exit_receiver)),
_container_gc_root: container_gc_root,
}))
Ok(TurbopackResult {
result: NapiProject {
project: External::new(ProjectInstance {
turbopack_ctx,
container,
exit_receiver: Mutex::new(Some(exit_receiver)),
_container_gc_root: container_gc_root,
}),
},
issues: initialization_issues
.iter()
.map(|issue| NapiIssue::from(&**issue))
.collect(),
})
}
.instrument(tracing::info_span!("create project")),
)
......@@ -741,7 +765,7 @@ pub async fn project_update(
options: NapiPartialProjectOptions,
) -> napi::Result<()> {
let ctx = &project.turbopack_ctx;
let options = options.into();
let options = options.into_partial_project_options();
let container = project.container;
ctx.turbo_tasks()
.run(async move { container.update(options).await })
......
......@@ -19,6 +19,17 @@ Next.js' production server is also traced for its needed files and output at `.n
To leverage the `.nft.json` files emitted to the `.next` output directory, you can read the list of files in each trace that are relative to the `.nft.json` file and then copy them to your deployment location.
### Turbopack NFT extensions
Turbopack `.nft.json` files include `fileHashes` and `symlinks` extensions:
- `fileHashes` is a parallel array with the same length and ordering as `files`. For example, `fileHashes[0]` is the hash for `files[0]`. A consumer can use the hash as a content identifier for caching or deduplicating traced assets.
- `symlinks` maps indexes in the sibling `files` array to their immediate targets. When `symlinks` is present, files without a corresponding entry can be assumed to be normal files or directories.
Traces that use [`experimental.turbopackAdditionalRoots`](/docs/app/api-reference/config/next-config-js/turbopack#additional-roots-experimental) also include the `additionalRoots` extension:
- `additionalRoots` is an ordered list of named source roots. Each root has its own `files`, `fileHashes`, and `symlinks` lists. Its `path` is relative to the directory containing the `.nft.json` file and identifies the source location on the build machine. `additionalRoots` names match those provided in `next.config.js` and are guaranteed to be valid directory names on most operating systems and filesystems.
## Automatically Copying Traced Files
Next.js can automatically create a `standalone` folder that copies only the necessary files for a production deployment including select files in `node_modules`.
......@@ -33,6 +44,8 @@ module.exports = {
This will create a folder at `.next/standalone` which can then be deployed on its own without installing `node_modules`.
On Windows, creating directory symlinks [can require elevated privileges or Developer Mode](https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10/). If standalone generation must fall back to a junction point, Windows stores an absolute target and that particular output is not relocatable.
Additionally, a minimal `server.js` file is also output which can be used instead of `next start`. This minimal server does not copy the `public` or `.next/static` folders by default as these should ideally be handled by a CDN instead, although these folders can be copied to the `standalone/public` and `standalone/.next/static` folders manually, after which `server.js` file will serve these automatically.
To copy these manually, you can use the `cp` command-line tool after you `next build`:
......
......@@ -91,7 +91,7 @@ If you have a loader that is critically dependent upon one of these features ple
Turbopack uses the root directory to resolve modules. Files outside of the project root are not resolved.
The reason files are not resolved outside of the project root is to improve cache validation, reduce filesystem watching overhead, and reduce the number of resolving steps needed.
Files are not resolved outside of the project root is to improve cache validation, reduce filesystem watching overhead, and reduce the number of [resolving steps](https://nodejs.org/api/esm.html#resolution-algorithm) needed.
Next.js automatically detects the root directory of your project. It does so by looking for one of these files:
......@@ -112,9 +112,44 @@ module.exports = {
}
```
To resolve files from linked dependencies outside the project root (via `npm link`, `yarn link`, `pnpm link`, etc.), you must configure the `turbopack.root` to the parent directory of both the project and the linked dependencies.
To resolve files from linked dependencies outside the project root (via `npm link`, `yarn link`, `pnpm link`, etc.), you must either configure the `turbopack.root` to the parent directory of both the project and the linked dependencies or configure an additional root.
While this expands the scope of filesystem watching, it's typically only necessary during development when actively working on linked packages.
Do not extend the root directory too broadly (e.g. to your home directory). Turbopack may watch all files inside of roots, and configuring too broad of a root directory can cause significant performance problems.
### Additional roots (experimental)
`experimental.turbopackAdditionalRoots` allows Turbopack to follow symbolic links whose targets are outside `turbopack.root`. It is useful for linked packages that live outside the project.
Additional roots are read-only. Additional roots can only be crossed at symlink boundaries. Direct relative imports that escape a root are unsupported.
```js filename="next.config.js"
const path = require('path')
module.exports = {
experimental: {
turbopackAdditionalRoots: {
linkedPackages: { path: path.join(__dirname, '../packages') },
},
},
}
```
Each key identifies one root. `path` can be absolute or relative to the directory where you run Next.js.
If a root path is not found when `next build` or `next dev` starts, a warning will be issued, unless `ignoreIfMissing` is set to `true` (defaults to false).
To ensure portability of your configuration across a variety of platforms, including Windows, a root name must meet all of these requirements:
- It contains 1 to 40 characters.
- Each character must be an ASCII letter (`a-z` or `A-Z`), a digit (`0-9`), an underscore (`_`), or a hyphen (`-`).
- It is not a Windows device name.
- It does not duplicate an earlier name under ASCII case-insensitive comparison.
To avoid ambiguous references to files, roots may not contain overlapping paths. For example, configuring both `foo/` and `foo/bar/` as roots would produce a warning, and the last-configured value will be ignored.
Additional roots changes the [`trace format`](/docs/app/api-reference/config/next-config-js/output#turbopack-nft-extensions) and requires support from the [build adapter](/docs/app/api-reference/adapters).
When using [`output: "standalone"`](/docs/app/api-reference/config/next-config-js/output#automatically-copying-traced-files), unbundled files stored in these additional roots will be copied to a subdirectory of the output directory containing the configured name of the root.
### Configuring webpack loaders
......@@ -395,6 +430,7 @@ The option automatically adds a polyfill for debug IDs to the JavaScript bundle
| Version | Changes |
| -------- | ---------------------------------------------------- |
| `16.4.0` | `experimental.turbopackAdditionalRoots` was added |
| `16.2.0` | `turbopackLoader` import attributes were added. |
| `16.2.0` | `turbopack.rules.*.type` was added. |
| `16.2.0` | `turbopack.rules.*.condition.contentType` was added. |
......
......@@ -344,9 +344,9 @@ There are a number of non-trivial behavior differences between webpack and Turbo
Turbopack uses the root directory to resolve modules. Files outside of the project root are not resolved.
For example, when linking dependencies outside the project root (via `npm link`, `yarn link`, `pnpm link`, etc.), those linked files will not be resolved by default. To resolve these files, you must configure the root option to the parent directory of both the project and the linked dependencies.
For example, linked dependencies outside the project root (via `npm link`, `yarn link`, `pnpm link`, etc.) are not resolved by default. Configure [`experimental.turbopackAdditionalRoots`](/docs/app/api-reference/config/next-config-js/turbopack#additional-roots-experimental) for symlinked dependencies.
You can configure the filesystem root using [turbopack.root](/docs/app/api-reference/config/next-config-js/turbopack#root-directory) option in `next.config.js`.
Use [`turbopack.root`](/docs/app/api-reference/config/next-config-js/turbopack#root-directory) when your application directly imports files outside the detected root rather than reaching them through symlinks.
### CSS Module Ordering
......
......@@ -7,11 +7,12 @@ export interface NftFileList {
* the current root when inside `NftAdditionalRoot`.
*
* When using webpack, these paths may exist outside the tracing root. The
* [`@vercel/next` package](https://github.com/vercel/vercel/blob/%40vercel/next%404.20.5/packages/next/src/server-build.ts#L1022-L1026)
* ignores these paths.
* [`@vercel/next` package][@vercel/next] ignores these paths.
*
* When using Turbopack, these paths are guaranteed to exist within the
* `turbopack.root` specified or inferred from `next.config.js`.
*
* [@vercel/next]: https://github.com/vercel/vercel/blob/%40vercel/next%404.20.5/packages/next/src/server-build.ts#L1022-L1026
*/
files: string[]
/**
......@@ -55,7 +56,7 @@ export interface NftAdditionalRoot extends NftFileList {
/**
* Stable unique identifier provided in `next.config.js`. This can be used to
* generate the output path where these files are copied, such as
* `nextAdditionalRoots/${name}`.
* `next_additional_roots/${name}`.
*
* This uses a character set that is valid on most filesystems, and identifiers
* are guaranteed not to overlap on case-insensitive filesystems.
......@@ -175,7 +176,7 @@ function mapAdditionalRootPath(
}
return {
source,
destination: path.join('nextAdditionalRoots', root.name, relativePath),
destination: path.join('next_additional_roots', root.name, relativePath),
}
}
......
......@@ -6,9 +6,9 @@ export function formatWarningsHeader(count: number): string {
}
/**
* Processes and reports build issues from Turbopack entrypoints.
* Processes and reports build issues from Turbopack's N-API functions.
*
* @param entrypoints - The result object containing build issues to process.
* @param result - The result object containing build issues to process.
* @param isDev - A flag indicating if the build is running in development mode.
* @param opts.deferWarnings - When true, warnings are returned instead of
* printed so the caller can print them later.
......@@ -17,7 +17,7 @@ export function formatWarningsHeader(count: number): string {
* 'fatal' and 'bug' issues. In production mode, we also throw on 'error' issues.
*/
export function printBuildErrors<T>(
entrypoints: TurbopackResult<T>,
result: TurbopackResult<T>,
isDev: boolean,
opts?: { deferWarnings?: boolean }
): { warnings: string[] } {
......@@ -33,7 +33,7 @@ export function printBuildErrors<T>(
const seenErrors = new Set<string>()
const seenWarnings = new Set<string>()
for (const issue of entrypoints.issues) {
for (const issue of result.issues) {
// We only want to completely shut down the server
if (issue.severity === 'fatal' || issue.severity === 'bug') {
const formatted = formatIssue(issue)
......
......@@ -203,6 +203,12 @@ export interface NapiAdditionalIssueSource {
codeFrame?: string
}
export interface NapiAdditionalRoot {
key: RcStr
path: RcStr
ignoreIfMissing?: boolean
}
export interface NapiAssetPath {
path: RcStr
contentHash: RcStr
......@@ -361,9 +367,6 @@ export interface NapiOptionEnvVar {
* Refer to [`NapiProjectOptions`] for documentation on this struct's fields.
*/
export interface NapiPartialProjectOptions {
rootPath?: RcStr
projectPath?: RcStr
watch?: NapiWatchOptions
nextConfig?: RcStr
env?: Array<NapiEnvVar>
defineEnv?: NapiDefineEnv
......@@ -376,6 +379,10 @@ export interface NapiPartialProjectOptions {
noMangling?: boolean
}
export interface NapiProject {
project: { __napiType: 'Project' }
}
export interface NapiProjectOptions {
/**
* An absolute root path (Unix or Windows path) from which all files must be nested under.
......@@ -398,6 +405,8 @@ export interface NapiProjectOptions {
watch: NapiWatchOptions
/** The contents of next.config.js, serialized to JSON. */
nextConfig: RcStr
/** Additional filesystem roots from next.config.js. */
additionalRoots: Array<NapiAdditionalRoot>
/** A map of environment variables to use when compiling code. */
env: Array<NapiEnvVar>
/**
......@@ -509,10 +518,6 @@ export interface NapiTurboEngineOptions {
gc?: NapiTurbopackGcOptions
}
/**
* Tuning for Turbopack's reference-counting GC, mirroring the
* `experimental.turbopackGc` config option.
*/
export interface NapiTurbopackGcOptions {
/** How long a GC pass runs before it will honour an interrupt, in milliseconds. */
minProgressMs?: number
......@@ -664,7 +669,7 @@ export declare function projectNew(
options: NapiProjectOptions,
turboEngineOptions: NapiTurboEngineOptions,
napiCallbacks: NapiNextTurbopackCallbacksJsObject
): Promise<{ __napiType: 'Project' }>
): Promise<TurbopackResult<{ project: { __napiType: 'Project' } }>>
/**
* Runs exit handlers for the project registered using the [`ExitHandler`] API.
......
......@@ -653,8 +653,12 @@ function bindingToApi(
async function rustifyProjectOptions(
options: ProjectOptions
): Promise<NapiProjectOptions> {
const additionalRoots = Object.entries(
options.nextConfig.experimental.turbopackAdditionalRoots ?? {}
).map(([key, root]) => ({ key, ...root }))
return {
...options,
additionalRoots,
nextConfig: await serializeNextConfig(
options.nextConfig,
path.join(options.rootPath, options.projectPath)
......@@ -664,16 +668,14 @@ function bindingToApi(
}
async function rustifyPartialProjectOptions(
options: PartialProjectOptions
options: PartialProjectOptions,
projectPath: string
): Promise<NapiPartialProjectOptions> {
return {
...options,
nextConfig:
options.nextConfig &&
(await serializeNextConfig(
options.nextConfig,
path.join(options.rootPath, options.projectPath)
)),
(await serializeNextConfig(options.nextConfig, projectPath)),
env: options.env && rustifyEnv(options.env),
}
}
......@@ -681,7 +683,10 @@ function bindingToApi(
class ProjectImpl implements Project {
private readonly _nativeProject: { __napiType: 'Project' }
constructor(nativeProject: { __napiType: 'Project' }) {
constructor(
nativeProject: { __napiType: 'Project' },
private readonly projectPath: string
) {
this._nativeProject = nativeProject
if (typeof binding.registerWorkerScheduler === 'function') {
......@@ -692,7 +697,7 @@ function bindingToApi(
async update(options: PartialProjectOptions) {
await binding.projectUpdate(
this._nativeProject,
await rustifyPartialProjectOptions(options)
await rustifyPartialProjectOptions(options, this.projectPath)
)
}
......@@ -1276,18 +1281,23 @@ function bindingToApi(
turboEngineOptions,
callbacks?: import('./types').TurbopackProjectCallbacks
) {
return new ProjectImpl(
await binding.projectNew(
await rustifyProjectOptions(options),
turboEngineOptions,
{
throwTurbopackInternalError: (
require('../../shared/lib/turbopack/internal-error') as typeof import('../../shared/lib/turbopack/internal-error')
).throwTurbopackInternalError,
onBeforeDeferredEntries: callbacks?.onBeforeDeferredEntries,
}
)
const { value, issues } = await binding.projectNew(
await rustifyProjectOptions(options),
turboEngineOptions,
{
throwTurbopackInternalError: (
require('../../shared/lib/turbopack/internal-error') as typeof import('../../shared/lib/turbopack/internal-error')
).throwTurbopackInternalError,
onBeforeDeferredEntries: callbacks?.onBeforeDeferredEntries,
}
)
return {
value: new ProjectImpl(
value.project,
path.join(options.rootPath, options.projectPath)
),
issues,
}
}
}
......@@ -1419,7 +1429,7 @@ async function loadWasm(importPath = '') {
_options: ProjectOptions,
_turboEngineOptions: TurboEngineOptions,
_callbacks?: import('./types').TurbopackProjectCallbacks | undefined
): Promise<Project> {
): Promise<TurbopackResult<Project>> {
throw new Error(
`Turbopack is not supported on this platform (${PlatformName}/${ArchName}) because native bindings are not available. ` +
`Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings. ` +
......
......@@ -44,7 +44,7 @@ export interface Binding {
options: ProjectOptions,
turboEngineOptions: NapiTurboEngineOptions,
callbacks?: TurbopackProjectCallbacks
): Promise<Project>
): Promise<TurbopackResult<Project>>
startTurbopackTraceServerHandle(
traceFilePath: string,
port: number | undefined
......@@ -499,7 +499,7 @@ export type WrittenEndpoint =
}
export interface ProjectOptions
extends Omit<NapiProjectOptions, 'nextConfig' | 'env'> {
extends Omit<NapiProjectOptions, 'nextConfig' | 'additionalRoots' | 'env'> {
/**
* The next.config.js contents.
*/
......@@ -513,8 +513,6 @@ export interface ProjectOptions
export interface PartialProjectOptions
extends Omit<NapiPartialProjectOptions, 'nextConfig' | 'env'> {
rootPath: NapiProjectOptions['rootPath']
projectPath: NapiProjectOptions['projectPath']
/**
* The next.config.js contents.
*/
......
......@@ -10,6 +10,7 @@ import { getSupportedBrowsers } from '../get-supported-browsers'
import { trace } from '../../trace'
import { normalizePath } from '../../lib/normalize-path'
import { PHASE_PRODUCTION_BUILD } from '../../shared/lib/constants'
import { printBuildErrors } from '../print-build-errors'
export type AnalyzeContext = {
config: NextConfigComplete
......@@ -51,7 +52,7 @@ export async function turbopackAnalyze(
const persistentCaching =
config.experimental?.turbopackFileSystemCacheForBuild || false
const rootPath = config.turbopack?.root || config.outputFileTracingRoot || dir
const project = await bindings.turbo.createProject(
const projectResult = await bindings.turbo.createProject(
{
rootPath: config.turbopack?.root || config.outputFileTracingRoot || dir,
projectPath: normalizePath(path.relative(rootPath, dir) || '.'),
......@@ -100,8 +101,10 @@ export async function turbopackAnalyze(
isShortSession: true,
}
)
const project = projectResult.value
try {
printBuildErrors(projectResult, dev)
const analyzeEventsSpan = trace('turbopack-analyze-events')
// Stop immediately: this span is only used as a parent for
// manualTraceChild calls which carry their own timestamps.
......
......@@ -122,7 +122,7 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{
const sriEnabled = Boolean(config.experimental.sri?.algorithm)
const project = await bindings.turbo.createProject(
const projectResult = await bindings.turbo.createProject(
{
...sharedProjectOptions,
debugBuildPaths: NextBuildContext.debugBuildPaths,
......@@ -143,6 +143,7 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{
}
: undefined
)
const project = projectResult.value
const shutdownController = new AbortController()
const compilationEvents = backgroundLogCompilationEvents(project, {
// Compilation events carry their own timestamps, so they hang directly off
......@@ -162,6 +163,8 @@ export async function turbopackBuild(telemetry: Telemetry): Promise<{
}
try {
printBuildErrors(projectResult, dev)
// Write an empty file in a known location to signal this was built with Turbopack
await fs.writeFile(path.join(distDir, 'turbopack'), '')
......
......@@ -196,6 +196,15 @@ export const experimentalSchema = {
.union([z.enum(['security', 'latest', 'future']), z.literal(false)])
.optional(),
agentFeedback: z.boolean().optional(),
turbopackAdditionalRoots: z
.record(
z.string(),
z.strictObject({
path: z.string(),
ignoreIfMissing: z.boolean().optional(),
})
)
.optional(),
outputHashSalt: z.string().optional(),
useSkewCookie: z.boolean().optional(),
after: z.boolean().optional(),
......
......@@ -496,6 +496,20 @@ export interface ExperimentalConfig {
* agents prepare anonymized Next.js feedback for user review.
*/
agentFeedback?: boolean
/**
* Additional filesystem roots that symlinked dependencies may resolve into.
* Relative paths are resolved from the current working directory.
*
* Root names must contain 1-40 characters, using only ASCII letters, digits,
* underscores, or hyphens. They must not be Windows device names and must be
* unique under ASCII case-insensitive comparison. Invalid roots produce a
* warning and are ignored.
*/
turbopackAdditionalRoots?: Record<
string,
{ path: string; ignoreIfMissing?: boolean }
>
/**
* @deprecated Use the top-level `outputHashSalt` option instead.
*/
......
......@@ -494,7 +494,7 @@ export async function createHotReloaderTurbopack(
})
}
const project = await bindings.turbo.createProject(
const projectResult = await bindings.turbo.createProject(
{
rootPath,
projectPath: normalizePath(relative(rootPath, projectPath) || '.'),
......@@ -539,6 +539,10 @@ export async function createHotReloaderTurbopack(
isShortSession: false,
}
)
for (const issue of projectResult.issues) {
printNonFatalIssue(issue)
}
const project = projectResult.value
backgroundLogCompilationEvents(project, {
eventTypes: [
'StartupCacheInvalidationEvent',
......
......@@ -88,7 +88,6 @@ import {
} from '../../../shared/lib/turbopack/utils'
import { getDefineEnv } from '../../../build/define-env'
import { TurbopackInternalError } from '../../../shared/lib/turbopack/internal-error'
import { normalizePath } from '../../../lib/normalize-path'
import { recursiveReadDir } from '../../../lib/recursive-readdir'
import {
JSON_CONTENT_TYPE_HEADER,
......@@ -942,10 +941,6 @@ async function startWatcher(
opts.fsChecker.rewrites.beforeFiles.length > 0 ||
opts.fsChecker.rewrites.fallback.length > 0
const rootPath =
opts.nextConfig.turbopack?.root ||
opts.nextConfig.outputFileTracingRoot ||
opts.dir
await hotReloader.turbopackProject.update({
defineEnv: createDefineEnv({
isTurbopack: true,
......@@ -961,8 +956,6 @@ async function startWatcher(
projectPath: opts.dir,
rewrites: opts.fsChecker.rewrites,
}),
rootPath,
projectPath: normalizePath(path.relative(rootPath, dir)),
})
} else {
let tsconfigResult:
......
......@@ -162,7 +162,7 @@ async function main() {
const bindings = await loadBindings();
const rootPath = __dirname;
const distDir = '.next';
const project = await bindings.turbo.createProject({
const projectResult = await bindings.turbo.createProject({
env: {},
nextConfig: nextConfig,
rootPath,
......@@ -204,6 +204,12 @@ async function main() {
}, {
turbopackMemoryEviction: 'off',
});
if (projectResult.issues.length > 0) {
throw new Error(
\`Project initialization failed: \${JSON.stringify(projectResult.issues)}\`
);
}
const project = projectResult.value;
const entrypointsSubscription = project.entrypointsSubscribe();
const entrypoints = (await entrypointsSubscription.next()).value.value;
......@@ -316,7 +322,7 @@ describe('next.rs api', () => {
? path.resolve(__dirname, '../../..')
: next.testDir
const distDir = '.next'
project = await bindings.turbo.createProject(
const projectResult = await bindings.turbo.createProject(
{
env: {},
nextConfig: nextConfig,
......@@ -361,6 +367,13 @@ describe('next.rs api', () => {
turbopackMemoryEviction: 'off' as MemoryEvictionMode,
}
)
const initializationIssues = normalizeIssues(projectResult.issues)
if (initializationIssues.length > 0) {
throw new Error(
`Project initialization failed:\n${JSON.stringify(initializationIssues, null, 2)}`
)
}
project = projectResult.value
projectUpdateSubscription = filterMapAsyncIterator(
project.updateInfoSubscribe(1000),
(update) => (update.updateType === 'end' ? update.value : undefined)
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import linked from '../linked'
export default function Page() {
return <p id="value">{linked.value}</p>
}
const sibling = require('sibling')
const { formatUrl } = require('next/dist/shared/lib/router/utils/format-url')
module.exports = {
value: `linked-${sibling.value}-${formatUrl({ pathname: '/next-plugin' })}`,
}
import { isNextStart, nextTestSetup } from 'e2e-utils'
import fs from 'fs-extra'
import os from 'os'
import path from 'path'
import {
fetchViaHTTP,
findPort,
initNextServerScript,
killApp,
retry,
} from 'next-test-utils'
// Deploy only uploads `project`, but this suite intentionally uses a sibling filesystem root.
//
// @force-gate turbopack && !deploy
describe('turbopack additional roots', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
subDir: 'project',
nextConfig: {
output: 'standalone',
serverExternalPackages: ['sibling'],
experimental: {
turbopackAdditionalRoots: {
linkedPackages: { path: '../additional-root' },
missingOptional: {
path: './missing-optional-root',
ignoreIfMissing: false,
},
},
},
},
skipStart: true,
})
let externalRoot: string
let linkedPackage: string
beforeAll(async () => {
externalRoot = path.resolve(next.testDir, '../additional-root')
linkedPackage = path.join(externalRoot, 'packages/linked')
await fs.copy(
path.join(__dirname, 'fixtures/additional-root'),
externalRoot
)
await fs.symlink(
linkedPackage,
path.join(next.testDir, 'linked'),
'junction' // use a junction point on windows (this argument is ignored everywhere else)
)
await next.start()
})
afterAll(async () => {
await next.stop()
await fs.remove(externalRoot)
})
it('resolves a linked package, sibling dependency, and next/dist', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('#value').text()).toBe(
'linked-initial-/next-plugin'
)
})
it('reports initialization warnings when startup succeeds', () => {
expect(next.cliOutput).toContain('Invalid Turbopack additional root')
})
if (isNextDev) {
it('tracks updates in an additional root', async () => {
const browser = await next.browser('/')
await next.patchFile(
'../additional-root/packages/linked/index.js',
(content) => content.replace('linked-', 'updated-'),
async () => {
await retry(async () => {
expect(await browser.elementByCss('#value').text()).toBe(
'updated-initial-/next-plugin'
)
})
}
)
})
}
if (isNextStart) {
it('emits additional-root files and cross-root symlinks in the NFT', async () => {
const nftPath = path.join(
next.testDir,
'.next/server/app/page.js.nft.json'
)
const nft = await fs.readJson(nftPath)
const crossRootSymlinks = nft.symlinks
.filter((symlink: [number, string, number?]) => symlink.length === 3)
.map(
([fileIndex, target, additionalRootIndex]: [
number,
string,
number,
]) => ({
file: nft.files[fileIndex],
target,
additionalRoot: nft.additionalRoots[additionalRootIndex].name,
})
)
const additionalRoots = nft.additionalRoots.map((root: any) => {
const copy = { ...root }
delete copy.fileHashes
return copy
})
expect(crossRootSymlinks).toMatchInlineSnapshot(`
[
{
"additionalRoot": "linkedPackages",
"file": "../../node_modules/sibling-639f6b1f4617eee0",
"target": "node_modules/sibling",
},
]
`)
expect(additionalRoots).toMatchInlineSnapshot(`
[
{
"files": [
"node_modules/sibling/index.js",
"node_modules/sibling/package.json",
],
"name": "linkedPackages",
"path": "../../../../additional-root",
"symlinks": [],
},
]
`)
})
it('runs after relocating standalone output away from the source root', async () => {
await next.stop()
const temporaryDirectory = await fs.mkdtemp(
path.join(os.tmpdir(), 'next-additional-roots-')
)
const standaloneDirectory = path.join(temporaryDirectory, 'standalone')
let server: any
try {
await fs.move(
path.join(next.testDir, '.next/standalone'),
standaloneDirectory
)
await fs.remove(externalRoot)
const stagedRoot = path.join(
standaloneDirectory,
'next_additional_roots',
'linkedPackages'
)
expect(
await fs.pathExists(
path.join(stagedRoot, 'node_modules/sibling/index.js')
)
).toBe(true)
const nodeModulesDirectory = path.join(
standaloneDirectory,
'.next/node_modules'
)
const linkName = (await fs.readdir(nodeModulesDirectory)).find((name) =>
name.startsWith('sibling-')
)
expect(linkName).toBeDefined()
const linkPath = path.join(nodeModulesDirectory, linkName!)
const linkTarget = await fs.readlink(linkPath)
expect(path.isAbsolute(linkTarget)).toBe(false)
expect(path.resolve(nodeModulesDirectory, linkTarget)).toBe(
path.join(stagedRoot, 'node_modules/sibling')
)
const appPort = await findPort()
server = await initNextServerScript(
path.join(standaloneDirectory, 'server.js'),
/- Local:/,
{
...process.env,
...next.env,
PORT: appPort.toString(),
},
undefined,
{ cwd: standaloneDirectory }
)
const response = await fetchViaHTTP(appPort, '/')
expect(response.status).toBe(200)
expect(await response.text()).toContain('linked-initial-/next-plugin')
} finally {
if (server) await killApp(server)
await fs.remove(temporaryDirectory)
}
})
}
})
......@@ -1397,10 +1397,9 @@ async fn find_package(
for resolve_modules in &options.modules {
match resolve_modules {
ResolveModules::Nested(root, names) => {
ResolveModules::Nested(names) => {
let mut lookup_path = lookup_path.clone();
let mut lookup_path_value = lookup_path.clone();
while lookup_path_value.is_inside_ref(root) {
loop {
for name in names.iter() {
let fs_path = lookup_path.join(name)?;
if let Some(fs_path) = dir_exists(
......@@ -1430,12 +1429,10 @@ async fn find_package(
}
}
}
lookup_path = lookup_path.parent();
let new_context_value = lookup_path.clone();
if new_context_value == lookup_path_value {
if lookup_path.is_root() {
break;
}
lookup_path_value = new_context_value;
lookup_path = lookup_path.parent();
}
}
ResolveModules::Path {
......@@ -3070,13 +3067,8 @@ async fn resolve_import_map_result(
alias_lookup_path.clone(),
request,
match ty {
// TODO is that root correct?
ExternalType::CommonJs => {
node_cjs_resolve_options(alias_lookup_path.root().owned().await?)
}
ExternalType::EcmaScriptModule => {
node_esm_resolve_options(alias_lookup_path.root().owned().await?)
}
ExternalType::CommonJs => node_cjs_resolve_options(),
ExternalType::EcmaScriptModule => node_esm_resolve_options(),
ExternalType::Script | ExternalType::Url | ExternalType::Global => options,
},
)
......@@ -3898,7 +3890,7 @@ mod tests {
let extensions = custom_extensions
.unwrap_or_else(|| vec![rcstr!(".ts"), rcstr!(".js"), rcstr!(".json")]);
let mut options_value = node_esm_resolve_options(lookup_path.clone())
let mut options_value = node_esm_resolve_options()
.with_fully_specified(fully_specified)
.with_extensions(extensions)
.owned()
......
use turbo_rcstr::rcstr;
use turbo_tasks::Vc;
use turbo_tasks_fs::FileSystemPath;
use super::options::{
ConditionValue, ResolutionConditions, ResolveInPackage, ResolveIntoPackage, ResolveModules,
......@@ -8,7 +7,7 @@ use super::options::{
};
#[turbo_tasks::function]
pub fn node_cjs_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
pub fn node_cjs_resolve_options() -> Vc<ResolveOptions> {
let conditions: ResolutionConditions = [
(rcstr!("node"), ConditionValue::Set),
(rcstr!("require"), ConditionValue::Set),
......@@ -17,7 +16,7 @@ pub fn node_cjs_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
let extensions = vec![rcstr!(".js"), rcstr!(".json"), rcstr!(".node")];
ResolveOptions {
extensions,
modules: vec![ResolveModules::Nested(root, vec![rcstr!("node_modules")])],
modules: vec![ResolveModules::Nested(vec![rcstr!("node_modules")])],
into_package: vec![
ResolveIntoPackage::ExportsField {
conditions: conditions.clone(),
......@@ -38,7 +37,7 @@ pub fn node_cjs_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
}
#[turbo_tasks::function]
pub fn node_esm_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
pub fn node_esm_resolve_options() -> Vc<ResolveOptions> {
let conditions: ResolutionConditions = [
(rcstr!("node"), ConditionValue::Set),
(rcstr!("import"), ConditionValue::Set),
......@@ -48,7 +47,7 @@ pub fn node_esm_resolve_options(root: FileSystemPath) -> Vc<ResolveOptions> {
ResolveOptions {
fully_specified: true,
extensions,
modules: vec![ResolveModules::Nested(root, vec![rcstr!("node_modules")])],
modules: vec![ResolveModules::Nested(vec![rcstr!("node_modules")])],
into_package: vec![
ResolveIntoPackage::ExportsField {
conditions: conditions.clone(),
......
......@@ -29,9 +29,8 @@ pub struct ExcludedExtensions(#[bincode(with = "turbo_bincode::indexset")] pub F
TraceRawVcs, Hash, PartialEq, Eq, Clone, Debug, ValueDebugFormat, NonLocalValue, Encode, Decode,
)]
pub enum ResolveModules {
/// when inside of path, use the list of directories to
/// resolve inside these
Nested(FileSystemPath, Vec<RcStr>),
/// Starting from the lookup path, look for modules in these directories at each parent.
Nested(Vec<RcStr>),
/// look into that directory, unless the request has an excluded extension
Path {
dir: FileSystemPath,
......
......@@ -1860,9 +1860,14 @@ pub async fn read_matches(
FileSystemEntryType::Directory
)
{
results.push((
nested.push((
pos,
PatternMatch::Directory(prefix.clone().into(), fs_path),
read_matches(
target.file_system_path().clone(),
prefix.clone().into(),
true,
pattern,
),
));
}
}
......
......@@ -38,7 +38,11 @@ impl AfterResolvePluginCondition {
pub fn matches(&self, fs_path: &FileSystemPath) -> bool {
match self {
AfterResolvePluginCondition::Glob { root, glob } => {
root.get_path_to(fs_path).is_some_and(|p| glob.matches(p))
if root.fs == fs_path.fs {
root.get_path_to(fs_path).is_some_and(|p| glob.matches(p))
} else {
glob.matches(&fs_path.path)
}
}
AfterResolvePluginCondition::Always => true,
AfterResolvePluginCondition::Never => false,
......
use anyhow::Result;
use next_taskless::{BUN_EXTERNALS, EDGE_NODE_EXTERNALS, NODE_EXTERNALS};
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{FileSystem, FileSystemPath};
use turbo_tasks::Vc;
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::resolve::{
AliasMap, AliasPattern, ExternalTraced, ExternalType, FindContextFileResult, find_context_file,
options::{
......@@ -18,12 +18,10 @@ use crate::{
#[turbo_tasks::function]
async fn base_resolve_options(
fs: ResolvedVc<Box<dyn FileSystem>>,
options_context: Vc<ResolveOptionsContext>,
) -> Result<Vc<ResolveOptions>> {
let opt = options_context.await?;
let emulating = opt.emulate_environment;
let root = fs.root().owned().await?;
let mut direct_mappings = AliasMap::new();
let node_externals = if let Some(environment) = emulating {
environment.node_externals().owned().await?
......@@ -154,20 +152,14 @@ async fn base_resolve_options(
extensions,
modules: if let Some(environment) = emulating {
if *environment.resolve_node_modules().await? {
vec![ResolveModules::Nested(
root.clone(),
vec![rcstr!("node_modules")],
)]
vec![ResolveModules::Nested(vec![rcstr!("node_modules")])]
} else {
Vec::new()
}
} else {
let mut mods = Vec::new();
if let Some(dir) = &opt.enable_node_modules {
mods.push(ResolveModules::Nested(
dir.clone(),
vec![rcstr!("node_modules")],
));
if opt.enable_node_modules.is_some() {
mods.push(ResolveModules::Nested(vec![rcstr!("node_modules")]));
}
mods
},
......@@ -228,7 +220,7 @@ pub async fn resolve_options(
}
}
let resolve_options = base_resolve_options(*resolve_path.fs, options_context);
let resolve_options = base_resolve_options(options_context);
let resolve_options = if options_context_value.enable_typescript {
let find_tsconfig = async || {
......
......@@ -246,7 +246,7 @@ pub async fn tsconfig_resolve_options(
let configs = read_tsconfigs(
tsconfig.read(),
ResolvedVc::upcast(FileSource::new(tsconfig.clone()).to_resolved().await?),
node_cjs_resolve_options(tsconfig.root().owned().await?),
node_cjs_resolve_options(),
)
.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