Unverified Commit 15a05670 authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

Turbopack: Remove undocumented legacy syntax for built-in conditions (e.g.…

Turbopack: Remove undocumented legacy syntax for built-in conditions (e.g. foreign, browser) (#83068)

- https://github.com/vercel/next.js/pull/82857 provides a better way to do this that we intend to document.
- This syntax was never documented (outside of the types and tests). You wouldn't be able to figure out the built-in conditions without digging through the Turbopack source code.
parent 040e4676
use std::{collections::BTreeSet, str::FromStr};
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use either::Either; use either::Either;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
...@@ -667,21 +665,11 @@ impl TryFrom<ConfigConditionItem> for ConditionItem { ...@@ -667,21 +665,11 @@ impl TryFrom<ConfigConditionItem> for ConditionItem {
} }
} }
#[derive(
Clone, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue,
)]
#[serde(rename_all = "camelCase", untagged)]
pub enum RuleConfigItem {
Options(RuleConfigItemOptions),
LegacyConditional(FxIndexMap<RcStr, RuleConfigItem>),
LegacyBoolean(bool),
}
#[derive( #[derive(
Clone, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue,
)] )]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct RuleConfigItemOptions { pub struct RuleConfigItem {
pub loaders: Vec<LoaderItem>, pub loaders: Vec<LoaderItem>,
#[serde(default, alias = "as")] #[serde(default, alias = "as")]
pub rename_as: Option<RcStr>, pub rename_as: Option<RcStr>,
...@@ -1401,11 +1389,7 @@ impl NextConfig { ...@@ -1401,11 +1389,7 @@ impl NextConfig {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn webpack_rules( pub async fn webpack_rules(&self, project_path: FileSystemPath) -> Result<Vc<WebpackRules>> {
&self,
active_conditions: BTreeSet<WebpackLoaderBuiltinCondition>,
project_path: FileSystemPath,
) -> Result<Vc<WebpackRules>> {
let Some(turbo_rules) = self.turbopack.as_ref().and_then(|t| t.rules.as_ref()) else { let Some(turbo_rules) = self.turbopack.as_ref().and_then(|t| t.rules.as_ref()) else {
return Ok(Vc::cell(Vec::new())); return Ok(Vc::cell(Vec::new()));
}; };
...@@ -1429,43 +1413,6 @@ impl NextConfig { ...@@ -1429,43 +1413,6 @@ impl NextConfig {
.collect(), .collect(),
) )
} }
enum FindRuleResult<'a> {
Found(&'a RuleConfigItemOptions),
NotFound,
Break,
}
// This logic is needed for the `LegacyConditional`/`LegacyBoolean` configuration
// syntax. This is technically public syntax, but was never documented and it is
// unlikely that anyone is depending on it (outside of some Next.js internals).
fn find_rule<'a>(
rule: &'a RuleConfigItem,
active_conditions: &BTreeSet<WebpackLoaderBuiltinCondition>,
) -> FindRuleResult<'a> {
match rule {
RuleConfigItem::Options(rule) => FindRuleResult::Found(rule),
RuleConfigItem::LegacyConditional(map) => {
for (condition, rule) in map.iter() {
let condition = WebpackLoaderBuiltinCondition::from_str(condition);
if let Ok(condition) = condition
&& (condition == WebpackLoaderBuiltinCondition::Default
|| active_conditions.contains(&condition))
{
match find_rule(rule, active_conditions) {
FindRuleResult::Found(rule) => {
return FindRuleResult::Found(rule);
}
FindRuleResult::Break => {
return FindRuleResult::Break;
}
FindRuleResult::NotFound => {}
}
}
}
FindRuleResult::NotFound
}
RuleConfigItem::LegacyBoolean(_) => FindRuleResult::Break,
}
}
let config_file_path = || project_path.join(&self.config_file_name); let config_file_path = || project_path.join(&self.config_file_name);
for item in &rule_collection.0 { for item in &rule_collection.0 {
match item { match item {
...@@ -1479,13 +1426,11 @@ impl NextConfig { ...@@ -1479,13 +1426,11 @@ impl NextConfig {
}, },
)); ));
} }
RuleConfigCollectionItem::Full(rule_config_item) => { RuleConfigCollectionItem::Full(RuleConfigItem {
if let FindRuleResult::Found(RuleConfigItemOptions {
loaders, loaders,
rename_as, rename_as,
condition, condition,
}) = find_rule(rule_config_item, &active_conditions) }) => {
{
// If the extension contains a wildcard, and the rename_as does not, // If the extension contains a wildcard, and the rename_as does not,
// emit an issue to prevent users from encountering duplicate module // emit an issue to prevent users from encountering duplicate module
// names. // names.
...@@ -1531,7 +1476,6 @@ impl NextConfig { ...@@ -1531,7 +1476,6 @@ impl NextConfig {
} }
} }
} }
}
Ok(Vc::cell(rules)) Ok(Vc::cell(rules))
} }
...@@ -2001,11 +1945,11 @@ mod tests { ...@@ -2001,11 +1945,11 @@ mod tests {
} }
}); });
let rule_config: RuleConfigItemOptions = serde_json::from_value(json_value).unwrap(); let rule_config: RuleConfigItem = serde_json::from_value(json_value).unwrap();
assert_eq!( assert_eq!(
rule_config, rule_config,
RuleConfigItemOptions { RuleConfigItem {
loaders: vec![], loaders: vec![],
rename_as: Some(rcstr!("*.js")), rename_as: Some(rcstr!("*.js")),
condition: Some(ConfigConditionItem::All( condition: Some(ConfigConditionItem::All(
......
...@@ -5,7 +5,7 @@ use regex::Regex; ...@@ -5,7 +5,7 @@ use regex::Regex;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::{self, FileSystemEntryType, FileSystemPath}; use turbo_tasks_fs::{self, FileSystemEntryType, FileSystemPath};
use turbopack::module_options::LoaderRuleItem; use turbopack::module_options::{ConditionItem, LoaderRuleItem};
use turbopack_core::{ use turbopack_core::{
issue::{Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString}, issue::{Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString},
reference_type::{CommonJsReferenceSubType, ReferenceType}, reference_type::{CommonJsReferenceSubType, ReferenceType},
...@@ -13,6 +13,8 @@ use turbopack_core::{ ...@@ -13,6 +13,8 @@ use turbopack_core::{
}; };
use turbopack_node::transforms::webpack::WebpackLoaderItem; use turbopack_node::transforms::webpack::WebpackLoaderItem;
use crate::next_shared::webpack_rules::WebpackLoaderBuiltinCondition;
// https://babeljs.io/docs/config-files // https://babeljs.io/docs/config-files
// TODO: Also support a `babel` key in a package.json file // TODO: Also support a `babel` key in a package.json file
const BABEL_CONFIG_FILES: &[&str] = &[ const BABEL_CONFIG_FILES: &[&str] = &[
...@@ -89,7 +91,9 @@ pub async fn get_babel_loader_rules( ...@@ -89,7 +91,9 @@ pub async fn get_babel_loader_rules(
options: Default::default(), options: Default::default(),
}]), }]),
rename_as: Some(rcstr!("*")), rename_as: Some(rcstr!("*")),
condition: None, condition: Some(ConditionItem::Not(Box::new(ConditionItem::Builtin(
RcStr::from(WebpackLoaderBuiltinCondition::Foreign.as_str()),
)))),
}, },
)]) )])
} }
......
...@@ -149,7 +149,7 @@ pub async fn webpack_loader_options( ...@@ -149,7 +149,7 @@ pub async fn webpack_loader_options(
builtin_conditions: BTreeSet<WebpackLoaderBuiltinCondition>, builtin_conditions: BTreeSet<WebpackLoaderBuiltinCondition>,
) -> Result<Vc<OptionWebpackLoadersOptions>> { ) -> Result<Vc<OptionWebpackLoadersOptions>> {
let mut rules = next_config let mut rules = next_config
.webpack_rules(builtin_conditions.clone(), project_path.clone()) .webpack_rules(project_path.clone())
.owned() .owned()
.await?; .await?;
......
...@@ -16,7 +16,6 @@ import type { ...@@ -16,7 +16,6 @@ import type {
TurbopackRuleCondition, TurbopackRuleCondition,
TurbopackRuleConfigCollection, TurbopackRuleConfigCollection,
TurbopackRuleConfigItem, TurbopackRuleConfigItem,
TurbopackRuleConfigItemOptions,
} from '../../server/config-shared' } from '../../server/config-shared'
import { isDeepStrictEqual } from 'util' import { isDeepStrictEqual } from 'util'
import { type DefineEnvOptions, getDefineEnv } from '../define-env' import { type DefineEnvOptions, getDefineEnv } from '../define-env'
...@@ -836,6 +835,10 @@ function bindingToApi( ...@@ -836,6 +835,10 @@ function bindingToApi(
for (const key of ruleKeys) { for (const key of ruleKeys) {
nextConfig.turbopack.conditions[`#reactCompiler/${key}`] = { nextConfig.turbopack.conditions[`#reactCompiler/${key}`] = {
all: [
'browser',
{ not: 'foreign' },
{
path: key, path: key,
content: content:
options.compilationMode === 'annotation' options.compilationMode === 'annotation'
...@@ -845,10 +848,10 @@ function bindingToApi( ...@@ -845,10 +848,10 @@ function bindingToApi(
? // Matches declaration or useXXX or </ (closing jsx) or /> (self closing jsx) ? // Matches declaration or useXXX or </ (closing jsx) or /> (self closing jsx)
/['"]use memo['"]|\Wuse[A-Z]|<\/|\/>/ /['"]use memo['"]|\Wuse[A-Z]|<\/|\/>/
: undefined, : undefined,
},
],
} }
nextConfig.turbopack.rules[`#reactCompiler/${key}`] = { nextConfig.turbopack.rules[`#reactCompiler/${key}`] = {
browser: {
foreign: false,
loaders: [ loaders: [
getReactCompilerLoader( getReactCompilerLoader(
reactCompilerOptions, reactCompilerOptions,
...@@ -858,7 +861,6 @@ function bindingToApi( ...@@ -858,7 +861,6 @@ function bindingToApi(
/* reactCompilerExclude */ undefined /* reactCompilerExclude */ undefined
), ),
], ],
},
} }
} }
} }
...@@ -1039,26 +1041,14 @@ function bindingToApi( ...@@ -1039,26 +1041,14 @@ function bindingToApi(
glob: string glob: string
): any { ): any {
if (!rule) return rule if (!rule) return rule
let serializedRule: any = rule for (const item of rule.loaders) {
if ('loaders' in rule) {
const narrowedRule = rule as TurbopackRuleConfigItemOptions
for (const item of narrowedRule.loaders) {
checkLoaderItem(item, glob) checkLoaderItem(item, glob)
} }
if (narrowedRule.condition != null) { let serializedRule: any = rule
if (rule.condition != null) {
serializedRule = { serializedRule = {
...rule, ...rule,
condition: serializeRuleCondition(narrowedRule.condition), condition: serializeRuleCondition(rule.condition),
}
}
} else {
serializedRule = {}
for (const [key, value] of Object.entries(rule)) {
if (typeof value === 'object' && value) {
serializedRule[key] = serializeConfigItem(value, glob)
} else {
serializedRule[key] = value
}
} }
} }
return serializedRule return serializedRule
......
...@@ -11,7 +11,6 @@ import type { ...@@ -11,7 +11,6 @@ import type {
DeprecatedExperimentalTurboOptions, DeprecatedExperimentalTurboOptions,
TurbopackOptions, TurbopackOptions,
TurbopackRuleConfigItem, TurbopackRuleConfigItem,
TurbopackRuleConfigItemOptions,
TurbopackRuleConfigCollection, TurbopackRuleConfigCollection,
TurbopackRuleCondition, TurbopackRuleCondition,
TurbopackLoaderBuiltinCondition, TurbopackLoaderBuiltinCondition,
...@@ -135,26 +134,17 @@ const zTurbopackCondition: zod.ZodType<TurbopackRuleCondition> = z.union([ ...@@ -135,26 +134,17 @@ const zTurbopackCondition: zod.ZodType<TurbopackRuleCondition> = z.union([
}), }),
]) ])
const zTurbopackRuleConfigItemOptions: zod.ZodType<TurbopackRuleConfigItemOptions> = const zTurbopackRuleConfigItem: zod.ZodType<TurbopackRuleConfigItem> =
z.strictObject({ z.strictObject({
loaders: z.array(zTurbopackLoaderItem), loaders: z.array(zTurbopackLoaderItem),
as: z.string().optional(), as: z.string().optional(),
condition: zTurbopackCondition.optional(), condition: zTurbopackCondition.optional(),
}) })
const zTurbopackRuleConfigItem: zod.ZodType<TurbopackRuleConfigItem> = z.union([
z.literal(false),
z.record(
zTurbopackLoaderBuiltinCondition,
z.lazy(() => zTurbopackRuleConfigItem)
),
zTurbopackRuleConfigItemOptions,
])
const zTurbopackRuleConfigCollection: zod.ZodType<TurbopackRuleConfigCollection> = const zTurbopackRuleConfigCollection: zod.ZodType<TurbopackRuleConfigCollection> =
z.union([ z.union([
zTurbopackRuleConfigItem, zTurbopackRuleConfigItem,
z.array(z.union([zTurbopackLoaderItem, zTurbopackRuleConfigItemOptions])), z.array(z.union([zTurbopackLoaderItem, zTurbopackRuleConfigItem])),
]) ])
const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({ const zTurbopackConfig: zod.ZodType<TurbopackOptions> = z.strictObject({
......
...@@ -278,17 +278,12 @@ export type TurbopackRuleCondition = ...@@ -278,17 +278,12 @@ export type TurbopackRuleCondition =
content?: RegExp content?: RegExp
} }
export type TurbopackRuleConfigItemOptions = { export type TurbopackRuleConfigItem = {
loaders: TurbopackLoaderItem[] loaders: TurbopackLoaderItem[]
as?: string as?: string
condition?: TurbopackRuleCondition condition?: TurbopackRuleCondition
} }
export type TurbopackRuleConfigItem =
| TurbopackRuleConfigItemOptions
| { [condition in TurbopackLoaderBuiltinCondition]?: TurbopackRuleConfigItem }
| false
/** /**
* This can be an object representing a single configuration, or a list of * This can be an object representing a single configuration, or a list of
* loaders and/or rule configuration objects. * loaders and/or rule configuration objects.
...@@ -300,7 +295,7 @@ export type TurbopackRuleConfigItem = ...@@ -300,7 +295,7 @@ export type TurbopackRuleConfigItem =
*/ */
export type TurbopackRuleConfigCollection = export type TurbopackRuleConfigCollection =
| TurbopackRuleConfigItem | TurbopackRuleConfigItem
| (TurbopackLoaderItem | TurbopackRuleConfigItemOptions)[] | (TurbopackLoaderItem | TurbopackRuleConfigItem)[]
export interface TurbopackOptions { export interface TurbopackOptions {
/** /**
......
...@@ -4,9 +4,9 @@ ...@@ -4,9 +4,9 @@
const nextConfig = { const nextConfig = {
turbopack: { turbopack: {
rules: { rules: {
'*.test-file.js': { '*.test-file.js': [
browser: { {
foreign: { condition: { all: ['browser', 'foreign'] },
loaders: [ loaders: [
{ {
loader: require.resolve('./test-file-loader.js'), loader: require.resolve('./test-file-loader.js'),
...@@ -14,7 +14,8 @@ const nextConfig = { ...@@ -14,7 +14,8 @@ const nextConfig = {
}, },
], ],
}, },
default: { {
condition: { all: ['browser', { not: 'foreign' }] },
loaders: [ loaders: [
{ {
loader: require.resolve('./test-file-loader.js'), loader: require.resolve('./test-file-loader.js'),
...@@ -22,9 +23,8 @@ const nextConfig = { ...@@ -22,9 +23,8 @@ const nextConfig = {
}, },
], ],
}, },
}, {
foreign: false, condition: { not: { any: ['browser', 'foreign'] } },
default: {
loaders: [ loaders: [
{ {
loader: require.resolve('./test-file-loader.js'), loader: require.resolve('./test-file-loader.js'),
...@@ -32,7 +32,7 @@ const nextConfig = { ...@@ -32,7 +32,7 @@ const nextConfig = {
}, },
], ],
}, },
}, ],
}, },
}, },
} }
......
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