Unverified Commit 43d81b9d authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

feat(turbopack): resolve `/`-rooted imports from the project directory (#97799)

### What?

A request starting with `/` — `import '/content/where'`,
`require('/foo.js')` — now resolves from
the **project directory** (the one holding `next.config`), and cannot
reach outside it. Previously
it resolved from the root of the filesystem while reporting *"server
relative imports are not
implemented yet"*.

This is the base of a stack: the follow-up on top of it moves
`import.meta.glob`'s `/`-rooted
patterns onto the same root, so a pattern and a plain import agree on
what `/` means.

### Why?

The feature was half-present and mislabelled. The
`Request::ServerRelative` arm rewrote `/foo` to
`./foo` and resolved it against the filesystem root, then emitted a "not
implemented yet" issue
unless an import-map alias had already matched. Users got a diagnostic
telling them to give up on
something that in fact resolved.

Worse, resolving from the *filesystem* root means `/` escapes the
project. In a Turbopack execution
test — where the filesystem root is the repository root —
`require('/package.json')` resolved this
repository's own `package.json`. In a monorepo, where Turbopack's root
is the workspace root and the
app lives in `apps/web`, `/content/x.js` would reach a workspace-level
file rather than the app's.

The intended semantics are Vite's, and they were confirmed by
measurement rather than from memory.
In a workspace where `content/*.js` exists *both* at the workspace root
and under the Vite root, so
the two are distinguishable, Vite 5.4.21:

- resolves `/content/…` from the configured `root` — changing `root`
changes which file wins;
- fails outright for a file that exists only above `root`, rather than
walking up;
- behaves identically for a plain `import` and for `import.meta.glob`.

### How?

`ResolveOptions` gains `server_relative_root`, the directory a
`/`-rooted request resolves from, and
`ResolveOptionsContext` exposes it so embedders can set it. Next.js sets
it to the project directory
in the client, server and edge resolve contexts — all of which already
had it to hand, so nothing new
is threaded through.

Three deliberate choices:

- **The option is optional and defaults to the previous behaviour.**
`turbopack-core` is used well
beyond Next.js; an embedder that doesn't set it keeps resolving `/` from
the filesystem root. This
is also why the change is provably contained — the whole
`turbopack-tests` suite passes with no
  snapshot churn.
- **It is named and documented in filesystem terms**, tied to the
existing `Request::ServerRelative`
vocabulary, rather than introducing a "project root" concept into
`turbopack-core`, which must stay
  free of Next.js concepts.
- **There is no fallback.** Resolution happens in the configured root
and stops; a request that isn't
there is a normal module-not-found. A fallback to the filesystem root
would reintroduce exactly the
  escape this fixes.

The "not implemented yet" issue is removed. The equivalent issue for
Windows-style absolute requests
is untouched, as is the separate tsconfig `extends` handling, which
treats a rooted path as absolute
per TypeScript's own rule.

### Testing

The Turbopack execution harness already has two distinct roots — the
repository root as the
filesystem root, and each test's own directory — so pointing the new
option at the test directory
makes "project directory" and "filesystem root" genuinely different, and
the distinction testable
without a Next.js app. Two fixtures: one where a `/`-rooted import and
require resolve from the
project directory, and one asserting that `/package.json`, which exists
only at the filesystem root,
does *not* resolve. The former emits no issues at all, which is what
pins the removal of the
diagnostic.

The end-to-end case uses the existing monorepo fixture, where the
project directory really is not the
filesystem root. A file of the same name exists in both
`apps/web/content` and the workspace root, so
the rendered value alone identifies which root was used — a test that
merely asserted "it renders"
would have passed under the old behaviour too.

### Known gap

TypeScript resolves a leading `/` as an absolute path on disk, so a
`/`-rooted import in a `.ts` file
still fails type checking (`TS2307`) even though it bundles and runs.
The e2e page is therefore
JavaScript. A tsconfig `paths` mapping works around it for users, but it
also makes the request match
the import map instead, so the two resolvers overlap; that deserves its
own decision and is tracked
separately rather than papered over here.

<!-- NEXT_JS_LLM -->

<!-- fleet 3acc7e63-52a8-4472-89cd-b1bbb8ad59fa -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 7dcf6c0a
......@@ -190,6 +190,9 @@ pub async fn get_client_resolve_options_context(
resolved_map: Some(next_client_resolved_map),
browser: true,
module: true,
// A request starting with `/` is resolved from the project directory, which is not
// necessarily the root of the filesystem (e.g. in a monorepo).
server_relative_root: Some(project_path.clone()),
after_resolve_plugins: vec![ResolvedVc::upcast(
NextSharedRuntimeResolvePlugin::new(project_path.clone())
.to_resolved()
......
......@@ -139,6 +139,9 @@ pub async fn get_edge_resolve_options_context(
fallback_import_map: Some(next_edge_fallback_import_map),
module: true,
browser: true,
// A request starting with `/` is resolved from the project directory, which is not
// necessarily the root of the filesystem (e.g. in a monorepo).
server_relative_root: Some(project_path.clone()),
after_resolve_plugins,
..Default::default()
......
......@@ -261,6 +261,9 @@ pub async fn get_server_resolve_options_context(
custom_conditions,
import_map: Some(next_server_import_map),
fallback_import_map: Some(next_server_fallback_import_map),
// A request starting with `/` is resolved from the project directory, which is not
// necessarily the root of the filesystem (e.g. in a monorepo).
server_relative_root: Some(project_path.clone()),
after_resolve_plugins,
..Default::default()
};
......
// `/content/where` exists both under the project directory (apps/web) and at the
// workspace root, so which one is loaded says where `/` is rooted. It has to be
// the project directory.
//
// This page is JavaScript on purpose: TypeScript resolves a leading `/` as an
// absolute path on disk, so it can't type a `/`-rooted import (TS2307). Adding a
// tsconfig `paths` mapping for it would make the request match the import map
// instead, which wouldn't exercise the resolution under test.
import where from '/content/where'
export default function Page() {
return <p id="where">{where}</p>
}
// Same path relative to the *workspace* root as apps/web/content/where.ts is to
// the project directory. A `/`-rooted import must not pick this one up.
export default 'FROM-WORKSPACE-ROOT'
......@@ -12,6 +12,9 @@ describe('non-root-project-monorepo', () => {
files: {
apps: new FileRef(path.resolve(__dirname, 'apps')),
packages: new FileRef(path.resolve(__dirname, 'packages')),
// Deliberately shadows apps/web/content, to pin down which one a
// `/`-rooted import resolves from.
content: new FileRef(path.resolve(__dirname, 'content')),
'pnpm-workspace.yaml': `packages:
- 'apps/*'
- 'packages/*'
......@@ -28,6 +31,15 @@ describe('non-root-project-monorepo', () => {
return
}
describe('server relative import', () => {
it('should resolve a `/`-rooted import from the project directory, not the workspace root', async () => {
// `/content/where` exists both in apps/web (the project directory) and at
// the workspace root, so the value says which root was used.
const $ = await next.render$('/server-relative-import')
expect($('#where').text()).toBe('FROM-PROJECT-DIR')
})
})
describe('monorepo-package', () => {
it('should work during RSC', async () => {
const $ = await next.render$('/monorepo-package-rsc')
......
......@@ -2043,30 +2043,35 @@ async fn resolve_internal_inline(
new_pat.push_front(rcstr!(".").into());
let relative = Request::relative(new_pat, query.clone(), fragment.clone(), true);
if !has_alias {
ResolvingIssue {
severity: resolve_error_severity(options).await?,
request_type: "server relative import: not implemented yet".to_string(),
request: relative.to_resolved().await?,
file_path: lookup_path.clone(),
resolve_options: options.to_resolved().await?,
error_message: Some(
"server relative imports are not implemented yet. Please try an \
import relative to the file you are importing from."
.to_string(),
),
source: None,
// A `/`-rooted request is resolved from `server_relative_root`. It is not resolved
// relative to the importing file, and it does not fall back to a wider directory,
// so it can't reach outside of that root.
if let Some(root) = &options_value.server_relative_root {
Box::pin(resolve_internal_inline(root.clone(), relative, options)).await?
} else {
// Without a root configured there is nothing to resolve this from, so it isn't
// supported. Guessing at the root of the filesystem would silently resolve or
// silently fail depending on what happens to live there.
if !has_alias {
ResolvingIssue {
severity: resolve_error_severity(options).await?,
request_type: "server relative import: not implemented yet".to_string(),
request: relative.to_resolved().await?,
file_path: lookup_path.clone(),
resolve_options: options.to_resolved().await?,
error_message: Some(
"server relative imports are not implemented yet. Please try an \
import relative to the file you are importing from."
.to_string(),
),
source: None,
}
.resolved_cell()
.emit();
}
.resolved_cell()
.emit();
}
Box::pin(resolve_internal_inline(
lookup_path.root().owned().await?,
relative,
options,
))
.await?
ResolveResult::unresolvable().cell()
}
}
Request::Windows {
path: _,
......
......@@ -664,6 +664,15 @@ pub struct ResolveOptions {
pub collect_affecting_sources: bool,
/// Whether to parse data URIs into modules (as opposed to keeping them as externals)
pub parse_data_uris: bool,
/// The directory that a request starting with `/` (a [`Request::ServerRelative`]) resolves
/// from, e.g. `/dir/file.js`. A request that doesn't exist below this directory is not
/// resolved, so `/` can't reach outside of it.
///
/// When unset, there is nothing to resolve such a request from, so it isn't supported: it
/// reports an issue saying so and doesn't resolve.
///
/// [`Request::ServerRelative`]: crate::resolve::parse::Request::ServerRelative
pub server_relative_root: Option<FileSystemPath>,
pub placeholder_for_future_extensions: (),
}
......
......@@ -208,6 +208,7 @@ async fn base_resolve_options(
before_resolve_plugins: opt.before_resolve_plugins.clone(),
loose_errors: opt.loose_errors,
collect_affecting_sources: opt.collect_affecting_sources,
server_relative_root: opt.server_relative_root.clone(),
..Default::default()
}
.cell())
......
......@@ -81,6 +81,14 @@ pub struct ResolveOptionsContext {
pub loose_errors: bool,
/// Collect affecting sources for each resolve result. Useful for tracing.
pub collect_affecting_sources: bool,
/// The directory that a request starting with `/` resolves from, e.g. `/dir/file.js`. When
/// unset, such a request isn't supported and reports an issue saying so.
///
/// Sets [`ResolveOptions::server_relative_root`].
///
/// [`ResolveOptions::server_relative_root`]:
/// turbopack_core::resolve::options::ResolveOptions::server_relative_root
pub server_relative_root: Option<FileSystemPath>,
pub placeholder_for_future_extensions: (),
}
......
......@@ -292,6 +292,11 @@ struct TestOptions {
/// package.json.
#[serde(default)]
side_effect_free_packages: Vec<RcStr>,
/// Whether a request starting with `/` resolves from the test's directory. Set this to `false`
/// to leave `ResolveOptions::server_relative_root` unset, as an embedder that doesn't support
/// such requests would, which makes them unresolvable.
#[serde(default = "default_true")]
server_relative_root: bool,
}
fn default_true() -> bool {
......@@ -313,6 +318,7 @@ impl Default for TestOptions {
minify: false,
production_chunking: false,
side_effect_free_packages: Vec::new(),
server_relative_root: default_true(),
}
}
}
......@@ -501,6 +507,9 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
enable_node_native_modules: true,
enable_node_externals: true,
custom_conditions: vec![rcstr!("development")],
// A `/`-rooted request resolves from the test's own directory, which is not the root
// of the filesystem (that is the repository root), so the two are distinguishable.
server_relative_root: options.server_relative_root.then(|| project_path.clone()),
rules: vec![(
ContextCondition::InNodeModules,
ResolveOptionsContext {
......
// `/package.json` exists at the root of the filesystem (the repository root),
// but not inside the project directory (this test's own directory). A `/`-rooted
// request must not escape the project, so this must fail to resolve rather than
// silently pick up the file outside of it. The value of this test is the
// `issues/` snapshot.
it('should not resolve a `/`-rooted import from outside the project directory', () => {
let resolved = true
try {
require('/package.json')
} catch {
resolved = false
}
expect(resolved).toBe(false)
})
warning - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/server-relative-import-outside/input/index.js:10:4 Module not found: Can't resolve '/package.json'
6 |
7 | it('should not resolve a `/`-rooted import from outside the project directory', () => {
8 | let resolved = true
9 | try {
+ v----------------------v
10 + require('/package.json')
+ ^----------------------^
11 | } catch {
12 | resolved = false
13 | }
14 | expect(resolved).toBe(false)
| It was not possible to find the requested file.
| Parsed request as written in source code: server relative '/package.json'
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/server-relative-import-outside/input/index.js
| Type of request: commonjs request
|
\ No newline at end of file
// Without a `server_relative_root` there is nothing to resolve a `/`-rooted
// request from, so it isn't supported: it reports an issue and doesn't resolve.
//
// `/package.json` exists at the root of the filesystem (the repository root), so
// guessing at that root would resolve it. It must not: reporting the request as
// unsupported and then resolving it anyway would contradict itself.
it('should not resolve a `/`-rooted request', () => {
expect(() => require('/package.json')).toThrow()
})
it('should not resolve one below the importing directory either', () => {
expect(() => require('/input/dir/foo.js')).toThrow()
})
error - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/server-relative-import-unsupported/input Module not found: Can't resolve './package.json'
server relative imports are not implemented yet. Please try an import relative to the file you are importing from.
| An error happened during resolving.
| Parsed request as written in source code: relative-in-lookup-dir './package.json'
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/server-relative-import-unsupported/input
| Type of request: server relative import: not implemented yet
|
\ No newline at end of file
error - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/server-relative-import-unsupported/input Module not found: Can't resolve './input/dir/foo.js'
server relative imports are not implemented yet. Please try an import relative to the file you are importing from.
| An error happened during resolving.
| Parsed request as written in source code: relative-in-lookup-dir './input/dir/foo.js'
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/server-relative-import-unsupported/input
| Type of request: server relative import: not implemented yet
|
\ No newline at end of file
error - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/server-relative-import-unsupported/input/index.js:13:15 Module not found: Can't resolve '/input/dir/foo.js'
9 | expect(() => require('/package.json')).toThrow()
10 | })
11 |
12 | it('should not resolve one below the importing directory either', () => {
+ v--------------------------v
13 + expect(() => require('/input/dir/foo.js')).toThrow()
+ ^--------------------------^
14 | })
15 |
| It was not possible to find the requested file.
| Parsed request as written in source code: server relative '/input/dir/foo.js'
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/server-relative-import-unsupported/input/index.js
| Type of request: commonjs request
|
\ No newline at end of file
error - [resolve] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/server-relative-import-unsupported/input/index.js:9:15 Module not found: Can't resolve '/package.json'
5 | // guessing at that root would resolve it. It must not: reporting the request as
6 | // unsupported and then resolving it anyway would contradict itself.
7 |
8 | it('should not resolve a `/`-rooted request', () => {
+ v----------------------v
9 + expect(() => require('/package.json')).toThrow()
+ ^----------------------^
10 | })
11 |
12 | it('should not resolve one below the importing directory either', () => {
13 | expect(() => require('/input/dir/foo.js')).toThrow()
| It was not possible to find the requested file.
| Parsed request as written in source code: server relative '/package.json'
| Path where resolving has started: [project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/server-relative-import-unsupported/input/index.js
| Type of request: commonjs request
|
\ No newline at end of file
// A request starting with `/` is resolved from the project directory, not from
// the root of the filesystem. Here the project directory is this test's own
// directory, so `/input/dir/foo.js` is the file next to this one.
//
// Vite's rule: a request is either relative to the importing file or absolute
// from the project root.
// https://vite.dev/guide/features.html#glob-import-caveats
import foo from '/input/dir/foo.js'
it('should resolve a `/`-rooted import from the project directory', () => {
expect(foo).toBe('foo')
})
it('should resolve a `/`-rooted require from the project directory', () => {
expect(require('/input/dir/bar.js')).toBe('bar')
})
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