Skip to main content

livewire/
registry.rs

1//! The components, synthesizers, and template hooks an application registers once, frozen into one
2//! shared value before the application boots.
3//!
4//! Component definitions live in the application, never in a global: the registry is built from the
5//! application's provider, shared through the container, and handed to the engine and the update
6//! handler. Two applications in one test process therefore keep their own components.
7
8use std::collections::{BTreeMap, BTreeSet};
9use std::fmt;
10use std::sync::Arc;
11
12use laravel::view::minijinja::Environment;
13
14use crate::component::{Component, WireField};
15use crate::config::LivewireConfig;
16use crate::synthesizers::Synth;
17
18/// Why an application's component registration was rejected.
19#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
20pub enum RegistryError {
21    /// Two components were registered under one name.
22    #[error("two components are registered as [{name}]: a component name must be unique")]
23    DuplicateComponent {
24        /// The name both components claimed.
25        name: String,
26    },
27    /// Two synthesizers were registered under one key.
28    #[error("two synthesizers are registered with the key [{key}]: a synthesizer key must be unique")]
29    DuplicateSynth {
30        /// The key both synthesizers claimed.
31        key: String,
32    },
33    /// A component name is empty, or carries characters a name cannot.
34    #[error("the component name [{name}] is not valid: use letters, digits, dashes, dots, slashes, or `::`")]
35    InvalidName {
36        /// The rejected name.
37        name: String,
38    },
39}
40
41/// The definition of one registered component.
42struct Registration {
43    /// Builds a default instance, which the server then hydrates or mounts.
44    factory: Box<dyn Fn() -> Box<dyn Component> + Send + Sync>,
45    /// The component's wire-public fields, which the derive monomorphized for its type.
46    fields: fn() -> &'static [WireField],
47    /// The Rust type, for diagnostics.
48    type_name: &'static str,
49}
50
51impl fmt::Debug for Registration {
52    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
53        formatter
54            .debug_struct("Registration")
55            .field("type_name", &self.type_name)
56            .finish_non_exhaustive()
57    }
58}
59
60/// A callback that configures the `.livewire` engine's environment.
61pub type TemplateConfigurator = Arc<dyn Fn(&mut Environment<'static>) + Send + Sync>;
62
63/// The components and template hooks one application registered.
64pub struct ComponentRegistry {
65    components: BTreeMap<String, Registration>,
66    synthesizers: BTreeSet<&'static str>,
67    templates: Vec<TemplateConfigurator>,
68    config: LivewireConfig,
69    synthesize_placeholder: bool,
70    hooks: crate::hooks::Hooks,
71    persistent: Vec<std::sync::Arc<dyn crate::persistent::PersistentMiddleware>>,
72}
73
74impl fmt::Debug for ComponentRegistry {
75    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
76        formatter
77            .debug_struct("ComponentRegistry")
78            .field("components", &self.components)
79            .field("synthesizers", &self.synthesizers)
80            .field("templates", &self.templates.len())
81            .field("config", &self.config)
82            .field("hooks", &self.hooks)
83            .field("persistent", &self.persistent.len())
84            .finish_non_exhaustive()
85    }
86}
87
88impl ComponentRegistry {
89    /// An empty registry for an application configured with `config`.
90    #[must_use]
91    pub fn new(config: LivewireConfig) -> Self {
92        let mut registry = Self {
93            components: BTreeMap::new(),
94            synthesizers: BTreeSet::new(),
95            templates: Vec::new(),
96            config,
97            synthesize_placeholder: true,
98            hooks: crate::hooks::Hooks::default(),
99            persistent: Vec::new(),
100        };
101
102        // The adapters every application has, whether or not it registers its own.
103        registry.synthesizers.insert(crate::synthesizers::Arr::KEY);
104        registry.synthesizers.insert(crate::synthesizers::Std::KEY);
105        registry.synthesizers.insert(crate::synthesizers::Str::KEY);
106        registry.synthesizers.insert(crate::synthesizers::Int::KEY);
107        registry.synthesizers.insert(crate::synthesizers::Float::KEY);
108
109        registry
110    }
111
112    /// Registers a guard that runs on every update of a component mounted by a page.
113    ///
114    /// The guard sees the update's request and the page the component was mounted from, so a route
115    /// guard the page ran runs again when the browser drives the component.
116    pub fn persistent(&mut self, guard: impl crate::persistent::PersistentMiddleware + 'static) -> &mut Self {
117        self.persistent.push(std::sync::Arc::new(guard));
118
119        self
120    }
121
122    /// The guards an update runs, in registration order.
123    pub(crate) fn persistent_guards(&self) -> &[std::sync::Arc<dyn crate::persistent::PersistentMiddleware>] {
124        &self.persistent
125    }
126
127    /// Registers a lifecycle hook, which the pipeline runs at each step.
128    ///
129    /// Hooks run in registration order, on every request, for every component.
130    pub fn hook(&mut self, callback: impl Fn(&crate::hooks::HookEvent<'_>) + Send + Sync + 'static) -> &mut Self {
131        self.hooks.push(std::sync::Arc::new(callback));
132
133        self
134    }
135
136    /// Runs the registered hooks with `event`.
137    pub(crate) fn run_hooks(&self, event: &crate::hooks::HookEvent<'_>) {
138        self.hooks.run(event);
139    }
140
141    /// Registers a component under `name`.
142    ///
143    /// # Errors
144    ///
145    /// Fails when the name is invalid, or when another component already has it.
146    pub fn register<C: Component + Default>(&mut self, name: impl Into<String>) -> Result<&mut Self, RegistryError> {
147        let name = normalize_name(&name.into())?;
148
149        self.insert(
150            name,
151            Registration {
152                factory: Box::new(|| Box::new(C::default()) as Box<dyn Component>),
153                fields: C::wire_fields,
154                type_name: std::any::type_name::<C>(),
155            },
156        )?;
157
158        Ok(self)
159    }
160
161    /// Registers a component that is built by `factory` rather than by `Default`.
162    ///
163    /// # Errors
164    ///
165    /// Fails when the name is invalid, or when another component already has it.
166    pub fn register_with<C: Component + Default>(
167        &mut self,
168        name: impl Into<String>,
169        factory: impl Fn() -> C + Send + Sync + 'static,
170    ) -> Result<&mut Self, RegistryError> {
171        let name = normalize_name(&name.into())?;
172
173        self.insert(
174            name,
175            Registration {
176                factory: Box::new(move || Box::new(factory()) as Box<dyn Component>),
177                fields: C::wire_fields,
178                type_name: std::any::type_name::<C>(),
179            },
180        )?;
181
182        Ok(self)
183    }
184
185    fn insert(&mut self, name: String, registration: Registration) -> Result<(), RegistryError> {
186        if self.components.contains_key(&name) {
187            return Err(RegistryError::DuplicateComponent { name });
188        }
189
190        self.components.insert(name, registration);
191
192        Ok(())
193    }
194
195    /// Registers a synthesizer, so that a snapshot may name its key.
196    ///
197    /// # Errors
198    ///
199    /// Fails when another synthesizer already has the key.
200    pub fn register_synth<S: Synth>(&mut self) -> Result<&mut Self, RegistryError> {
201        self.register_synth_key(S::KEY)
202    }
203
204    /// Registers a synthesizer key that a field already names.
205    ///
206    /// # Errors
207    ///
208    /// Fails when another synthesizer already has the key.
209    pub fn register_synth_key(&mut self, key: &'static str) -> Result<&mut Self, RegistryError> {
210        if !self.synthesizers.insert(key) {
211            return Err(RegistryError::DuplicateSynth { key: key.to_owned() });
212        }
213
214        Ok(self)
215    }
216
217    /// Adds a callback that configures the `.livewire` engine, such as filters of the application's
218    /// own.
219    pub fn templates(&mut self, configure: impl Fn(&mut Environment<'static>) + Send + Sync + 'static) -> &mut Self {
220        self.templates.push(Arc::new(configure));
221        self
222    }
223
224    /// Whether a snapshot may name `key` as a synthesizer.
225    #[must_use]
226    pub fn has_synth(&self, key: &str) -> bool {
227        self.synthesizers.contains(key)
228    }
229
230    /// The synthesizer keys the application registered.
231    pub fn synth_keys(&self) -> impl Iterator<Item = &'static str> + '_ {
232        self.synthesizers.iter().copied()
233    }
234
235    /// A new instance of the component registered as `name`.
236    #[must_use]
237    pub fn instantiate(&self, name: &str) -> Option<Box<dyn Component>> {
238        self.components.get(name).map(|registration| (registration.factory)())
239    }
240
241    /// The wire-public fields of the component registered as `name`.
242    #[must_use]
243    pub fn wire_fields(&self, name: &str) -> Option<&'static [WireField]> {
244        self.components.get(name).map(|registration| (registration.fields)())
245    }
246
247    /// The names of the registered components, in order.
248    pub fn names(&self) -> impl ExactSizeIterator<Item = &str> {
249        self.components.keys().map(String::as_str)
250    }
251
252    /// Whether a component is registered.
253    #[must_use]
254    pub fn contains(&self, name: &str) -> bool {
255        self.components.contains_key(name)
256    }
257
258    /// The callbacks that configure the engine.
259    #[must_use]
260    pub fn template_configurators(&self) -> &[TemplateConfigurator] {
261        &self.templates
262    }
263
264    /// The configuration the application froze the registry with.
265    #[must_use]
266    pub fn config(&self) -> &LivewireConfig {
267        &self.config
268    }
269
270    /// Whether the built-in placeholder renders a lazy component before it loads.
271    #[must_use]
272    pub fn synthesize_placeholder(&self) -> bool {
273        self.synthesize_placeholder
274    }
275
276    /// Turns the built-in lazy placeholder off, for an application that renders its own.
277    pub fn without_placeholder(&mut self) -> &mut Self {
278        self.synthesize_placeholder = false;
279        self
280    }
281}
282
283/// Normalizes a component name: `/` becomes `.`, a leading `⚡` is removed, and `::` namespaces are
284/// kept.
285///
286/// # Errors
287///
288/// Fails when the name is empty, or when it holds a character a name cannot, which keeps a crafted
289/// name from escaping the registry or a view path.
290pub fn normalize_name(name: &str) -> Result<String, RegistryError> {
291    let name: String = name.trim().chars().filter(|character| *character != '⚡').collect();
292    let name = name.trim_start_matches('/').replace('/', ".");
293
294    let invalid = name.is_empty()
295        || !name
296            .chars()
297            .all(|character| character.is_alphanumeric() || matches!(character, '-' | '_' | '.' | ':' | '⚡'))
298        || name.contains("..")
299        || name.starts_with('.')
300        || name.ends_with('.');
301
302    if invalid {
303        return Err(RegistryError::InvalidName { name });
304    }
305
306    Ok(name)
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312    use crate::component::ComponentContext;
313    use crate::{LivewireComponent, component};
314
315    #[derive(Default, LivewireComponent)]
316    #[livewire(inline = "<div></div>")]
317    struct Counter {
318        count: i32,
319    }
320
321    #[component]
322    impl Counter {
323        pub fn increment(&mut self) {
324            self.count += 1;
325        }
326    }
327
328    #[derive(Default, LivewireComponent)]
329    #[livewire(inline = "<div></div>")]
330    struct Other {
331        count: i32,
332    }
333
334    #[component]
335    impl Other {}
336
337    #[test]
338    fn a_registered_component_can_be_instantiated_and_updated() {
339        let mut registry = ComponentRegistry::new(LivewireConfig::default());
340        registry.register::<Counter>("counter").expect("registers");
341
342        assert!(registry.contains("counter"));
343        assert_eq!(registry.names().collect::<Vec<_>>(), ["counter"]);
344
345        let mut component = registry.instantiate("counter").expect("a component");
346        futures_util::FutureExt::now_or_never(component.call(
347            crate::component::Call {
348                method: "increment".to_owned(),
349                params: crate::component::Params::default(),
350                metadata: serde_json::Map::new(),
351            },
352            &mut ComponentContext::mounting("id", "counter", None),
353        ))
354        .expect("ready")
355        .expect("runs");
356    }
357
358    #[test]
359    fn the_wire_fields_come_from_the_registered_type() {
360        let mut registry = ComponentRegistry::new(LivewireConfig::default());
361        registry.register::<Counter>("counter").expect("registers");
362
363        let fields = registry.wire_fields("counter").expect("fields");
364
365        assert_eq!(fields.iter().map(|field| field.name).collect::<Vec<_>>(), ["count"]);
366        assert!(registry.wire_fields("other").is_none());
367    }
368
369    #[test]
370    fn two_components_may_not_share_a_name() {
371        let mut registry = ComponentRegistry::new(LivewireConfig::default());
372        registry.register::<Counter>("counter").expect("registers");
373
374        let error = registry.register::<Other>("counter").expect_err("duplicate");
375
376        assert_eq!(
377            error,
378            RegistryError::DuplicateComponent {
379                name: "counter".to_owned()
380            }
381        );
382    }
383
384    #[test]
385    fn a_name_is_normalized_before_it_is_checked() {
386        let mut registry = ComponentRegistry::new(LivewireConfig::default());
387
388        registry.register::<Counter>("/pages/⚡counter").expect("registers");
389
390        assert!(registry.contains("pages.counter"));
391        assert!(!registry.contains("/pages/⚡counter"));
392    }
393
394    #[test]
395    fn a_name_that_would_escape_its_path_is_rejected() {
396        for name in ["", "..", "a..b", "pages/../../etc/passwd", ".hidden"] {
397            assert!(normalize_name(name).is_err(), "{name}");
398        }
399    }
400
401    #[test]
402    fn a_namespace_separator_is_kept() {
403        assert_eq!(normalize_name("pages::counter").expect("valid"), "pages::counter");
404    }
405
406    #[test]
407    fn every_adapter_is_registered_by_default() {
408        let registry = ComponentRegistry::new(LivewireConfig::default());
409
410        for key in ["arr", "std", "str", "int", "float"] {
411            assert!(registry.has_synth(key), "{key}");
412        }
413        assert!(!registry.has_synth("mdl"));
414    }
415
416    #[test]
417    fn a_synthesizer_key_may_not_be_registered_twice() {
418        let mut registry = ComponentRegistry::new(LivewireConfig::default());
419
420        let error = registry
421            .register_synth::<crate::synthesizers::Arr>()
422            .expect_err("duplicate");
423
424        assert_eq!(error, RegistryError::DuplicateSynth { key: "arr".to_owned() });
425    }
426}