ferro-inertia 0.2.87

Server-side Inertia.js adapter for Rust web frameworks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! Inertia response generation.

use crate::config::InertiaConfig;
use crate::manifest::resolve_assets;
use crate::request::InertiaRequest;
use crate::shared::InertiaShared;
use serde::Serialize;

/// Escape a string for safe insertion into a double-quoted HTML attribute or element text.
/// Covers the five characters that can break attribute/text context.
fn escape_html(value: &str) -> String {
    value
        .replace('&', "&")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#x27;")
}

/// Framework-agnostic HTTP response.
///
/// Convert this to your framework's response type.
#[derive(Debug, Clone)]
pub struct InertiaHttpResponse {
    /// HTTP status code
    pub status: u16,
    /// Response headers as (name, value) pairs
    pub headers: Vec<(String, String)>,
    /// Response body
    pub body: String,
    /// Content type
    pub content_type: &'static str,
}

impl InertiaHttpResponse {
    /// Create a JSON response with Inertia headers.
    pub fn json(body: impl Into<String>) -> Self {
        Self {
            status: 200,
            headers: vec![
                ("X-Inertia".to_string(), "true".to_string()),
                ("Vary".to_string(), "X-Inertia".to_string()),
            ],
            body: body.into(),
            content_type: "application/json",
        }
    }

    /// Create a raw JSON response without Inertia headers.
    ///
    /// Used for JSON fallback when a non-Inertia client requests JSON.
    pub fn raw_json(body: impl Into<String>) -> Self {
        Self {
            status: 200,
            headers: vec![],
            body: body.into(),
            content_type: "application/json",
        }
    }

    /// Create an HTML response.
    pub fn html(body: impl Into<String>) -> Self {
        Self {
            status: 200,
            headers: vec![("Vary".to_string(), "X-Inertia".to_string())],
            body: body.into(),
            content_type: "text/html; charset=utf-8",
        }
    }

    /// Create a 409 Conflict response for version mismatch.
    pub fn conflict(location: impl Into<String>) -> Self {
        Self {
            status: 409,
            headers: vec![("X-Inertia-Location".to_string(), location.into())],
            body: String::new(),
            content_type: "text/plain",
        }
    }

    /// Set the HTTP status code.
    pub fn status(mut self, status: u16) -> Self {
        self.status = status;
        self
    }

    /// Add a header to the response.
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// Create a redirect response for Inertia requests.
    ///
    /// For POST/PUT/PATCH/DELETE requests, uses status 303 (See Other) to force
    /// the browser to follow the redirect with a GET request.
    ///
    /// For GET requests, uses standard 302.
    pub fn redirect(location: impl Into<String>, is_post_like: bool) -> Self {
        // POST/PUT/PATCH/DELETE -> 303 (See Other) forces GET on redirect
        // GET -> 302 (Found) standard redirect
        let status = if is_post_like { 303 } else { 302 };

        Self {
            status,
            headers: vec![
                ("X-Inertia".to_string(), "true".to_string()),
                ("Location".to_string(), location.into()),
            ],
            body: String::new(),
            content_type: "text/plain",
        }
    }
}

/// Main Inertia integration struct.
///
/// Provides methods for rendering Inertia responses in a framework-agnostic way.
pub struct Inertia;

