Skip to main content

livewire/
provider.rs

1//! The service provider an application adds to use Livewire.
2//!
3//! The provider freezes the application's component registrations into one registry, shares it
4//! through the container, registers the `.livewire` engine, adds the endpoints, and injects the
5//! runtime into pages that rendered a component.
6
7use std::sync::{Arc, Mutex, OnceLock};
8
9use laravel::config::{Config, Env};
10use laravel::container::{Container, Registrar};
11use laravel::foundation::ServiceProvider;
12use laravel::http::{Middleware, Next};
13use laravel::http::{Request, Response};
14
15use crate::assets::FrontendAssets;
16use crate::config::LivewireConfig;
17use crate::context::LivewireRequest;
18use crate::engine::LivewireEngine;
19use crate::frontend::Endpoints;
20use crate::registry::ComponentRegistry;
21
22/// Registers an application's Livewire components.
23///
24/// ```ignore
25/// use livewire::LivewireServiceProvider;
26///
27/// let provider = LivewireServiceProvider::new(|components| {
28///     components.register::<Counter>("counter").expect("unique");
29/// });
30/// ```
31pub struct LivewireServiceProvider<F> {
32    configure: Mutex<Option<F>>,
33    registry: OnceLock<Arc<ComponentRegistry>>,
34}
35
36impl<F> LivewireServiceProvider<F> {
37    /// Creates the provider, which adds the components `configure` registers.
38    pub fn new(configure: F) -> Self {
39        Self {
40            configure: Mutex::new(Some(configure)),
41            registry: OnceLock::new(),
42        }
43    }
44
45    /// The registry the provider froze, once the application registered its services.
46    #[must_use]
47    pub fn registry(&self) -> Option<&Arc<ComponentRegistry>> {
48        self.registry.get()
49    }
50}
51
52impl<F> std::fmt::Debug for LivewireServiceProvider<F> {
53    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        formatter
55            .debug_struct("LivewireServiceProvider")
56            .field("registry", &self.registry.get().map(|registry| registry.names().len()))
57            .finish_non_exhaustive()
58    }
59}
60
61impl<F> ServiceProvider for LivewireServiceProvider<F>
62where
63    F: FnOnce(&mut ComponentRegistry) + Send + 'static,
64{
65    fn config(&self, config: &mut Config, env: &Env) {
66        config.discover(env!("CARGO_CRATE_NAME"), env);
67
68        if config.get::<LivewireConfig>().is_none() {
69            config.set(LivewireConfig::default());
70        }
71    }
72
73    fn register(&self, app: &mut Registrar) {
74        let mut registry = ComponentRegistry::new(LivewireConfig::of(app.config()).clone());
75
76        if let Some(configure) = self.configure.lock().ok().and_then(|mut slot| slot.take()) {
77            configure(&mut registry);
78        }
79
80        let registry = Arc::new(registry);
81        let endpoints = Endpoints::new(app.config().app.key.as_deref().unwrap_or("livewire"));
82        let assets = Arc::new(FrontendAssets::new(registry.config(), endpoints.clone()));
83
84        app.instance(Arc::clone(&registry));
85        app.instance(Arc::clone(&assets));
86
87        app.views()
88            .engine("livewire", LivewireEngine::new(Arc::clone(&registry)));
89
90        // An ordinary page renders components and puts the runtime on itself with the same
91        // functions a component view uses.
92        let page_registry = Arc::clone(&registry);
93        app.views().minijinja(move |environment| {
94            crate::engine::register_functions(environment, &page_registry);
95        });
96
97        crate::routes::register(app.routing(), endpoints, registry.config().upload_throttle());
98
99        app.commands().add::<crate::commands::MakeLivewire>();
100        app.commands().add::<crate::commands::LivewireMake>();
101        app.commands().add::<crate::commands::LivewireConfigCommand>();
102        app.commands().add::<crate::commands::ConfigureS3UploadCleanup>();
103        app.commands().add::<crate::commands::Layout>();
104        app.commands().add::<crate::commands::Convert>();
105        app.commands().add::<crate::commands::Publish>();
106        app.commands().add::<crate::commands::Stubs>();
107
108        app.middleware().append(RememberPage);
109
110        if registry.config().inject_assets {
111            app.middleware().append(InjectAssets {
112                assets: Arc::clone(&assets),
113                inject: true,
114            });
115        }
116
117        let _ = self.registry.set(registry);
118    }
119
120    async fn boot(&self, app: &Container) -> laravel::Result<()> {
121        use laravel_core::context::Internals as _;
122
123        let context = laravel_core::context::Context::current()
124            .ok_or_else(|| laravel::Error::msg("Livewire boots inside the application"))?;
125
126        // A missing or invalid key would let a browser forge a snapshot, so the application does
127        // not start without one.
128        context.encrypter().map_err(|error| {
129            laravel::Error::msg(format!(
130                "Livewire needs a valid application encryption key to sign snapshots: {error}"
131            ))
132        })?;
133
134        let registry = app.resolve::<Arc<ComponentRegistry>>().await?;
135
136        // Only the local disk exists in this port; a configured name that promises another one
137        // would silently store files in the wrong place.
138        if let Some(disk) = &registry.config().temporary_file_upload.disk
139            && disk != "local"
140        {
141            return Err(laravel::Error::msg(format!(
142                "Livewire stores temporary uploads on `{disk}`, but this port ships only the local disk: \
143                 set temporary_file_upload.disk to `local` or leave it unset"
144            )));
145        }
146
147        for location in &registry.config().component_locations {
148            let path = app.config().app.base_path.join(location);
149            if !path.exists() {
150                tracing::debug!(
151                    path = %path.display(),
152                    "the configured component location does not exist yet"
153                );
154            }
155        }
156
157        Ok(())
158    }
159}
160
161/// Remembers the page a request renders, so its components record where they were mounted.
162#[derive(Debug)]
163pub struct RememberPage;
164
165impl Middleware for RememberPage {
166    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
167        // The request is read apart and put back untouched: nothing here consumes the body, and a
168        // page render is what needs remembering.
169        let http = request.into_http();
170        let method = http.method().as_str().to_owned();
171        let (parts, body) = http.into_parts();
172        let request = Request::from_http(laravel::axum::http::Request::from_parts(parts, body));
173
174        // Every request that renders a page is remembered, whatever its method, so a page a form
175        // submission re-renders carries its route context too. The browser sends the Livewire
176        // header only to the update and upload endpoints, which render no page.
177        if request.header("x-livewire").is_none()
178            && let Some(livewire) = crate::context::LivewireRequest::current()
179        {
180            livewire.remember_page(request.path(), &method, &request.origin());
181        }
182
183        Ok(next.run(request).await)
184    }
185}
186
187/// Injects the runtime into pages that rendered a component, when the application asks for it.
188#[derive(Debug)]
189pub struct InjectAssets {
190    assets: Arc<FrontendAssets>,
191    inject: bool,
192}
193
194impl Middleware for InjectAssets {
195    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
196        let response = next.run(request).await;
197
198        if !self.inject {
199            return Ok(response);
200        }
201
202        if !LivewireRequest::current().is_some_and(|request| request.has_rendered()) {
203            return Ok(response);
204        }
205
206        let is_html = response
207            .headers()
208            .get("content-type")
209            .and_then(|value| value.to_str().ok())
210            .is_some_and(|value| value.contains("text/html"));
211
212        if !is_html {
213            return Ok(response);
214        }
215
216        use http_body_util::BodyExt as _;
217
218        let (parts, body) = response.into_http().into_parts();
219        let Ok(collected) = body.collect().await else {
220            return Ok(Response::new("").with_status(laravel::http::StatusCode::INTERNAL_SERVER_ERROR));
221        };
222
223        let html = String::from_utf8_lossy(&collected.to_bytes()).into_owned();
224        let csrf = crate::session::csrf_token().unwrap_or_default();
225        let nonce = laravel::view::csp_nonce();
226        let rendered = LivewireRequest::current();
227
228        let html = inject(&html, &self.assets, &csrf, nonce.as_deref(), rendered.as_deref());
229
230        Ok(Response::from_http(laravel::axum::http::Response::from_parts(
231            parts,
232            laravel::axum::body::Body::from(html),
233        )))
234    }
235}
236
237/// Puts the styles before `</head>` and the scripts before `</body>`, when both are there.
238fn inject(
239    html: &str,
240    assets: &FrontendAssets,
241    csrf: &str,
242    nonce: Option<&str>,
243    rendered: Option<&LivewireRequest>,
244) -> String {
245    let mut html = html.to_owned();
246
247    let styles_done = rendered.is_some_and(LivewireRequest::styles_rendered);
248    let scripts_done = rendered.is_some_and(LivewireRequest::scripts_rendered);
249
250    if !styles_done && let Some(index) = html.rfind("</head>") {
251        let styles = assets.styles().into_string();
252        html.insert_str(index, &styles);
253    }
254
255    if !scripts_done && let Some(index) = html.rfind("</body>") {
256        let scripts = assets.scripts(csrf, nonce, &[]).into_string();
257        html.insert_str(index, &scripts);
258    }
259
260    html
261}