Unverified Commit ed1aab5d authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

fix(turbopack): resolve `../` and `/`-rooted `import.meta.glob` patterns (#96557)

### What?

`import.meta.glob()` now resolves `../`-relative and
`/`-project-root-absolute
patterns (and `base`), validates every pattern (positive and negative)
for
whether it escapes the filesystem root, and shares the underlying
"resolve leading `./`/`../` against a directory" primitive with
`next-core::relativize_glob` (used by `outputFileTracingIncludes`)
instead of
duplicating it.

### Why?

`import.meta.glob()` handed its patterns straight to Turbopack's `Glob`,
which
matches relative to the scanned directory and understands neither a
leading
`/` nor `..` segments. `import.meta.glob('../../content/*.js')` and
`import.meta.glob('/content/*.js')` therefore silently returned `{}`,
and a
`base` that walked above the filesystem root failed with an internal
error
and a panic report instead of a normal diagnostic. A negative
(exclusion)
pattern that escaped the root was silently dropped, which is the worst
outcome for an exclusion — it would silently include files the user
asked to
exclude.

### How?

- Patterns are split into the directory they're rooted in and the
remaining
glob, matched relative to a single common scan directory covering every
  positive and negative pattern. `/` is resolved from the project root,
matching Vite's rule that patterns are relative to the importing file or
  absolute from the project root.
- Map keys follow the pattern too: `base` now produces base-relative
keys
  (`'./zeta.js'` instead of `'../../content/zeta.js'`, matching Vite), a
  project-root-absolute pattern produces project-root-absolute keys, and
  origin-relative keys are unchanged otherwise.
- Every pattern is validated up front; one that leaves the project (a
`base`,
a positive pattern, or a negative one) reports an error issue at the
call
  site and yields an empty object, instead of crashing or being silently
  dropped.
- The `./`/`../`-resolution loop is extracted into
  `turbo_tasks_fs::glob::relativize_glob`, a crate both `next-core` and
`turbopack-ecmascript` already depend on. `next-core::relativize_glob`
is
now a thin wrapper over it (same name, signature and error message); its
5
unit tests are removed since the shared primitive's own tests cover the
  same cases.

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 334052ff
use std::{borrow::Cow, fmt::Display, str::FromStr}; use std::{fmt::Display, str::FromStr};
use anyhow::{Result, bail}; use anyhow::{Context, Result, bail};
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use next_taskless::{expand_next_js_template, expand_next_js_template_no_imports}; use next_taskless::{expand_next_js_template, expand_next_js_template_no_imports};
use serde::{Deserialize, de::DeserializeOwned}; use serde::{Deserialize, de::DeserializeOwned};
...@@ -572,198 +572,7 @@ pub fn relativize_glob<'a>( ...@@ -572,198 +572,7 @@ pub fn relativize_glob<'a>(
glob: &'a str, glob: &'a str,
relative_to: &FileSystemPath, relative_to: &FileSystemPath,
) -> Result<(&'a str, FileSystemPath)> { ) -> Result<(&'a str, FileSystemPath)> {
let mut relative_to = Cow::Borrowed(relative_to); turbo_tasks_fs::glob::relativize_glob(glob, relative_to).with_context(|| {
let mut processed_glob = glob; format!("glob '{glob}' is invalid, it has a prefix that navigates out of the project root")
loop { })
if let Some(stripped) = processed_glob.strip_prefix("../") {
if relative_to.path.is_empty() {
bail!(
"glob '{glob}' is invalid, it has a prefix that navigates out of the project \
root"
);
}
relative_to = Cow::Owned(relative_to.parent());
processed_glob = stripped;
} else if let Some(stripped) = processed_glob.strip_prefix("./") {
processed_glob = stripped;
} else {
break;
}
}
Ok((processed_glob, relative_to.into_owned()))
}
#[cfg(test)]
mod tests {
use turbo_tasks::ResolvedVc;
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{FileSystemPath, NullFileSystem};
use super::*;
fn create_test_fs_path(path: &str) -> FileSystemPath {
FileSystemPath {
fs: ResolvedVc::upcast(NullFileSystem {}.resolved_cell()),
path: path.into(),
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_relativize_glob_normal_patterns() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async {
// Test normal glob patterns without relative prefixes
let base_path = create_test_fs_path("project/src");
let (glob, path) = relativize_glob("*.js", &base_path).unwrap();
assert_eq!(glob, "*.js");
assert_eq!(path.path.as_str(), "project/src");
let (glob, path) = relativize_glob("components/**/*.tsx", &base_path).unwrap();
assert_eq!(glob, "components/**/*.tsx");
assert_eq!(path.path.as_str(), "project/src");
let (glob, path) = relativize_glob("lib/utils.ts", &base_path).unwrap();
assert_eq!(glob, "lib/utils.ts");
assert_eq!(path.path.as_str(), "project/src");
Ok(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_relativize_glob_current_directory_prefix() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async {
let base_path = create_test_fs_path("project/src");
// Single ./ prefix
let (glob, path) = relativize_glob("./components/*.tsx", &base_path).unwrap();
assert_eq!(glob, "components/*.tsx");
assert_eq!(path.path.as_str(), "project/src");
// Multiple ./ prefixes
let (glob, path) = relativize_glob("././utils.js", &base_path).unwrap();
assert_eq!(glob, "utils.js");
assert_eq!(path.path.as_str(), "project/src");
// ./ with complex glob
let (glob, path) = relativize_glob("./lib/**/*.{js,ts}", &base_path).unwrap();
assert_eq!(glob, "lib/**/*.{js,ts}");
assert_eq!(path.path.as_str(), "project/src");
Ok(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_relativize_glob_parent_directory_navigation() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async {
let base_path = create_test_fs_path("project/src/components");
// Single ../ prefix
let (glob, path) = relativize_glob("../utils/*.js", &base_path).unwrap();
assert_eq!(glob, "utils/*.js");
assert_eq!(path.path.as_str(), "project/src");
// Multiple ../ prefixes
let (glob, path) = relativize_glob("../../lib/*.ts", &base_path).unwrap();
assert_eq!(glob, "lib/*.ts");
assert_eq!(path.path.as_str(), "project");
// Complex navigation with glob
let (glob, path) = relativize_glob("../../../external/**/*.json", &base_path).unwrap();
assert_eq!(glob, "external/**/*.json");
assert_eq!(path.path.as_str(), "");
Ok(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_relativize_glob_mixed_prefixes() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async {
let base_path = create_test_fs_path("project/src/components");
// ../ followed by ./
let (glob, path) = relativize_glob(".././utils/*.js", &base_path).unwrap();
assert_eq!(glob, "utils/*.js");
assert_eq!(path.path.as_str(), "project/src");
// ./ followed by ../
let (glob, path) = relativize_glob("./../lib/*.ts", &base_path).unwrap();
assert_eq!(glob, "lib/*.ts");
assert_eq!(path.path.as_str(), "project/src");
// Multiple mixed prefixes
let (glob, path) = relativize_glob("././../.././external/*.json", &base_path).unwrap();
assert_eq!(glob, "external/*.json");
assert_eq!(path.path.as_str(), "project");
Ok(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_relativize_glob_error_navigation_out_of_root() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async {
// Test navigating out of project root with empty path
let empty_path = create_test_fs_path("");
let result = relativize_glob("../outside.js", &empty_path);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("navigates out of the project root")
);
// Test navigating too far up from a shallow path
let shallow_path = create_test_fs_path("project");
let result = relativize_glob("../../outside.js", &shallow_path);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("navigates out of the project root")
);
// Test multiple ../ that would go out of root
let base_path = create_test_fs_path("a/b");
let result = relativize_glob("../../../outside.js", &base_path);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("navigates out of the project root")
);
Ok(())
})
.await
.unwrap();
}
} }
...@@ -181,6 +181,25 @@ const modules = import.meta.glob('./dir/*.js') ...@@ -181,6 +181,25 @@ const modules = import.meta.glob('./dir/*.js')
> **Good to know:** `import.meta.glob` requires Turbopack. It is not available when using webpack. > **Good to know:** `import.meta.glob` requires Turbopack. It is not available when using webpack.
### Patterns
A pattern is either relative to the importing file (`./`, `../`) or absolute from the project root (`/`):
```js
// Relative to the importing file
const siblings = import.meta.glob('./dir/*.js')
const parent = import.meta.glob('../docs/*.js')
// Absolute from the project root
const content = import.meta.glob('/content/*.md')
```
The keys of the result follow the pattern: relative patterns produce relative keys (`'./dir/foo.js'`, `'../docs/intro.js'`), project-root-absolute patterns produce project-root-absolute keys (`'/content/alpha.md'`).
`node_modules` is matched like any other directory, so a broad pattern such as `import.meta.glob('/**/*.js')` walks your dependencies as well and can take seconds. Narrow the pattern, or exclude what you don't need with a negative pattern. The build output directory (`.next`) is never traversed.
The keys are always sorted, deterministically and identically in development and production. The sort is a bytewise comparison of the key, so it is not a natural or display order — `'10-ten.js'` sorts before `'2-two.js'`, uppercase before `_` before lowercase, and files in subdirectories are interleaved with their siblings rather than grouped. Multiple patterns are merged into a single sorted object, not concatenated in pattern order.
### Lazy loading (default) ### Lazy loading (default)
By default, each value in the result object is a thunk — a function that returns a `Promise` for the module. This enables lazy loading: By default, each value in the result object is a thunk — a function that returns a `Promise` for the module. This enables lazy loading:
...@@ -264,6 +283,18 @@ const modules = import.meta.glob(['./dir/*.js', './other/*.js']) ...@@ -264,6 +283,18 @@ const modules = import.meta.glob(['./dir/*.js', './other/*.js'])
const withoutTests = import.meta.glob(['./src/**/*.js', '!**/*.test.js']) const withoutTests = import.meta.glob(['./src/**/*.js', '!**/*.test.js'])
``` ```
### Base path
Use the `base` option to resolve the patterns against a different directory. The keys of the result are then relative to `base` rather than to the importing file:
```js
const modules = import.meta.glob('*.md', { base: '../../content' })
// {
// './alpha.md': () => import('../../content/alpha.md'),
// './nested/deep.md': () => import('../../content/nested/deep.md'),
// }
```
### TypeScript ### TypeScript
TypeScript types for `import.meta.glob` are included in Next.js. They are available automatically when `"moduleResolution": "bundler"` (or `"node16"` / `"nodenext"`) is set in your `tsconfig.json`, which is the default for new Next.js projects. TypeScript types for `import.meta.glob` are included in Next.js. They are available automatically when `"moduleResolution": "bundler"` (or `"node16"` / `"nodenext"`) is set in your `tsconfig.json`, which is the default for new Next.js projects.
...@@ -295,13 +326,13 @@ const eager = import.meta.glob<Mod>('./dir/*.ts', { eager: true }) ...@@ -295,13 +326,13 @@ const eager = import.meta.glob<Mod>('./dir/*.ts', { eager: true })
### Options reference ### Options reference
| Option | Type | Default | Description | | Option | Type | Default | Description |
| --------------- | --------------------------------------------- | ----------- | -------------------------------------------------------------------------- | | --------------- | --------------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------- |
| `eager` | `boolean` | `false` | Import modules synchronously instead of returning thunks. | | `eager` | `boolean` | `false` | Import modules synchronously instead of returning thunks. |
| `import` | `string` | `undefined` | Named export to select from each matched module (e.g. `'default'`). | | `import` | `string` | `undefined` | Named export to select from each matched module (e.g. `'default'`). |
| `query` | `string \| Record<string, string \| boolean>` | `undefined` | Query string (or object) to append to each import. | | `query` | `string \| Record<string, string \| boolean>` | `undefined` | Query string (or object) to append to each import. |
| `base` | `string` | `undefined` | Override the base path used for resolving patterns and keying results. | | `base` | `string` | `undefined` | Directory the patterns are resolved against, relative to the importing file. Result keys become relative to it. |
| `caseSensitive` | `boolean` | `true` | Match glob patterns case-sensitively. Set to `false` to ignore ASCII case. | | `caseSensitive` | `boolean` | `true` | Match glob patterns case-sensitively. Set to `false` to ignore ASCII case. |
> **Note:** The `as` option (deprecated in Vite 5) is not supported. Use `query` together with a matching rule instead, as shown in [Query strings](#query-strings). The legacy `import.meta.globEager()` API is also not supported — use `import.meta.glob('...', { eager: true })` instead. > **Note:** The `as` option (deprecated in Vite 5) is not supported. Use `query` together with a matching rule instead, as shown in [Query strings](#query-strings). The legacy `import.meta.globEager()` API is also not supported — use `import.meta.glob('...', { eager: true })` instead.
......
// `/content/where` exists both in apps/web (the Next.js project directory) and at
// the workspace root, with different contents, so the value that comes back says
// which root was used. It has to be the project directory, for both a plain
// import and a `/`-rooted `import.meta.glob` pattern — the two can't disagree
// about what `/` means.
//
// JavaScript, not TypeScript: TypeScript resolves a leading `/` as an absolute
// path on disk, so it can't type a `/`-rooted import.
import where from '/content/where'
const globbed = import.meta.glob('/content/*', { eager: true })
export default function Page() {
return (
<>
<p id="import">{where}</p>
<p id="glob-keys">{JSON.stringify(Object.keys(globbed))}</p>
<p id="glob-value">{globbed['/content/where.ts'].default}</p>
</>
)
}
export default function Root({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
// Inside the Next.js project directory (apps/web), which is where a `/`-rooted
// pattern resolves from.
export default 'FROM-PROJECT-DIR'
/**
* @type {import('next').NextConfig}
*/
module.exports = {}
{
"name": "import-meta-glob-web",
"version": "0.0.0",
"scripts": {
"dev": "next dev",
"start": "next start",
"build": "next build"
}
}
// At the workspace root, which is Turbopack's root but *not* the Next.js project
// directory. A `/`-rooted pattern must not reach this one.
export default 'FROM-WORKSPACE-ROOT'
import { nextTestSetup, FileRef } from 'e2e-utils'
import * as path from 'path'
// `import.meta.glob` is a Turbopack-only feature, and webpack compiles
// `import.meta` to `{}`, so the page would throw while collecting page data.
// This suite lives in its own monorepo rather than in
// `test/e2e/app-dir/non-root-project-monorepo`, so that skipping it here doesn't
// take that suite's webpack coverage with it.
const testFn =
process.env.IS_WEBPACK_TEST || process.env.NEXT_RSPACK
? describe.skip
: describe
testFn('import-meta-glob-monorepo', () => {
const { next, skipped } = nextTestSetup({
files: {
apps: new FileRef(path.resolve(__dirname, 'apps')),
// Deliberately shadows apps/web/content, to pin down which one a
// `/`-rooted pattern resolves from.
content: new FileRef(path.resolve(__dirname, 'content')),
'pnpm-workspace.yaml': `packages:
- 'apps/*'
`,
},
packageJson: require('./package.json'),
buildCommand: 'pnpm build',
startCommand: (global as any).isNextDev ? 'pnpm dev' : 'pnpm start',
installCommand: 'pnpm i',
skipDeployment: true,
})
if (skipped) {
return
}
it('should resolve a `/`-rooted pattern from the project directory, like a plain import', async () => {
const $ = await next.render$('/glob')
// The point of the test: a glob and a plain import agree about what `/` means.
expect($('#glob-value').text()).toBe($('#import').text())
expect($('#glob-value').text()).toBe('FROM-PROJECT-DIR')
// The key stays absolute from the project directory, as in Vite.
expect(JSON.parse($('#glob-keys').text())).toEqual(['/content/where.ts'])
})
})
{
"name": "import-meta-glob-monorepo-root",
"version": "0.0.0",
"private": true,
"scripts": {
"build": "pnpm i && pnpm run --dir apps/web build",
"start": "pnpm run --dir apps/web start",
"dev": "pnpm i && pnpm run --dir apps/web dev"
}
}
use std::fmt::Display; use std::{borrow::Cow, fmt::Display};
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use bincode::{ use bincode::{
...@@ -12,7 +12,7 @@ use regex::bytes::{Regex, RegexBuilder}; ...@@ -12,7 +12,7 @@ use regex::bytes::{Regex, RegexBuilder};
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{Vc, trace::TraceRawVcs}; use turbo_tasks::{Vc, trace::TraceRawVcs};
use crate::globset::parse; use crate::{FileSystemPath, globset::parse};
// Examples: // Examples:
// - file.js = File(file.js) // - file.js = File(file.js)
...@@ -161,6 +161,47 @@ impl Glob { ...@@ -161,6 +161,47 @@ impl Glob {
} }
} }
/// Resolve the leading `./` and `../` segments of a glob pattern into a
/// directory, so that what remains only ever traverses *down* the tree.
///
/// [`Glob`] matches paths relative to the directory that is scanned and has no
/// notion of `.` or `..`, and the directory walker only descends. A pattern like
/// `../dir/*.js` therefore has to be turned into the pattern `dir/*.js` matched
/// against the parent of `relative_to`, which is what this does.
///
/// Returns the remaining pattern together with the directory it is relative to,
/// or [`None`] if the pattern walks above the root of the filesystem. Callers
/// decide how to report that: it is a hard error for some and a diagnostic for
/// others.
///
/// ```ignore
/// // with `relative_to` = `src/app`
/// relativize_glob("*.js") // => ("*.js", "src/app")
/// relativize_glob("./dir/*.js") // => ("dir/*.js", "src/app")
/// relativize_glob("../dir/*.js") // => ("dir/*.js", "src")
/// relativize_glob("././../x/*.js") // => ("x/*.js", "src")
/// ```
pub fn relativize_glob<'a>(
glob: &'a str,
relative_to: &FileSystemPath,
) -> Option<(&'a str, FileSystemPath)> {
let mut relative_to = Cow::Borrowed(relative_to);
let mut remaining = glob;
loop {
if let Some(stripped) = remaining.strip_prefix("../") {
if relative_to.is_root() {
return None;
}
relative_to = Cow::Owned(relative_to.parent());
remaining = stripped;
} else if let Some(stripped) = remaining.strip_prefix("./") {
remaining = stripped;
} else {
return Some((remaining, relative_to.into_owned()));
}
}
}
fn new_regex(pattern: &str, opts: GlobOptions) -> Regex { fn new_regex(pattern: &str, opts: GlobOptions) -> Regex {
RegexBuilder::new(pattern) RegexBuilder::new(pattern)
// Because we aren't setting the `unicode` flag, this is only ASCII case-insensitive. // Because we aren't setting the `unicode` flag, this is only ASCII case-insensitive.
...@@ -170,6 +211,97 @@ fn new_regex(pattern: &str, opts: GlobOptions) -> Regex { ...@@ -170,6 +211,97 @@ fn new_regex(pattern: &str, opts: GlobOptions) -> Regex {
.expect("A successfully parsed glob should produce a valid regex") .expect("A successfully parsed glob should produce a valid regex")
} }
#[cfg(test)]
mod relativize_glob_tests {
use turbo_tasks::ResolvedVc;
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use super::*;
use crate::NullFileSystem;
fn path(path: &str) -> FileSystemPath {
FileSystemPath {
fs: ResolvedVc::upcast(NullFileSystem {}.resolved_cell()),
path: path.into(),
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn relativizes_leading_segments() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async {
let dir = path("project/src/components");
// No leading relative segments: returned as-is.
let (glob, root) = relativize_glob("*.js", &dir).unwrap();
assert_eq!(
(glob, root.path.as_str()),
("*.js", "project/src/components")
);
let (glob, root) = relativize_glob("nested/**/*.js", &dir).unwrap();
assert_eq!(
(glob, root.path.as_str()),
("nested/**/*.js", "project/src/components")
);
// `./` doesn't move the directory, repeated or not.
let (glob, root) = relativize_glob("./*.js", &dir).unwrap();
assert_eq!(
(glob, root.path.as_str()),
("*.js", "project/src/components")
);
let (glob, root) = relativize_glob("././*.js", &dir).unwrap();
assert_eq!(
(glob, root.path.as_str()),
("*.js", "project/src/components")
);
// Each `../` walks one directory up.
let (glob, root) = relativize_glob("../*.js", &dir).unwrap();
assert_eq!((glob, root.path.as_str()), ("*.js", "project/src"));
let (glob, root) = relativize_glob("../../lib/*.js", &dir).unwrap();
assert_eq!((glob, root.path.as_str()), ("lib/*.js", "project"));
// `./` and `../` may be mixed, in either order, and are all consumed.
let (glob, root) = relativize_glob(".././utils/*.js", &dir).unwrap();
assert_eq!((glob, root.path.as_str()), ("utils/*.js", "project/src"));
let (glob, root) = relativize_glob("./../lib/*.js", &dir).unwrap();
assert_eq!((glob, root.path.as_str()), ("lib/*.js", "project/src"));
let (glob, root) = relativize_glob("././../.././x/*.js", &dir).unwrap();
assert_eq!((glob, root.path.as_str()), ("x/*.js", "project"));
// Walking exactly to the filesystem root is fine.
let (glob, root) = relativize_glob("../../../*.js", &dir).unwrap();
assert_eq!((glob, root.path.as_str()), ("*.js", ""));
Ok(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn reports_walking_above_the_root() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async {
// One `../` too many, from a nested directory and from the root itself.
assert!(relativize_glob("../../../../*.js", &path("project/src/components")).is_none());
assert!(relativize_glob("../*.js", &path("")).is_none());
// The `../` doesn't have to be the first segment to be detected.
assert!(relativize_glob("./../../*.js", &path("project")).is_none());
Ok(())
})
.await
.unwrap();
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use rstest::*; use rstest::*;
......
// `base` and patterns that walk above the filesystem root must produce a
// normal, actionable error issue and an empty result — not an internal
// Turbopack error with a panic report.
const escapingBase = import.meta.glob('*.js', {
base: '../../../../../../../../../../../..',
})
it('should return an empty object for a base above the project root', () => {
expect(escapingBase).toEqual({})
})
const escapingPattern = import.meta.glob(
'../../../../../../../../../../../../*.js'
)
it('should return an empty object for a pattern above the project root', () => {
expect(escapingPattern).toEqual({})
})
// A positive pattern that escapes is reported and then skipped, so the patterns
// around it still resolve: fewer matches is easier to work with while editing
// than nothing at all.
const escapingAmongValid = import.meta.glob(
['./dir/*.js', '../../../../../../../../../../../../*.js'],
{ eager: true }
)
it('should still match the other patterns when one of them escapes', () => {
expect(Object.keys(escapingAmongValid)).toEqual(['./dir/one.js'])
expect(escapingAmongValid['./dir/one.js'].default).toBe('one')
})
// A negative pattern that escapes can't exclude anything, and skipping it would
// include files the user asked to exclude, so nothing is matched at all.
const escapingNegativePattern = import.meta.glob([
'./*.js',
'!../../../../../../../../../../../../*.js',
])
it('should return an empty object for a negative pattern above the project root', () => {
expect(escapingNegativePattern).toEqual({})
})
error - [code gen] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-escape-root/input/index.js:36:32 import.meta.glob() cannot look outside of the project root
32 | })
33 |
34 | // A negative pattern that escapes can't exclude anything, and skipping it would
35 | // include files the user asked to exclude, so nothing is matched at all.
| v-----------------
36 + const escapingNegativePattern = import.meta.glob([
37 + './*.js',
38 + '!../../../../../../../../../../../../*.js',
39 + ])
+--^
40 |
41 | it('should return an empty object for a negative pattern above the project root', () => {
42 | expect(escapingNegativePattern).toEqual({})
43 | })
the pattern "!../../../../../../../../../../../../*.js" of import.meta.glob("./*.js", "!../../../../../../../../../../../../*.js") resolves to a directory above the project root, relative to turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-escape-root/input. Patterns are relative to the importing file, or absolute from the project root when they start with `/`.
\ No newline at end of file
error - [code gen] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-escape-root/input/index.js:24:27 import.meta.glob() cannot look outside of the project root
20 |
21 | // A positive pattern that escapes is reported and then skipped, so the patterns
22 | // around it still resolve: fewer matches is easier to work with while editing
23 | // than nothing at all.
| v----------------
24 + const escapingAmongValid = import.meta.glob(
25 + ['./dir/*.js', '../../../../../../../../../../../../*.js'],
26 + { eager: true }
27 + )
+-^
28 |
29 | it('should still match the other patterns when one of them escapes', () => {
30 | expect(Object.keys(escapingAmongValid)).toEqual(['./dir/one.js'])
31 | expect(escapingAmongValid['./dir/one.js'].default).toBe('one')
the pattern "../../../../../../../../../../../../*.js" of import.meta.glob("./dir/*.js", "../../../../../../../../../../../../*.js") resolves to a directory above the project root, relative to turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-escape-root/input. Patterns are relative to the importing file, or absolute from the project root when they start with `/`.
\ No newline at end of file
error - [code gen] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-escape-root/input/index.js:5:21 import.meta.glob() cannot look outside of the project root
1 | // `base` and patterns that walk above the filesystem root must produce a
2 | // normal, actionable error issue and an empty result — not an internal
3 | // Turbopack error with a panic report.
4 |
| v-------------------------
5 + const escapingBase = import.meta.glob('*.js', {
6 + base: '../../../../../../../../../../../..',
7 + })
+--^
8 |
9 | it('should return an empty object for a base above the project root', () => {
10 | expect(escapingBase).toEqual({})
11 | })
the 'base' option "../../../../../../../../../../../.." of import.meta.glob("*.js") resolves to a directory above the project root, relative to turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-escape-root/input. Patterns are relative to the importing file, or absolute from the project root when they start with `/`.
\ No newline at end of file
error - [code gen] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-escape-root/input/index.js:13:24 import.meta.glob() cannot look outside of the project root
9 | it('should return an empty object for a base above the project root', () => {
10 | expect(escapingBase).toEqual({})
11 | })
12 |
| v----------------
13 + const escapingPattern = import.meta.glob(
14 + '../../../../../../../../../../../../*.js'
15 + )
+-^
16 |
17 | it('should return an empty object for a pattern above the project root', () => {
18 | expect(escapingPattern).toEqual({})
19 | })
the pattern "../../../../../../../../../../../../*.js" of import.meta.glob("../../../../../../../../../../../../*.js") resolves to a directory above the project root, relative to turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-escape-root/input. Patterns are relative to the importing file, or absolute from the project root when they start with `/`.
\ No newline at end of file
// Without a directory to resolve a `/`-rooted request from, a `/`-rooted pattern
// isn't supported either: it reports that and matches nothing, rather than
// falling back to the root of the filesystem.
//
// The pattern below is deliberately spelled from the root of the filesystem, so
// it *would* match `dir/foo.js` if that root were used. It must not.
const absolute = import.meta.glob(
'/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-no-root/input/dir/*.js',
{ eager: true }
)
it('should not match a `/`-rooted pattern', () => {
expect(absolute).toEqual({})
})
// A relative pattern is unaffected.
const relative = import.meta.glob('./dir/*.js', { eager: true })
it('should still match a relative pattern', () => {
expect(Object.keys(relative)).toEqual(['./dir/foo.js'])
})
error - [code gen] /turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-no-root/input/index.js:8:17 import.meta.glob() does not support patterns absolute from the root of the project here
4 | //
5 | // The pattern below is deliberately spelled from the root of the filesystem, so
6 | // it *would* match `dir/foo.js` if that root were used. It must not.
7 |
| v----------------
8 + const absolute = import.meta.glob(
9 + '/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-no-root/input/dir/*.js',
10 + { eager: true }
11 + )
+-^
12 |
13 | it('should not match a `/`-rooted pattern', () => {
14 | expect(absolute).toEqual({})
15 | })
the pattern "/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-no-root/input/dir/*.js" of import.meta.glob("/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/import-meta-glob-no-root/input/dir/*.js") starts with `/`, but there is no directory to resolve it from. Use a pattern relative to the importing file instead.
\ No newline at end of file
// The fixture keeps `one.js`, `two.js` and `nested/three.js` in a sibling
// directory of `input/`, so patterns have to walk out of the importer's
// directory to find them.
//
// Vite's rule: a pattern is either relative (`./`, `../`) to the importing file
// or absolute from the project root (`/`).
// https://vite.dev/guide/features.html#glob-import-caveats
const parentEager = import.meta.glob('../outside/*.js', { eager: true })
it('should match a pattern that walks up out of the importer directory', () => {
expect(Object.keys(parentEager)).toEqual([
'../outside/one.js',
'../outside/two.js',
])
expect(parentEager['../outside/one.js'].default).toBe('one')
expect(parentEager['../outside/two.js'].default).toBe('two')
})
const parentRecursive = import.meta.glob('../outside/**/*.js', { eager: true })
it('should match recursively below a parent directory', () => {
expect(Object.keys(parentRecursive)).toEqual([
'../outside/nested/three.js',
'../outside/one.js',
'../outside/two.js',
])
expect(parentRecursive['../outside/nested/three.js'].default).toBe('three')
})
const parentNegative = import.meta.glob(
['../outside/*.js', '!../outside/two.js'],
{ eager: true }
)
it('should apply negative patterns that walk up out of the importer directory', () => {
expect(Object.keys(parentNegative)).toEqual(['../outside/one.js'])
})
// Absolute from the directory a `/`-rooted request resolves from, which in this
// test suite is the test's own directory rather than the root of the filesystem.
const absolute = import.meta.glob('/outside/*.js', { eager: true })
it('should match a pattern that is absolute from the root of the project', () => {
expect(Object.keys(absolute)).toEqual(['/outside/one.js', '/outside/two.js'])
expect(absolute['/outside/one.js'].default).toBe('one')
})
const mixedRoots = import.meta.glob(['./local/*.js', '../outside/one.js'], {
eager: true,
})
// A negative pattern may be rooted above the positive patterns.
const mixedRootsNegative = import.meta.glob(
['../outside/*.js', '!/outside/two.js'],
{ eager: true }
)
it('should merge patterns rooted in different directories', () => {
expect(Object.keys(mixedRoots).sort()).toEqual([
'../outside/one.js',
'./local/local.js',
])
expect(mixedRoots['./local/local.js'].default).toBe('local')
expect(mixedRoots['../outside/one.js'].default).toBe('one')
})
it('should apply a negative pattern rooted above the positive patterns', () => {
expect(Object.keys(mixedRootsNegative)).toEqual(['../outside/one.js'])
})
// `base` moves the directory the pattern is resolved against *and* the keys are
// relative to it. https://vite.dev/guide/features.html#base-path
const withBase = import.meta.glob('*.js', {
base: '../outside',
eager: true,
})
it('should key results relative to base', () => {
expect(Object.keys(withBase)).toEqual(['./one.js', './two.js'])
expect(withBase['./one.js'].default).toBe('one')
expect(withBase['./two.js'].default).toBe('two')
})
const withBaseRecursive = import.meta.glob('**/*.js', {
base: '../outside',
eager: true,
})
it('should key nested results relative to base', () => {
expect(Object.keys(withBaseRecursive)).toEqual([
'./nested/three.js',
'./one.js',
'./two.js',
])
})
const withBaseNegative = import.meta.glob(['*.js', '!two.js'], {
base: '../outside',
eager: true,
})
it('should apply negative patterns relative to base', () => {
expect(Object.keys(withBaseNegative)).toEqual(['./one.js'])
})
// A `base` that itself walks up and back down again.
const withParentBase = import.meta.glob('*.js', {
base: '../../import-meta-glob-relative/outside',
eager: true,
})
it('should normalize a base that walks up and back down', () => {
expect(Object.keys(withParentBase)).toEqual(['./one.js', './two.js'])
})
// Control: patterns relative to the importer keep their `./`-prefixed keys.
const local = import.meta.glob('./local/*.js', { eager: true })
it('should keep origin-relative keys when no base is given', () => {
expect(Object.keys(local)).toEqual(['./local/local.js'])
expect(local['./local/local.js'].default).toBe('local')
})
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