impl Inertia {
    /// Render an Inertia response.
    ///
    /// This is the primary method for returning Inertia responses from handlers.
    /// It automatically:
    /// - Detects XHR vs initial page load
    /// - Filters props for partial reloads
    ///
    /// # Configuration
    ///
    /// This uses [`InertiaConfig::default`] (env-driven). It does NOT read any
    /// process-global app config — that wiring lives in the framework wrapper
    /// (`ferro_rs::Inertia`, configured via `App::set_inertia_config`). Direct
    /// embedders of this crate that need custom config should call
    /// [`Inertia::render_with_config`].
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use ferro_inertia::Inertia;
    /// use serde_json::json;
    ///
    /// let response = Inertia::render(&req, "Home", json!({
    ///     "title": "Welcome",
    ///     "user": { "name": "John" }
    /// }));
    /// ```
    pub fn render<R, P>(req: &R, component: &str, props: P) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(req, component, props, None, InertiaConfig::default(), false)
    }

    /// Render an Inertia response with JSON fallback for API clients.
    ///
    /// When enabled, requests with `Accept: application/json` header (but without
    /// `X-Inertia: true`) will receive raw props as JSON instead of HTML.
    ///
    /// This is useful for:
    /// - API testing with curl or Postman
    /// - Hybrid apps that sometimes need raw JSON
    /// - Debug tooling
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use ferro_inertia::Inertia;
    /// use serde_json::json;
    ///
    /// // curl -H "Accept: application/json" http://localhost:3000/posts/1
    /// // Returns raw JSON props instead of HTML
    /// let response = Inertia::render_with_json_fallback(&req, "Posts/Show", json!({
    ///     "post": { "id": 1, "title": "Hello" }
    /// }));
    /// ```
    pub fn render_with_json_fallback<R, P>(
        req: &R,
        component: &str,
        props: P,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(req, component, props, None, InertiaConfig::default(), true)
    }

    /// Render an Inertia response with shared props.
    pub fn render_with_shared<R, P>(
        req: &R,
        component: &str,
        props: P,
        shared: &InertiaShared,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(
            req,
            component,
            props,
            Some(shared),
            InertiaConfig::default(),
            false,
        )
    }

    /// Render an Inertia response with custom configuration.
    pub fn render_with_config<R, P>(
        req: &R,
        component: &str,
        props: P,
        config: InertiaConfig,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(req, component, props, None, config, false)
    }

    /// Render an Inertia response with all options.
    pub fn render_with_options<R, P>(
        req: &R,
        component: &str,
        props: P,
        shared: Option<&InertiaShared>,
        config: InertiaConfig,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(req, component, props, shared, config, false)
    }

    /// Render an Inertia response with all options and JSON fallback.
    pub fn render_with_options_and_json_fallback<R, P>(
        req: &R,
        component: &str,
        props: P,
        shared: Option<&InertiaShared>,
        config: InertiaConfig,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        Self::render_internal(req, component, props, shared, config, true)
    }

    /// Internal render method with all options.
    fn render_internal<R, P>(
        req: &R,
        component: &str,
        props: P,
        shared: Option<&InertiaShared>,
        config: InertiaConfig,
        json_fallback: bool,
    ) -> InertiaHttpResponse
    where
        R: InertiaRequest,
        P: Serialize,
    {
        let url = req.path().to_string();
        let is_inertia = req.is_inertia();
        let partial_data = req.inertia_partial_data();
        let partial_component = req.inertia_partial_component();

        // Serialize props
        let mut props_value = match serde_json::to_value(&props) {
            Ok(v) => v,
            Err(e) => {
                return InertiaHttpResponse::html(format!("Failed to serialize props: {e}"))
                    .status(500);
            }
        };

        // Merge shared props
        if let Some(shared) = shared {
            shared.merge_into(&mut props_value);
        }

        // Filter props for partial reloads
        if is_inertia {
            if let Some(partial_keys) = partial_data {
                let should_filter = partial_component.map(|pc| pc == component).unwrap_or(false);

                if should_filter {
                    props_value = Self::filter_partial_props(props_value, &partial_keys);
                }
            }
        }

        // Check for JSON fallback before normal Inertia handling
        // If JSON fallback is enabled and request accepts JSON but is not an Inertia request,
        // return raw props as JSON
        if json_fallback && !is_inertia && req.accepts_json() {
            return InertiaHttpResponse::raw_json(
                serde_json::to_string(&props_value).unwrap_or_default(),
            );
        }

        let response = InertiaResponse::new(component, props_value, url).with_config(config);

        // Extract CSRF token from shared props for HTML response
        let csrf = shared.and_then(|s| s.csrf.as_deref());

        if is_inertia {
            response.to_json_response()
        } else {
            response.to_html_response(csrf)
        }
    }

    /// Check if a version conflict should trigger a full reload.
    ///
    /// Returns `Some(response)` with a 409 Conflict if versions don't match.
    pub fn check_version<R: InertiaRequest>(
        req: &R,
        current_version: &str,
        redirect_url: &str,
    ) -> Option<InertiaHttpResponse> {
        if !req.is_inertia() {
            return None;
        }

        if let Some(client_version) = req.inertia_version() {
            if client_version != current_version {
                return Some(InertiaHttpResponse::conflict(redirect_url));
            }
        }

        None
    }

    /// Filter props to only include those requested in partial reload.
    fn filter_partial_props(props: serde_json::Value, partial_keys: &[&str]) -> serde_json::Value {
        match props {
            serde_json::Value::Object(map) => {
                let filtered: serde_json::Map<String, serde_json::Value> = map
                    .into_iter()
                    .filter(|(k, _)| partial_keys.contains(&k.as_str()))
                    .collect();
                serde_json::Value::Object(filtered)
            }
            other => other,
        }
    }
}

