Skip to main content

livewire/
assets.rs

1//! The browser runtime an application serves: its bundle bytes, the tags that load them, and the
2//! inline CSS they need.
3
4use laravel::embed::Embedded;
5use laravel::view::Html;
6
7use crate::config::LivewireConfig;
8use crate::frontend::Endpoints;
9
10/// The built browser runtime, compiled into the binary so an application never runs Node.
11static DIST: Embedded = laravel::embed!("dist");
12
13/// The placeholder the style sheet carries until the configured progress-bar colour replaces it.
14const PROGRESS_BAR_COLOR: &str = "__LIVEWIRE_PROGRESS_BAR_COLOR__";
15
16/// The inline CSS `@livewireStyles` emits, as upstream writes it before minification.
17const STYLES: &str = r#"<!-- Livewire Styles -->
18<style >
19    [wire\:loading][wire\:loading], [wire\:loading\.delay][wire\:loading\.delay], [wire\:loading\.list-item][wire\:loading\.list-item], [wire\:loading\.inline-block][wire\:loading\.inline-block], [wire\:loading\.inline][wire\:loading\.inline], [wire\:loading\.block][wire\:loading\.block], [wire\:loading\.flex][wire\:loading\.flex], [wire\:loading\.table][wire\:loading\.table], [wire\:loading\.grid][wire\:loading\.grid], [wire\:loading\.inline-flex][wire\:loading\.inline-flex] {
20        display: none;
21    }
22
23    [wire\:loading\.delay\.none][wire\:loading\.delay\.none], [wire\:loading\.delay\.shortest][wire\:loading\.delay\.shortest], [wire\:loading\.delay\.shorter][wire\:loading\.delay\.shorter], [wire\:loading\.delay\.short][wire\:loading\.delay\.short], [wire\:loading\.delay\.default][wire\:loading\.delay\.default], [wire\:loading\.delay\.long][wire\:loading\.delay\.long], [wire\:loading\.delay\.longer][wire\:loading\.delay\.longer], [wire\:loading\.delay\.longest][wire\:loading\.delay\.longest] {
24        display: none;
25    }
26
27    [wire\:offline][wire\:offline] {
28        display: none;
29    }
30
31    [wire\:dirty]:not(textarea):not(input):not(select) {
32        display: none;
33    }
34
35    :root {
36        --livewire-progress-bar-color: __LIVEWIRE_PROGRESS_BAR_COLOR__;
37    }
38
39    [x-cloak="x-cloak"],
40    [x-cloak=""] {
41        display: none !important;
42    }
43
44    [wire\:cloak="wire:cloak"],
45    [wire\:cloak=""] {
46        display: none !important;
47    }
48
49    dialog#livewire-error::backdrop {
50        background-color: rgba(0, 0, 0, .6);
51    }
52</style>"#;
53
54/// The browser runtime an application serves: its bundle bytes, the tags that load them, and the
55/// inline CSS they need.
56#[derive(Debug, Clone)]
57pub struct FrontendAssets {
58    /// The frontend-related configuration.
59    config: LivewireConfig,
60    /// The paths the bundles are served under.
61    endpoints: Endpoints,
62}
63
64impl FrontendAssets {
65    /// The assets an application configured and the endpoints its routes registered.
66    #[must_use]
67    pub fn new(config: &LivewireConfig, endpoints: Endpoints) -> Self {
68        Self {
69            config: config.clone(),
70            endpoints,
71        }
72    }
73
74    /// The `@livewireStyles` markup: the exact inline `<style>` from upstream `styles()`.
75    pub fn styles(&self) -> Html {
76        let color = escape_html(&self.config.navigate.progress_bar_color);
77
78        Html::raw(minify(&STYLES.replace(PROGRESS_BAR_COLOR, &color)))
79    }
80
81    /// The `@livewireScriptConfig` body: `window.livewireScriptConfig = {…};`
82    #[must_use]
83    pub fn script_config(&self, csrf: &str, nonce: Option<&str>) -> String {
84        let mut entries = serde_json::Map::new();
85        entries.insert("csrf".to_owned(), serde_json::Value::String(csrf.to_owned()));
86        entries.insert("uri".to_owned(), serde_json::Value::String(self.update_uri()));
87        entries.insert(
88            "moduleUrl".to_owned(),
89            serde_json::Value::String(self.endpoints.prefix().to_owned()),
90        );
91        entries.insert(
92            "progressBar".to_owned(),
93            serde_json::Value::String(self.progress_bar_attribute().to_owned()),
94        );
95        if let Some(nonce) = nonce {
96            entries.insert("nonce".to_owned(), serde_json::Value::String(nonce.to_owned()));
97        }
98
99        let config = serde_json::Value::Object(entries);
100        let nonce = nonce
101            .map(|nonce| format!(" nonce=\"{}\"", escape_html(nonce)))
102            .unwrap_or_default();
103
104        format!("<script{nonce} data-navigate-once=\"true\">window.livewireScriptConfig = {config};</script>")
105    }
106
107    /// The `@livewireScripts` markup: the `<script>` tags, with `data-csrf`,
108    /// `data-update-uri`, and `data-module-url`.
109    pub fn scripts(&self, csrf: &str, nonce: Option<&str>, extra_attributes: &[(&str, &str)]) -> Html {
110        let mut tag = String::with_capacity(256);
111        tag.push_str("<script src=\"");
112        tag.push_str(&escape_html(&self.script_url()));
113        tag.push('"');
114
115        if let Some(nonce) = nonce {
116            tag.push_str(" nonce=\"");
117            tag.push_str(&escape_html(nonce));
118            tag.push('"');
119        }
120
121        let progress_bar = self.progress_bar_attribute();
122        if !progress_bar.is_empty() {
123            tag.push(' ');
124            tag.push_str(progress_bar);
125        }
126
127        tag.push_str(" data-csrf=\"");
128        tag.push_str(&escape_html(csrf));
129        tag.push_str("\" data-module-url=\"");
130        tag.push_str(&escape_html(self.endpoints.prefix()));
131        tag.push_str("\" data-update-uri=\"");
132        tag.push_str(&escape_html(&self.update_uri()));
133        tag.push('"');
134
135        for (name, value) in extra_attributes {
136            tag.push(' ');
137            tag.push_str(name);
138            tag.push_str("=\"");
139            tag.push_str(&escape_html(value));
140            tag.push('"');
141        }
142
143        tag.push_str("></script>");
144
145        Html::raw(tag)
146    }
147
148    /// The embedded bundle or source map by file name, such as `livewire.min.js`.
149    #[must_use]
150    pub fn bundle(&self, file: &str) -> Option<&'static [u8]> {
151        DIST.get(file)
152    }
153
154    /// The asset id the query string carries, from `LIVEWIRE_ASSET_ID`.
155    #[must_use]
156    pub fn asset_id(&self) -> &'static str {
157        env!("LIVEWIRE_ASSET_ID")
158    }
159
160    /// The complete URL of the script tag, with its cache-busting query string.
161    fn script_url(&self) -> String {
162        let mut url = match &self.config.asset_url {
163            Some(asset_url) => asset_url.trim_end_matches('/').to_owned(),
164            None => self.endpoints.script(true, self.config.csp_safe),
165        };
166
167        // A relative URL needs a leading slash; a URL with a scheme must keep its shape.
168        if !url.contains("://") && !url.starts_with('/') {
169            url.insert(0, '/');
170        }
171
172        let mut id = self.asset_id().to_owned();
173        if self.config.csp_safe {
174            id.push_str("-csp");
175        }
176
177        url.push(if url.contains('?') { '&' } else { '?' });
178        url.push_str("id=");
179        url.push_str(&id);
180
181        url
182    }
183
184    /// The path or URL that receives component updates.
185    fn update_uri(&self) -> String {
186        self.config
187            .update_uri
188            .clone()
189            .unwrap_or_else(|| self.endpoints.update())
190    }
191
192    /// The script tag attribute that suppresses the progress bar, or an empty string.
193    fn progress_bar_attribute(&self) -> &'static str {
194        if self.config.navigate.show_progress_bar {
195            ""
196        } else {
197            "data-no-progress-bar"
198        }
199    }
200}
201
202/// Escape text for use in markup, as upstream's `escapeStringForHtml` does.
203fn escape_html(text: &str) -> String {
204    let mut escaped = String::with_capacity(text.len());
205
206    for character in text.chars() {
207        match character {
208            '&' => escaped.push_str("&amp;"),
209            '<' => escaped.push_str("&lt;"),
210            '>' => escaped.push_str("&gt;"),
211            '"' => escaped.push_str("&quot;"),
212            '\'' => escaped.push_str("&#039;"),
213            _ => escaped.push(character),
214        }
215    }
216
217    escaped
218}
219
220/// Remove tabs, vertical tabs, and runs of two or more whitespace characters, as upstream's
221/// `minify()` does.
222fn minify(subject: &str) -> String {
223    let mut minified = String::with_capacity(subject.len());
224    let mut whitespace = String::new();
225
226    for character in subject.chars() {
227        if character.is_whitespace() {
228            whitespace.push(character);
229            continue;
230        }
231
232        drain_whitespace(&mut whitespace, &mut minified);
233        minified.push(character);
234    }
235
236    drain_whitespace(&mut whitespace, &mut minified);
237
238    minified
239}
240
241/// Keep a lone whitespace character that upstream keeps, and drop the rest.
242fn drain_whitespace(whitespace: &mut String, minified: &mut String) {
243    let mut characters = whitespace.chars();
244    if let (Some(only), None) = (characters.next(), characters.next())
245        && only != '\t'
246        && only != '\u{000B}'
247    {
248        minified.push(only);
249    }
250
251    whitespace.clear();
252}
253
254#[cfg(test)]
255mod tests {
256    use super::{FrontendAssets, minify};
257    use crate::config::LivewireConfig;
258    use crate::frontend::Endpoints;
259
260    fn assets() -> FrontendAssets {
261        FrontendAssets::new(&LivewireConfig::default(), Endpoints::new("base64:test-key"))
262    }
263
264    #[test]
265    fn styles_are_the_upstream_minified_style_sheet() {
266        let styles = assets().styles();
267        let markup = styles.as_str();
268
269        assert!(markup.starts_with("<!-- Livewire Styles -->\n<style >"));
270        assert!(markup.ends_with("</style>"));
271        assert!(markup.contains("--livewire-progress-bar-color: #2299dd;"));
272        assert!(markup.contains("[wire\\:loading][wire\\:loading]"));
273        assert!(markup.contains("[wire\\:dirty]:not(textarea):not(input):not(select) {display: none;}"));
274        assert!(markup.contains("dialog#livewire-error::backdrop {background-color: rgba(0, 0, 0, .6);}"));
275        assert!(!markup.contains('\t'));
276        assert!(!markup.contains("  "));
277        assert!(!markup.contains('\u{000B}'));
278    }
279
280    #[test]
281    fn styles_use_the_configured_progress_bar_colour() {
282        let mut config = LivewireConfig::default();
283        config.navigate.progress_bar_color = "#ff0000".to_owned();
284
285        let styles = FrontendAssets::new(&config, Endpoints::new("base64:test-key")).styles();
286
287        assert!(styles.as_str().contains("--livewire-progress-bar-color: #ff0000;"));
288        assert!(!styles.as_str().contains("#2299dd"));
289    }
290
291    #[test]
292    fn minify_keeps_lone_whitespace_and_drops_runs() {
293        assert_eq!(minify("a b"), "a b");
294        assert_eq!(minify("a\nb"), "a\nb");
295        assert_eq!(minify("a\n    b"), "ab");
296        assert_eq!(minify("a\t b"), "ab");
297        assert_eq!(minify("a   b"), "ab");
298        assert_eq!(minify("a\u{000B}b"), "ab");
299    }
300
301    #[test]
302    fn scripts_load_the_minified_bundle_with_the_asset_id() {
303        let assets = assets();
304        let markup = assets.scripts("csrf-token", None, &[]);
305        let expected = format!(
306            "<script src=\"{}/livewire.min.js?id={}\"",
307            assets_id::prefix(),
308            assets.asset_id()
309        );
310
311        assert!(markup.as_str().starts_with(&expected), "{markup}");
312        assert!(markup.as_str().contains("data-csrf=\"csrf-token\""));
313        assert!(
314            markup
315                .as_str()
316                .contains(&format!("data-module-url=\"{}\"", assets_id::prefix()))
317        );
318        assert!(
319            markup
320                .as_str()
321                .contains(&format!("data-update-uri=\"{}/update\"", assets_id::prefix()))
322        );
323        assert!(markup.as_str().ends_with("></script>"));
324    }
325
326    #[test]
327    fn a_csp_build_loads_the_csp_bundle_and_busts_its_own_cache() {
328        let config = LivewireConfig {
329            csp_safe: true,
330            ..LivewireConfig::default()
331        };
332        let assets = FrontendAssets::new(&config, Endpoints::new("base64:test-key"));
333
334        let markup = assets.scripts("csrf-token", Some("nonce-value"), &[]);
335
336        assert!(markup.as_str().contains("/livewire.csp.min.js?id="));
337        assert!(markup.as_str().contains(&format!("{}-csp\"", assets.asset_id())));
338        assert!(!markup.as_str().contains("/livewire.min.js?id="));
339        assert!(markup.as_str().contains("nonce=\"nonce-value\""));
340    }
341
342    #[test]
343    fn asset_url_replaces_the_endpoint_url() {
344        let config = LivewireConfig {
345            asset_url: Some("https://cdn.example.com/livewire.js".to_owned()),
346            ..LivewireConfig::default()
347        };
348        let assets = FrontendAssets::new(&config, Endpoints::new("base64:test-key"));
349
350        let markup = assets.scripts("csrf-token", None, &[]);
351
352        assert!(markup.as_str().starts_with(&format!(
353            "<script src=\"https://cdn.example.com/livewire.js?id={}\"",
354            assets.asset_id()
355        )));
356    }
357
358    #[test]
359    fn a_relative_asset_url_gains_a_leading_slash() {
360        let config = LivewireConfig {
361            asset_url: Some("vendor/livewire.js".to_owned()),
362            ..LivewireConfig::default()
363        };
364        let assets = FrontendAssets::new(&config, Endpoints::new("base64:test-key"));
365
366        assert!(
367            assets
368                .scripts("csrf", None, &[])
369                .as_str()
370                .contains("src=\"/vendor/livewire.js?id=")
371        );
372    }
373
374    #[test]
375    fn an_asset_url_with_a_query_uses_an_ampersand() {
376        let config = LivewireConfig {
377            asset_url: Some("https://cdn.example.com/livewire.js?token=abc".to_owned()),
378            ..LivewireConfig::default()
379        };
380        let assets = FrontendAssets::new(&config, Endpoints::new("base64:test-key"));
381
382        assert!(
383            assets
384                .scripts("csrf", None, &[])
385                .as_str()
386                .contains("?token=abc&amp;id=")
387        );
388    }
389
390    #[test]
391    fn script_config_carries_every_value_the_runtime_reads() {
392        let assets = assets();
393        let config = assets.script_config("csrf-token", Some("nonce-value"));
394
395        assert!(config.starts_with("<script nonce=\"nonce-value\" data-navigate-once=\"true\">"));
396        assert!(config.contains("window.livewireScriptConfig = {"));
397        assert!(config.contains("\"csrf\":\"csrf-token\""));
398        assert!(config.contains(&format!("\"uri\":\"/livewire-{}/update\"", assets_id::hash())));
399        assert!(config.contains(&format!("\"moduleUrl\":\"/livewire-{}\"", assets_id::hash())));
400        assert!(config.contains("\"progressBar\":\"\""));
401        assert!(config.contains("\"nonce\":\"nonce-value\""));
402        assert!(config.ends_with(";</script>"));
403    }
404
405    #[test]
406    fn script_config_omits_a_nonce_that_is_not_given() {
407        let config = assets().script_config("csrf-token", None);
408
409        assert!(!config.contains("nonce="));
410        assert!(!config.contains("\"nonce\""));
411    }
412
413    #[test]
414    fn script_config_uses_the_configured_update_uri() {
415        let livewire = LivewireConfig {
416            update_uri: Some("/custom/update".to_owned()),
417            ..LivewireConfig::default()
418        };
419        let assets = FrontendAssets::new(&livewire, Endpoints::new("base64:test-key"));
420
421        assert!(
422            assets
423                .script_config("csrf", None)
424                .contains("\"uri\":\"/custom/update\"")
425        );
426        assert!(
427            assets
428                .scripts("csrf", None, &[])
429                .as_str()
430                .contains("data-update-uri=\"/custom/update\"")
431        );
432    }
433
434    #[test]
435    fn a_hidden_progress_bar_is_marked_in_both_tags() {
436        let mut config = LivewireConfig::default();
437        config.navigate.show_progress_bar = false;
438        let assets = FrontendAssets::new(&config, Endpoints::new("base64:test-key"));
439
440        assert!(
441            assets
442                .scripts("csrf", None, &[])
443                .as_str()
444                .contains(" data-no-progress-bar ")
445        );
446        assert!(
447            assets
448                .script_config("csrf", None)
449                .contains("\"progressBar\":\"data-no-progress-bar\"")
450        );
451    }
452
453    #[test]
454    fn extra_script_attributes_are_escaped() {
455        let markup = assets().scripts("csrf", None, &[("data-loaded", "a&b")]);
456
457        assert!(markup.as_str().contains(" data-loaded=\"a&amp;b\""));
458    }
459
460    #[test]
461    fn every_markup_value_is_escaped() {
462        let markup = assets().scripts("<csrf>", Some("\"nonce\""), &[]);
463
464        assert!(markup.as_str().contains("data-csrf=\"&lt;csrf&gt;\""));
465        assert!(markup.as_str().contains("nonce=\"&quot;nonce&quot;\""));
466    }
467
468    #[test]
469    fn bundles_are_the_embedded_files() {
470        let assets = assets();
471
472        assert!(
473            !assets
474                .bundle("livewire.min.js")
475                .expect("livewire.min.js is embedded")
476                .is_empty()
477        );
478        assert!(assets.bundle("livewire.csp.min.js").is_some());
479        assert!(assets.bundle("../secret").is_none());
480        assert!(assets.bundle("missing.js").is_none());
481    }
482
483    /// Helpers that read the endpoint paths out of an asset set.
484    mod assets_id {
485        use crate::frontend::Endpoints;
486
487        pub fn hash() -> String {
488            let prefix = Endpoints::new("base64:test-key");
489            prefix.prefix().trim_start_matches("/livewire-").to_owned()
490        }
491
492        pub fn prefix() -> String {
493            Endpoints::new("base64:test-key").prefix().to_owned()
494        }
495    }
496}