turbopack/module_options/
transition_rule.rs

1use anyhow::Result;
2use bincode::{Decode, Encode};
3use turbo_tasks::{NonLocalValue, ResolvedVc, trace::TraceRawVcs};
4use turbo_tasks_fs::FileSystemPath;
5use turbopack_core::{reference_type::ReferenceType, source::Source};
6
7use crate::{
8    module_options::{RuleCondition, match_mode::MatchMode},
9    transition::Transition,
10};
11
12#[derive(Debug, Clone, TraceRawVcs, PartialEq, Eq, NonLocalValue, Encode, Decode)]
13pub struct TransitionRule {
14    condition: RuleCondition,
15    transition: ResolvedVc<Box<dyn Transition>>,
16    match_mode: MatchMode,
17}
18
19impl TransitionRule {
20    /// Creates a new transition rule. Will not match internal references.
21    pub fn new(condition: RuleCondition, transition: ResolvedVc<Box<dyn Transition>>) -> Self {
22        TransitionRule {
23            condition,
24            transition,
25            match_mode: MatchMode::NonInternal,
26        }
27    }
28
29    /// Creates a new transition rule. Will only match internal references.
30    pub fn new_internal(
31        condition: RuleCondition,
32        transition: ResolvedVc<Box<dyn Transition>>,
33    ) -> Self {
34        TransitionRule {
35            condition,
36            transition,
37            match_mode: MatchMode::Internal,
38        }
39    }
40
41    /// Creates a new transition rule. Will match all references.
42    pub fn new_all(condition: RuleCondition, transition: ResolvedVc<Box<dyn Transition>>) -> Self {
43        TransitionRule {
44            condition,
45            transition,
46            match_mode: MatchMode::All,
47        }
48    }
49
50    pub fn transition(&self) -> ResolvedVc<Box<dyn Transition>> {
51        self.transition
52    }
53
54    pub async fn matches(
55        &self,
56        source: ResolvedVc<Box<dyn Source>>,
57        path: &FileSystemPath,
58        reference_type: &ReferenceType,
59    ) -> Result<bool> {
60        Ok(self.match_mode.matches(reference_type)
61            && self.condition.matches(source, path, reference_type).await?)
62    }
63}