turbopack_node/transforms/
webpack.rs

1use std::mem::take;
2
3use anyhow::{Context, Result, bail};
4use base64::Engine;
5use either::Either;
6use futures::try_join;
7use serde::{Deserialize, Serialize};
8use serde_json::{Map as JsonMap, Value as JsonValue, json};
9use serde_with::serde_as;
10use turbo_rcstr::{RcStr, rcstr};
11use turbo_tasks::{
12    Completion, NonLocalValue, OperationValue, OperationVc, ResolvedVc, TaskInput, TryJoinIterExt,
13    ValueToString, Vc, trace::TraceRawVcs,
14};
15use turbo_tasks_bytes::stream::SingleValue;
16use turbo_tasks_env::ProcessEnv;
17use turbo_tasks_fs::{
18    File, FileContent, FileSystemPath, glob::Glob, json::parse_json_with_source_context, rope::Rope,
19};
20use turbopack_core::{
21    asset::{Asset, AssetContent},
22    chunk::ChunkingContext,
23    context::{AssetContext, ProcessResult},
24    file_source::FileSource,
25    ident::AssetIdent,
26    issue::{
27        Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, OptionIssueSource,
28        OptionStyledString, StyledString,
29    },
30    module::Module,
31    reference_type::{InnerAssets, ReferenceType},
32    resolve::{
33        options::{ConditionValue, ResolveInPackage, ResolveIntoPackage, ResolveOptions},
34        parse::Request,
35        pattern::Pattern,
36        resolve,
37    },
38    source::Source,
39    source_map::{
40        GenerateSourceMap, OptionStringifiedSourceMap, utils::resolve_source_map_sources,
41    },
42    source_transform::SourceTransform,
43    virtual_source::VirtualSource,
44};
45use turbopack_resolve::{
46    ecmascript::get_condition_maps, resolve::resolve_options,
47    resolve_options_context::ResolveOptionsContext,
48};
49
50use super::util::{EmittedAsset, emitted_assets_to_virtual_sources};
51use crate::{
52    AssetsForSourceMapping,
53    debug::should_debug,
54    embed_js::embed_file_path,
55    evaluate::{
56        EnvVarTracking, EvaluateContext, EvaluationIssue, JavaScriptEvaluation,
57        JavaScriptStreamSender, compute, custom_evaluate, get_evaluate_pool,
58    },
59    execution_context::ExecutionContext,
60    pool::{FormattingMode, NodeJsPool},
61    source_map::{StackFrame, StructuredError},
62};
63
64#[serde_as]
65#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
66struct BytesBase64 {
67    #[serde_as(as = "serde_with::base64::Base64")]
68    binary: Vec<u8>,
69}
70
71#[derive(Debug, Serialize, Deserialize, Clone)]
72#[serde(rename_all = "camelCase")]
73#[turbo_tasks::value(serialization = "custom")]
74struct WebpackLoadersProcessingResult {
75    #[serde(with = "either::serde_untagged")]
76    #[turbo_tasks(debug_ignore, trace_ignore)]
77    source: Either<RcStr, BytesBase64>,
78    map: Option<RcStr>,
79    #[turbo_tasks(trace_ignore)]
80    assets: Option<Vec<EmittedAsset>>,
81}
82
83#[derive(
84    Clone, PartialEq, Eq, Debug, TraceRawVcs, Serialize, Deserialize, NonLocalValue, OperationValue,
85)]
86pub struct WebpackLoaderItem {
87    pub loader: RcStr,
88    pub options: serde_json::Map<String, serde_json::Value>,
89}
90
91#[derive(Debug, Clone)]
92#[turbo_tasks::value(shared, transparent)]
93pub struct WebpackLoaderItems(pub Vec<WebpackLoaderItem>);
94
95#[turbo_tasks::value]
96pub struct WebpackLoaders {
97    evaluate_context: ResolvedVc<Box<dyn AssetContext>>,
98    execution_context: ResolvedVc<ExecutionContext>,
99    loaders: ResolvedVc<WebpackLoaderItems>,
100    rename_as: Option<RcStr>,
101    resolve_options_context: ResolvedVc<ResolveOptionsContext>,
102    source_maps: bool,
103}
104
105#[turbo_tasks::value_impl]
106impl WebpackLoaders {
107    #[turbo_tasks::function]
108    pub fn new(
109        evaluate_context: ResolvedVc<Box<dyn AssetContext>>,
110        execution_context: ResolvedVc<ExecutionContext>,
111        loaders: ResolvedVc<WebpackLoaderItems>,
112        rename_as: Option<RcStr>,
113        resolve_options_context: ResolvedVc<ResolveOptionsContext>,
114        source_maps: bool,
115    ) -> Vc<Self> {
116        WebpackLoaders {
117            evaluate_context,
118            execution_context,
119            loaders,
120            rename_as,
121            resolve_options_context,
122            source_maps,
123        }
124        .cell()
125    }
126}
127
128#[turbo_tasks::value_impl]
129impl SourceTransform for WebpackLoaders {
130    #[turbo_tasks::function]
131    fn transform(
132        self: ResolvedVc<Self>,
133        source: ResolvedVc<Box<dyn Source>>,
134    ) -> Vc<Box<dyn Source>> {
135        Vc::upcast(
136            WebpackLoadersProcessedAsset {
137                transform: self,
138                source,
139            }
140            .cell(),
141        )
142    }
143}
144
145#[turbo_tasks::value]
146struct WebpackLoadersProcessedAsset {
147    transform: ResolvedVc<WebpackLoaders>,
148    source: ResolvedVc<Box<dyn Source>>,
149}
150
151#[turbo_tasks::value_impl]
152impl Source for WebpackLoadersProcessedAsset {
153    #[turbo_tasks::function]
154    async fn ident(&self) -> Result<Vc<AssetIdent>> {
155        Ok(
156            if let Some(rename_as) = self.transform.await?.rename_as.as_deref() {
157                self.source.ident().rename_as(rename_as.into())
158            } else {
159                self.source.ident()
160            },
161        )
162    }
163}
164
165#[turbo_tasks::value_impl]
166impl Asset for WebpackLoadersProcessedAsset {
167    #[turbo_tasks::function]
168    async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
169        Ok(*self.process().await?.content)
170    }
171}
172
173#[turbo_tasks::value_impl]
174impl GenerateSourceMap for WebpackLoadersProcessedAsset {
175    #[turbo_tasks::function]
176    async fn generate_source_map(self: Vc<Self>) -> Result<Vc<OptionStringifiedSourceMap>> {
177        Ok(*self.process().await?.source_map)
178    }
179}
180
181#[turbo_tasks::value]
182struct ProcessWebpackLoadersResult {
183    content: ResolvedVc<AssetContent>,
184    source_map: ResolvedVc<OptionStringifiedSourceMap>,
185    assets: Vec<ResolvedVc<VirtualSource>>,
186}
187
188#[turbo_tasks::function]
189async fn webpack_loaders_executor(
190    evaluate_context: Vc<Box<dyn AssetContext>>,
191) -> Result<Vc<ProcessResult>> {
192    Ok(evaluate_context.process(
193        Vc::upcast(FileSource::new(
194            embed_file_path(rcstr!("transforms/webpack-loaders.ts"))
195                .owned()
196                .await?,
197        )),
198        ReferenceType::Internal(InnerAssets::empty().to_resolved().await?),
199    ))
200}
201
202#[turbo_tasks::value_impl]
203impl WebpackLoadersProcessedAsset {
204    #[turbo_tasks::function]
205    async fn process(self: Vc<Self>) -> Result<Vc<ProcessWebpackLoadersResult>> {
206        let this = self.await?;
207        let transform = this.transform.await?;
208
209        let ExecutionContext {
210            project_path,
211            chunking_context,
212            env,
213        } = &*transform.execution_context.await?;
214        let source_content = this.source.content();
215        let AssetContent::File(file) = *source_content.await? else {
216            bail!("Webpack Loaders transform only support transforming files");
217        };
218        let FileContent::Content(file_content) = &*file.await? else {
219            return Ok(ProcessWebpackLoadersResult {
220                content: AssetContent::File(FileContent::NotFound.resolved_cell()).resolved_cell(),
221                assets: Vec::new(),
222                source_map: ResolvedVc::cell(None),
223            }
224            .cell());
225        };
226
227        // If the content is not a valid string (e.g. binary file), handle the error and pass a
228        // Buffer to Webpack instead of a Base64 string so the build process doesn't crash.
229        let content: JsonValue = match file_content.content().to_str() {
230            Ok(utf8_str) => utf8_str.to_string().into(),
231            Err(_) => JsonValue::Object(JsonMap::from_iter(std::iter::once((
232                "binary".to_string(),
233                JsonValue::from(
234                    base64::engine::general_purpose::STANDARD
235                        .encode(file_content.content().to_bytes()),
236                ),
237            )))),
238        };
239        let evaluate_context = transform.evaluate_context;
240
241        let webpack_loaders_executor = webpack_loaders_executor(*evaluate_context)
242            .module()
243            .to_resolved()
244            .await?;
245
246        let resource_fs_path = this.source.ident().path().owned().await?;
247        let resource_fs_path_ref = resource_fs_path.clone();
248        let Some(resource_path) = project_path.get_relative_path_to(&resource_fs_path_ref) else {
249            bail!(format!(
250                "Resource path \"{}\" need to be on project filesystem \"{}\"",
251                resource_fs_path_ref, project_path
252            ));
253        };
254        let loaders = transform.loaders.await?;
255        let config_value = evaluate_webpack_loader(WebpackLoaderContext {
256            module_asset: webpack_loaders_executor,
257            cwd: project_path.clone(),
258            env: *env,
259            context_source_for_issue: this.source,
260            asset_context: evaluate_context,
261            chunking_context: *chunking_context,
262            resolve_options_context: Some(transform.resolve_options_context),
263            args: vec![
264                ResolvedVc::cell(content),
265                // We need to pass the query string to the loader
266                ResolvedVc::cell(resource_path.to_string().into()),
267                ResolvedVc::cell(this.source.ident().await?.query.to_string().into()),
268                ResolvedVc::cell(json!(*loaders)),
269                ResolvedVc::cell(transform.source_maps.into()),
270            ],
271            additional_invalidation: Completion::immutable().to_resolved().await?,
272        })
273        .await?;
274
275        let SingleValue::Single(val) = config_value.try_into_single().await? else {
276            // An error happened, which has already been converted into an issue.
277            return Ok(ProcessWebpackLoadersResult {
278                content: AssetContent::File(FileContent::NotFound.resolved_cell()).resolved_cell(),
279                assets: Vec::new(),
280                source_map: ResolvedVc::cell(None),
281            }
282            .cell());
283        };
284        let processed: WebpackLoadersProcessingResult = parse_json_with_source_context(
285            val.to_str()?,
286        )
287        .context("Unable to deserializate response from webpack loaders transform operation")?;
288
289        // handle SourceMap
290        let source_map = if !transform.source_maps {
291            None
292        } else {
293            processed
294                .map
295                .map(|source_map| Rope::from(source_map.into_owned()))
296        };
297        let source_map = resolve_source_map_sources(source_map.as_ref(), resource_fs_path).await?;
298
299        let file = match processed.source {
300            Either::Left(str) => File::from(str),
301            Either::Right(bytes) => File::from(bytes.binary),
302        };
303        let assets = emitted_assets_to_virtual_sources(processed.assets).await?;
304
305        let content =
306            AssetContent::File(FileContent::Content(file).resolved_cell()).resolved_cell();
307        Ok(ProcessWebpackLoadersResult {
308            content,
309            assets,
310            source_map: ResolvedVc::cell(source_map),
311        }
312        .cell())
313    }
314}
315
316#[turbo_tasks::function]
317pub(crate) async fn evaluate_webpack_loader(
318    webpack_loader_context: WebpackLoaderContext,
319) -> Result<Vc<JavaScriptEvaluation>> {
320    custom_evaluate(webpack_loader_context).await
321}
322
323#[turbo_tasks::function]
324async fn compute_webpack_loader_evaluation(
325    webpack_loader_context: WebpackLoaderContext,
326    sender: Vc<JavaScriptStreamSender>,
327) -> Result<Vc<()>> {
328    compute(webpack_loader_context, sender).await
329}
330
331#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
332#[serde(rename_all = "camelCase")]
333enum LogType {
334    Error,
335    Warn,
336    Info,
337    Log,
338    Debug,
339    Trace,
340    Group,
341    GroupCollapsed,
342    GroupEnd,
343    Profile,
344    ProfileEnd,
345    Time,
346    Clear,
347    Status,
348}
349
350#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
351#[serde(rename_all = "camelCase")]
352pub struct LogInfo {
353    time: u64,
354    log_type: LogType,
355    args: Vec<JsonValue>,
356    trace: Option<Vec<StackFrame<'static>>>,
357}
358
359#[derive(Deserialize, Debug)]
360#[serde(tag = "type", rename_all = "camelCase")]
361pub enum InfoMessage {
362    // Sent to inform Turbopack about the dependencies of the task.
363    // All fields are `default` since it is ok for the client to
364    // simply omit instead of sending empty arrays.
365    Dependencies {
366        #[serde(default)]
367        env_variables: Vec<RcStr>,
368        #[serde(default)]
369        file_paths: Vec<RcStr>,
370        #[serde(default)]
371        directories: Vec<(RcStr, RcStr)>,
372        #[serde(default)]
373        build_file_paths: Vec<RcStr>,
374    },
375    EmittedError {
376        severity: IssueSeverity,
377        error: StructuredError,
378    },
379    Log {
380        logs: Vec<LogInfo>,
381    },
382}
383
384#[derive(Debug, Clone, TaskInput, Hash, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs)]
385#[serde(rename_all = "camelCase")]
386pub struct WebpackResolveOptions {
387    alias_fields: Option<Vec<RcStr>>,
388    condition_names: Option<Vec<RcStr>>,
389    no_package_json: bool,
390    extensions: Option<Vec<RcStr>>,
391    main_fields: Option<Vec<RcStr>>,
392    no_exports_field: bool,
393    main_files: Option<Vec<RcStr>>,
394    no_modules: bool,
395    prefer_relative: bool,
396}
397
398#[derive(Deserialize, Debug)]
399#[serde(tag = "type", rename_all = "camelCase")]
400pub enum RequestMessage {
401    #[serde(rename_all = "camelCase")]
402    Resolve {
403        options: WebpackResolveOptions,
404        lookup_path: RcStr,
405        request: RcStr,
406    },
407}
408
409#[derive(Serialize, Debug)]
410#[serde(untagged)]
411pub enum ResponseMessage {
412    Resolve { path: RcStr },
413}
414
415#[derive(Clone, PartialEq, Eq, Hash, TaskInput, Serialize, Deserialize, Debug, TraceRawVcs)]
416pub struct WebpackLoaderContext {
417    pub module_asset: ResolvedVc<Box<dyn Module>>,
418    pub cwd: FileSystemPath,
419    pub env: ResolvedVc<Box<dyn ProcessEnv>>,
420    pub context_source_for_issue: ResolvedVc<Box<dyn Source>>,
421    pub asset_context: ResolvedVc<Box<dyn AssetContext>>,
422    pub chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
423    pub resolve_options_context: Option<ResolvedVc<ResolveOptionsContext>>,
424    pub args: Vec<ResolvedVc<JsonValue>>,
425    pub additional_invalidation: ResolvedVc<Completion>,
426}
427
428impl EvaluateContext for WebpackLoaderContext {
429    type InfoMessage = InfoMessage;
430    type RequestMessage = RequestMessage;
431    type ResponseMessage = ResponseMessage;
432    type State = Vec<LogInfo>;
433
434    async fn compute(self, sender: Vc<JavaScriptStreamSender>) -> Result<()> {
435        compute_webpack_loader_evaluation(self, sender)
436            .as_side_effect()
437            .await
438    }
439
440    fn pool(&self) -> OperationVc<crate::pool::NodeJsPool> {
441        get_evaluate_pool(
442            self.module_asset,
443            self.cwd.clone(),
444            self.env,
445            self.asset_context,
446            self.chunking_context,
447            None,
448            self.additional_invalidation,
449            should_debug("webpack_loader"),
450            // Env vars are read untracked, since we want a more granular dependency on certain env
451            // vars only. So the runtime code tracks which env vars are read and send a dependency
452            // message for them.
453            EnvVarTracking::Untracked,
454        )
455    }
456
457    fn args(&self) -> &[ResolvedVc<serde_json::Value>] {
458        &self.args
459    }
460
461    fn cwd(&self) -> Vc<turbo_tasks_fs::FileSystemPath> {
462        self.cwd.clone().cell()
463    }
464
465    fn keep_alive(&self) -> bool {
466        true
467    }
468
469    async fn emit_error(&self, error: StructuredError, pool: &NodeJsPool) -> Result<()> {
470        EvaluationIssue {
471            error,
472            source: IssueSource::from_source_only(self.context_source_for_issue),
473            assets_for_source_mapping: pool.assets_for_source_mapping,
474            assets_root: pool.assets_root.clone(),
475            root_path: self.chunking_context.root_path().owned().await?,
476        }
477        .resolved_cell()
478        .emit();
479        Ok(())
480    }
481
482    async fn info(
483        &self,
484        state: &mut Self::State,
485        data: Self::InfoMessage,
486        pool: &NodeJsPool,
487    ) -> Result<()> {
488        match data {
489            InfoMessage::Dependencies {
490                env_variables,
491                file_paths,
492                directories,
493                build_file_paths,
494            } => {
495                // Track dependencies of the loader task
496                // TODO: Because these are reported _after_ the loader actually read the dependency
497                // there is a race condition where we may miss updates that race
498                // with the loader execution.
499
500                // Track all the subscriptions in parallel, since certain loaders like tailwind
501                // might add thousands of subscriptions.
502                let env_subscriptions = env_variables
503                    .iter()
504                    .map(|e| self.env.read(e.clone()))
505                    .try_join();
506                let file_subscriptions = file_paths
507                    .iter()
508                    .map(|p| async move { self.cwd.join(p)?.read().await })
509                    .try_join();
510                let directory_subscriptions = directories
511                    .iter()
512                    .map(|(dir, glob)| async move {
513                        self.cwd
514                            .join(dir)?
515                            .track_glob(Glob::new(glob.clone()), false)
516                            .await
517                    })
518                    .try_join();
519                let build_paths = build_file_paths
520                    .iter()
521                    .map(|path| async move { self.cwd.join(path) })
522                    .try_join();
523                let (resolved_build_paths, ..) = try_join!(
524                    build_paths,
525                    env_subscriptions,
526                    file_subscriptions,
527                    directory_subscriptions
528                )?;
529
530                for build_path in resolved_build_paths {
531                    BuildDependencyIssue {
532                        source: IssueSource::from_source_only(self.context_source_for_issue),
533                        path: build_path,
534                    }
535                    .resolved_cell()
536                    .emit();
537                }
538            }
539            InfoMessage::EmittedError { error, severity } => {
540                EvaluateEmittedErrorIssue {
541                    source: IssueSource::from_source_only(self.context_source_for_issue),
542                    error,
543                    severity,
544                    assets_for_source_mapping: pool.assets_for_source_mapping,
545                    assets_root: pool.assets_root.clone(),
546                    project_dir: self.chunking_context.root_path().owned().await?,
547                }
548                .resolved_cell()
549                .emit();
550            }
551            InfoMessage::Log { logs } => {
552                state.extend(logs);
553            }
554        }
555        Ok(())
556    }
557
558    async fn request(
559        &self,
560        _state: &mut Self::State,
561        data: Self::RequestMessage,
562        _pool: &NodeJsPool,
563    ) -> Result<Self::ResponseMessage> {
564        match data {
565            RequestMessage::Resolve {
566                options: webpack_options,
567                lookup_path,
568                request,
569            } => {
570                let Some(resolve_options_context) = self.resolve_options_context else {
571                    bail!("Resolve options are not available in this context");
572                };
573                let lookup_path = self.cwd.join(&lookup_path)?;
574                let request = Request::parse(Pattern::Constant(request));
575                let options = resolve_options(lookup_path.clone(), *resolve_options_context);
576
577                let options = apply_webpack_resolve_options(options, webpack_options);
578
579                let resolved = resolve(
580                    lookup_path.clone(),
581                    ReferenceType::Undefined,
582                    request,
583                    options,
584                );
585
586                if let Some(source) = *resolved.first_source().await? {
587                    if let Some(path) = self
588                        .cwd
589                        .get_relative_path_to(&*source.ident().path().await?)
590                    {
591                        Ok(ResponseMessage::Resolve { path })
592                    } else {
593                        bail!(
594                            "Resolving {} in {} ends up on a different filesystem",
595                            request.to_string().await?,
596                            lookup_path.value_to_string().await?
597                        );
598                    }
599                } else {
600                    bail!(
601                        "Unable to resolve {} in {}",
602                        request.to_string().await?,
603                        lookup_path.value_to_string().await?
604                    );
605                }
606            }
607        }
608    }
609
610    async fn finish(&self, state: Self::State, pool: &NodeJsPool) -> Result<()> {
611        let has_errors = state.iter().any(|log| log.log_type == LogType::Error);
612        let has_warnings = state.iter().any(|log| log.log_type == LogType::Warn);
613        if has_errors || has_warnings {
614            let logs = state
615                .into_iter()
616                .filter(|log| {
617                    matches!(
618                        log.log_type,
619                        LogType::Error
620                            | LogType::Warn
621                            | LogType::Info
622                            | LogType::Log
623                            | LogType::Clear,
624                    )
625                })
626                .collect();
627
628            EvaluateErrorLoggingIssue {
629                source: IssueSource::from_source_only(self.context_source_for_issue),
630                logging: logs,
631                severity: if has_errors {
632                    IssueSeverity::Error
633                } else {
634                    IssueSeverity::Warning
635                },
636                assets_for_source_mapping: pool.assets_for_source_mapping,
637                assets_root: pool.assets_root.clone(),
638                project_dir: self.chunking_context.root_path().owned().await?,
639            }
640            .resolved_cell()
641            .emit();
642        }
643        Ok(())
644    }
645}
646
647#[turbo_tasks::function]
648async fn apply_webpack_resolve_options(
649    resolve_options: Vc<ResolveOptions>,
650    webpack_resolve_options: WebpackResolveOptions,
651) -> Result<Vc<ResolveOptions>> {
652    let mut resolve_options = resolve_options.owned().await?;
653    if let Some(alias_fields) = webpack_resolve_options.alias_fields {
654        let mut old = resolve_options
655            .in_package
656            .extract_if(0.., |field| {
657                matches!(field, ResolveInPackage::AliasField(..))
658            })
659            .collect::<Vec<_>>();
660        for field in alias_fields {
661            if &*field == "..." {
662                resolve_options.in_package.extend(take(&mut old));
663            } else {
664                resolve_options
665                    .in_package
666                    .push(ResolveInPackage::AliasField(field));
667            }
668        }
669    }
670    if let Some(condition_names) = webpack_resolve_options.condition_names {
671        for conditions in get_condition_maps(&mut resolve_options) {
672            let mut old = take(conditions);
673            for name in &condition_names {
674                if name == "..." {
675                    conditions.extend(take(&mut old));
676                } else {
677                    conditions.insert(name.clone(), ConditionValue::Set);
678                }
679            }
680        }
681    }
682    if webpack_resolve_options.no_package_json {
683        resolve_options.into_package.retain(|item| {
684            !matches!(
685                item,
686                ResolveIntoPackage::ExportsField { .. } | ResolveIntoPackage::MainField { .. }
687            )
688        });
689    }
690    if let Some(mut extensions) = webpack_resolve_options.extensions {
691        if let Some(pos) = extensions.iter().position(|ext| ext == "...") {
692            extensions.splice(pos..=pos, take(&mut resolve_options.extensions));
693        }
694        resolve_options.extensions = extensions;
695    }
696    if let Some(main_fields) = webpack_resolve_options.main_fields {
697        let mut old = resolve_options
698            .into_package
699            .extract_if(0.., |field| {
700                matches!(field, ResolveIntoPackage::MainField { .. })
701            })
702            .collect::<Vec<_>>();
703        for field in main_fields {
704            if &*field == "..." {
705                resolve_options.into_package.extend(take(&mut old));
706            } else {
707                resolve_options
708                    .into_package
709                    .push(ResolveIntoPackage::MainField { field });
710            }
711        }
712    }
713    if webpack_resolve_options.no_exports_field {
714        resolve_options
715            .into_package
716            .retain(|field| !matches!(field, ResolveIntoPackage::ExportsField { .. }));
717    }
718    if let Some(main_files) = webpack_resolve_options.main_files {
719        resolve_options.default_files = main_files;
720    }
721    if webpack_resolve_options.no_modules {
722        resolve_options.modules.clear();
723    }
724    if webpack_resolve_options.prefer_relative {
725        resolve_options.prefer_relative = true;
726    }
727    Ok(resolve_options.cell())
728}
729
730/// An issue that occurred while evaluating node code.
731#[turbo_tasks::value(shared)]
732pub struct BuildDependencyIssue {
733    pub path: FileSystemPath,
734    pub source: IssueSource,
735}
736
737#[turbo_tasks::value_impl]
738impl Issue for BuildDependencyIssue {
739    fn severity(&self) -> IssueSeverity {
740        IssueSeverity::Warning
741    }
742
743    #[turbo_tasks::function]
744    fn title(&self) -> Vc<StyledString> {
745        StyledString::Text(rcstr!("Build dependencies are not yet supported")).cell()
746    }
747
748    #[turbo_tasks::function]
749    fn stage(&self) -> Vc<IssueStage> {
750        IssueStage::Unsupported.cell()
751    }
752
753    #[turbo_tasks::function]
754    fn file_path(&self) -> Vc<FileSystemPath> {
755        self.source.file_path()
756    }
757
758    #[turbo_tasks::function]
759    async fn description(&self) -> Result<Vc<OptionStyledString>> {
760        Ok(Vc::cell(Some(
761            StyledString::Line(vec![
762                StyledString::Text(rcstr!("The file at ")),
763                StyledString::Code(self.path.to_string().into()),
764                StyledString::Text(
765                    " is a build dependency, which is not yet implemented.
766    Changing this file or any dependency will not be recognized and might require restarting the \
767                     server"
768                        .into(),
769                ),
770            ])
771            .resolved_cell(),
772        )))
773    }
774
775    #[turbo_tasks::function]
776    fn source(&self) -> Vc<OptionIssueSource> {
777        Vc::cell(Some(self.source))
778    }
779}
780
781#[turbo_tasks::value(shared)]
782pub struct EvaluateEmittedErrorIssue {
783    pub source: IssueSource,
784    pub severity: IssueSeverity,
785    pub error: StructuredError,
786    pub assets_for_source_mapping: ResolvedVc<AssetsForSourceMapping>,
787    pub assets_root: FileSystemPath,
788    pub project_dir: FileSystemPath,
789}
790
791#[turbo_tasks::value_impl]
792impl Issue for EvaluateEmittedErrorIssue {
793    #[turbo_tasks::function]
794    fn file_path(&self) -> Vc<FileSystemPath> {
795        self.source.file_path()
796    }
797
798    #[turbo_tasks::function]
799    fn stage(&self) -> Vc<IssueStage> {
800        IssueStage::Transform.cell()
801    }
802
803    fn severity(&self) -> IssueSeverity {
804        self.severity
805    }
806
807    #[turbo_tasks::function]
808    fn title(&self) -> Vc<StyledString> {
809        StyledString::Text(rcstr!("Issue while running loader")).cell()
810    }
811
812    #[turbo_tasks::function]
813    async fn description(&self) -> Result<Vc<OptionStyledString>> {
814        Ok(Vc::cell(Some(
815            StyledString::Text(
816                self.error
817                    .print(
818                        *self.assets_for_source_mapping,
819                        self.assets_root.clone(),
820                        self.project_dir.clone(),
821                        FormattingMode::Plain,
822                    )
823                    .await?
824                    .into(),
825            )
826            .resolved_cell(),
827        )))
828    }
829
830    #[turbo_tasks::function]
831    fn source(&self) -> Vc<OptionIssueSource> {
832        Vc::cell(Some(self.source))
833    }
834}
835
836#[turbo_tasks::value(shared)]
837pub struct EvaluateErrorLoggingIssue {
838    pub source: IssueSource,
839    pub severity: IssueSeverity,
840    #[turbo_tasks(trace_ignore)]
841    pub logging: Vec<LogInfo>,
842    pub assets_for_source_mapping: ResolvedVc<AssetsForSourceMapping>,
843    pub assets_root: FileSystemPath,
844    pub project_dir: FileSystemPath,
845}
846
847#[turbo_tasks::value_impl]
848impl Issue for EvaluateErrorLoggingIssue {
849    #[turbo_tasks::function]
850    fn file_path(&self) -> Vc<FileSystemPath> {
851        self.source.file_path()
852    }
853
854    #[turbo_tasks::function]
855    fn stage(&self) -> Vc<IssueStage> {
856        IssueStage::Transform.cell()
857    }
858
859    fn severity(&self) -> IssueSeverity {
860        self.severity
861    }
862
863    #[turbo_tasks::function]
864    fn title(&self) -> Vc<StyledString> {
865        StyledString::Text(rcstr!("Error logging while running loader")).cell()
866    }
867
868    #[turbo_tasks::function]
869    fn description(&self) -> Vc<OptionStyledString> {
870        fn fmt_args(prefix: String, args: &[JsonValue]) -> String {
871            let mut iter = args.iter();
872            let Some(first) = iter.next() else {
873                return "".to_string();
874            };
875            let mut result = prefix;
876            if let JsonValue::String(s) = first {
877                result.push_str(s);
878            } else {
879                result.push_str(&first.to_string());
880            }
881            for arg in iter {
882                result.push(' ');
883                result.push_str(&arg.to_string());
884            }
885            result
886        }
887        let lines = self
888            .logging
889            .iter()
890            .map(|log| match log.log_type {
891                LogType::Error => {
892                    StyledString::Strong(fmt_args("<e> ".to_string(), &log.args).into())
893                }
894                LogType::Warn => StyledString::Text(fmt_args("<w> ".to_string(), &log.args).into()),
895                LogType::Info => StyledString::Text(fmt_args("<i> ".to_string(), &log.args).into()),
896                LogType::Log => StyledString::Text(fmt_args("<l> ".to_string(), &log.args).into()),
897                LogType::Clear => StyledString::Strong(rcstr!("---")),
898                _ => {
899                    unimplemented!("{:?} is not implemented", log.log_type)
900                }
901            })
902            .collect::<Vec<_>>();
903        Vc::cell(Some(StyledString::Stack(lines).resolved_cell()))
904    }
905
906    #[turbo_tasks::function]
907    fn source(&self) -> Vc<OptionIssueSource> {
908        Vc::cell(Some(self.source))
909    }
910}