/// Internal response builder.
pub struct InertiaResponse {
    component: String,
    props: serde_json::Value,
    url: String,
    config: InertiaConfig,
}

impl InertiaResponse {
    /// Create a new Inertia response.
    pub fn new(component: impl Into<String>, props: serde_json::Value, url: String) -> Self {
        Self {
            component: component.into(),
            props,
            url,
            config: InertiaConfig::default(),
        }
    }

    /// Set the configuration.
    pub fn with_config(mut self, config: InertiaConfig) -> Self {
        self.config = config;
        self
    }

    /// Build JSON response for XHR requests.
    pub fn to_json_response(&self) -> InertiaHttpResponse {
        let page = serde_json::json!({
            "component": self.component,
            "props": self.props,
            "url": self.url,
            "version": self.config.version,
        });

        InertiaHttpResponse::json(serde_json::to_string(&page).unwrap_or_default())
    }

    /// Build HTML response for initial page loads.
    pub fn to_html_response(&self, csrf_token: Option<&str>) -> InertiaHttpResponse {
        let page_data = serde_json::json!({
            "component": self.component,
            "props": self.props,
            "url": self.url,
            "version": self.config.version,
        });

        // Escape JSON for the double-quoted data-page HTML attribute.
        let page_json = escape_html(&serde_json::to_string(&page_data).unwrap_or_default());

        let csrf = escape_html(csrf_token.unwrap_or(""));

        // Use custom template if provided
        if let Some(template) = &self.config.html_template {
            let html = template
                .replace("{page}", &page_json)
                .replace("{csrf}", &csrf);
            return InertiaHttpResponse::html(html);
        }

        // Derive shared template values from config fields (title/head_extras/mount_id).
        // title and mount_id are escaped — they land in a <title> element and an id="" attribute.
        // head_extras is intentionally NOT escaped: it is raw, developer-controlled HTML
        // (trust boundary documented on InertiaConfig::head_extras — never populate from request data).
        let title_text = escape_html(
            self.config
                .title
                .as_deref()
                .unwrap_or(&self.config.app_name),
        );
        let head_extras = self.config.head_extras.as_deref().unwrap_or("");
        let mount_id = escape_html(&self.config.mount_id);

        // Default template
        let html = if self.config.development {
            format!(
                r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{}">
    <title>{}</title>
    <script type="module">
        import RefreshRuntime from '{}/@react-refresh'
        RefreshRuntime.injectIntoGlobalHook(window)
        window.$RefreshReg$ = () => {{}}
        window.$RefreshSig$ = () => (type) => type
        window.__vite_plugin_react_preamble_installed__ = true
    </script>
    <script type="module" src="{}/@vite/client"></script>
    <script type="module" src="{}/{}"></script>
    {}
</head>
<body>
    <div id="{}" data-page="{}"></div>
</body>
</html>"#,
                csrf,
                title_text,
                self.config.vite_dev_server,
                self.config.vite_dev_server,
                self.config.vite_dev_server,
                self.config.entry_point,
                head_extras,
                mount_id,
                page_json
            )
        } else {
            let assets = resolve_assets(&self.config.manifest_path, &self.config.entry_point);

            let css_tags: String = assets
                .css
                .iter()
                .map(|href| format!(r#"    <link rel="stylesheet" href="{href}">"#))
                .collect::<Vec<_>>()
                .join("\n");

            format!(
                r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{csrf}">
    <title>{title_text}</title>
    <script type="module" src="{js_src}"></script>
{css_tags}
    {head_extras}
</head>
<body>
    <div id="{mount_id}" data-page="{page_json}"></div>
</body>
</html>"#,
                js_src = assets.js,
                title_text = title_text,
                head_extras = head_extras,
                mount_id = mount_id,
            )
        };

        InertiaHttpResponse::html(html)
    }
}

#[cfg(test)]
mod content_negotiation_tests {
    use super::*;
    use crate::config::InertiaConfig;

    struct MockReq {
        is_inertia: bool,
        path: &'static str,
    }

    impl crate::request::InertiaRequest for MockReq {
        fn inertia_header(&self, name: &str) -> Option<&str> {
            if name == "X-Inertia" && self.is_inertia {
                Some("true")
            } else {
                None
            }
        }
        fn path(&self) -> &str {
            self.path
        }
    }

    #[test]
    fn non_inertia_request_returns_html_document() {
        let req = MockReq {
            is_inertia: false,
            path: "/home",
        };
        let resp = Inertia::render_with_config(
            &req,
            "Home",
            serde_json::json!({"title": "Hi"}),
            InertiaConfig::new().development(),
        );
        assert_eq!(resp.content_type, "text/html; charset=utf-8");
        assert!(resp.body.contains("<!DOCTYPE html>"));
        assert!(resp.body.contains(r#"data-page=""#));
    }

    #[test]
    fn inertia_request_returns_json_contract() {
        let req = MockReq {
            is_inertia: true,
            path: "/home",
        };
        let resp = Inertia::render_with_config(
            &req,
            "Home",
            serde_json::json!({"title": "Hi"}),
            InertiaConfig::new().development(),
        );
        assert_eq!(resp.content_type, "application/json");
        let body: serde_json::Value = serde_json::from_str(&resp.body).unwrap();
        assert_eq!(body["component"], "Home");
    }

    #[test]
    fn html_data_page_equals_json_contract() {
        let props = serde_json::json!({"title": "Hi", "count": 42});
        let cfg = InertiaConfig::new().development().version("test-1");
        let html = Inertia::render_with_config(
            &MockReq {
                is_inertia: false,
                path: "/home",
            },
            "Home",
            props.clone(),
            cfg.clone(),
        );
        let json = Inertia::render_with_config(
            &MockReq {
                is_inertia: true,
                path: "/home",
            },
            "Home",
            props,
            cfg,
        );
        let start = html.body.find(r#"data-page=""#).unwrap() + 11;
        let end = html.body[start..].find('"').unwrap() + start;
        let page = html.body[start..end]
            .replace("&quot;", "\"")
            .replace("&amp;", "&")
            .replace("&lt;", "<")
            .replace("&gt;", ">")
            .replace("&#x27;", "'");
        let html_page: serde_json::Value = serde_json::from_str(&page).unwrap();
        let json_page: serde_json::Value = serde_json::from_str(&json.body).unwrap();
        assert_eq!(html_page, json_page);
    }

    #[test]
    fn dev_mode_emits_vite_client_script() {
        let resp = Inertia::render_with_config(
            &MockReq {
                is_inertia: false,
                path: "/",
            },
            "App",
            serde_json::json!({}),
            InertiaConfig::new()
                .development()
                .vite_dev_server("http://localhost:5173"),
        );
        assert!(resp.body.contains("http://localhost:5173/@vite/client"));
    }

    #[test]
    fn title_override() {
        let resp = Inertia::render_with_config(
            &MockReq {
                is_inertia: false,
                path: "/",
            },
            "App",
            serde_json::json!({}),
            InertiaConfig::new()
                .development()
                .app_name("Fallback")
                .title("Explicit"),
        );
        assert!(resp.body.contains("<title>Explicit</title>"));
        assert!(!resp.body.contains("<title>Fallback</title>"));
    }

    #[test]
    fn head_extras_in_html() {
        let resp = Inertia::render_with_config(
            &MockReq {
                is_inertia: false,
                path: "/",
            },
            "App",
            serde_json::json!({}),
            InertiaConfig::new()
                .development()
                .head_extras(r#"<meta name="x" content="y">"#),
        );
        assert!(resp.body.contains(r#"<meta name="x" content="y">"#));
    }

    #[test]
    fn mount_id_applied() {
        let resp = Inertia::render_with_config(
            &MockReq {
                is_inertia: false,
                path: "/",
            },
            "App",
            serde_json::json!({}),
            InertiaConfig::new().development().mount_id("root"),
        );
        assert!(resp.body.contains(r#"id="root" data-page="#));
    }

    // SECURITY (T-238-03): prod build must never emit the @vite/client preamble.
    // Uses the prod branch — asserts ABSENCE of dev tags (manifest-cache bleed
    // is harmless for absence assertions).
    #[test]
    fn prod_mode_does_not_leak_dev_server() {
        let resp = Inertia::render_with_config(
            &MockReq {
                is_inertia: false,
                path: "/",
            },
            "App",
            serde_json::json!({}),
            InertiaConfig::new()
                .production()
                .vite_dev_server("http://localhost:5173"),
        );
        assert!(!resp.body.contains("/@vite/client"));
        assert!(!resp.body.contains("@react-refresh"));
    }
}