Skip to main content

saola_kit/envelope/
mod.rs

1pub mod auth;
2pub mod context_state;
3pub mod share;
4#[cfg(feature = "view")]
5pub mod ssr;
6
7use laravel::http::{IntoResponse, Json, Request, Response, StatusCode};
8use serde::Serialize;
9#[cfg(feature = "view")]
10use serde_json::Value;
11
12pub use auth::{ClientAuthProjection, ClientAuthUser, ClientGuardState};
13pub use context_state::{AppBootConfig, ViewContextState};
14pub use share::{ClientShare, InvalidShareKeyError};
15
16pub const HEADER_ENVELOPE: &str = "x-saola-envelope";
17pub const HEADER_CLIENT: &str = "x-saola-client";
18pub const HEADER_VIEW_REVISION: &str = "x-saola-view-revision";
19pub const HEADER_LANGUAGE: &str = "x-saola-language";
20pub const HEADER_LANGUAGE_REVISION: &str = "x-saola-language-revision";
21pub const HEADER_SAO_RESPONSE: &str = "x-sao-response";
22pub const HEADER_ONE_RESPONSE: &str = "x-one-response";
23
24/// Returns `true` when the client expects a Saola JSON envelope instead of the HTML shell.
25pub fn wants_saola_json(request: &Request) -> bool {
26    if request.wants_json() {
27        return true;
28    }
29    if header_eq_ignore_ascii_case(request, HEADER_SAO_RESPONSE, "json")
30        || header_eq_ignore_ascii_case(request, HEADER_ONE_RESPONSE, "json")
31    {
32        return true;
33    }
34    request.header(HEADER_CLIENT).is_some()
35}
36
37/// Returns `true` when the request identifies a v2 Saola client (`X-Saola-Client: 2`).
38pub fn is_client_v2(request: &Request) -> bool {
39    request.header(HEADER_CLIENT) == Some("2")
40}
41
42fn header_eq_ignore_ascii_case(request: &Request, name: &str, expected: &str) -> bool {
43    request
44        .header(name)
45        .is_some_and(|value| value.trim().eq_ignore_ascii_case(expected))
46}
47
48#[derive(Debug, Clone, Serialize)]
49struct EnvelopeBody<T> {
50    data: T,
51    #[serde(skip_serializing_if = "Option::is_none")]
52    view: Option<String>,
53    #[serde(skip_serializing_if = "Option::is_none")]
54    auth: Option<ClientAuthProjection>,
55}
56
57/// Standard Saola JSON response envelope: `{ data, view?, auth? }` with `X-Saola-Envelope: 1`.
58#[derive(Debug, Clone)]
59pub struct Envelope<T> {
60    data: T,
61    view: Option<String>,
62    auth: Option<ClientAuthProjection>,
63    status: StatusCode,
64    view_revision: Option<String>,
65    language_revision: Option<String>,
66    headers: Vec<(String, String)>,
67}
68
69impl<T: Serialize> Envelope<T> {
70    pub fn new(data: T) -> Self {
71        Self {
72            data,
73            view: None,
74            auth: None,
75            status: StatusCode::OK,
76            view_revision: None,
77            language_revision: None,
78            headers: Vec::new(),
79        }
80    }
81
82    pub fn ok(data: T) -> Self {
83        Self::new(data)
84    }
85
86    pub fn created(data: T) -> Self {
87        Self::new(data).status(StatusCode::CREATED)
88    }
89
90    pub fn view(mut self, view_key: impl Into<String>) -> Self {
91        self.view = Some(view_key.into());
92        self
93    }
94
95    pub fn auth(mut self, auth: ClientAuthProjection) -> Self {
96        self.auth = Some(auth);
97        self
98    }
99
100    pub fn status(mut self, status: StatusCode) -> Self {
101        self.status = status;
102        self
103    }
104
105    pub fn view_revision(mut self, revision: impl Into<String>) -> Self {
106        self.view_revision = Some(revision.into());
107        self
108    }
109
110    pub fn language_revision(mut self, revision: impl Into<String>) -> Self {
111        self.language_revision = Some(revision.into());
112        self
113    }
114
115    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
116        self.headers.push((name.into(), value.into()));
117        self
118    }
119}
120
121impl<T: Serialize> IntoResponse for Envelope<T> {
122    fn into_response(self) -> Response {
123        let body = EnvelopeBody {
124            data: self.data,
125            view: self.view,
126            auth: self.auth,
127        };
128
129        let mut response = Json(body)
130            .with_status(self.status)
131            .with_header("content-type", "application/json; charset=utf-8")
132            .with_header(HEADER_ENVELOPE, "1");
133
134        if let Some(rev) = self.view_revision {
135            response = response.with_header(HEADER_VIEW_REVISION, rev);
136        }
137        if let Some(rev) = self.language_revision {
138            response = response.with_header(HEADER_LANGUAGE_REVISION, rev);
139        }
140        for (name, value) in self.headers {
141            response = response.with_header(name, value);
142        }
143
144        response
145    }
146}
147
148/// Hybrid Saola page response: returns [`Envelope`] JSON for SPA/API requests, or renders the root
149/// HTML shell view for initial browser document requests.
150#[derive(Debug, Clone)]
151pub struct PageResponse<T> {
152    view_key: String,
153    data: T,
154    shell: String,
155    boot_config: Option<AppBootConfig>,
156    title: Option<String>,
157    locale: String,
158    context: String,
159    auth: Option<ClientAuthProjection>,
160    status: StatusCode,
161    view_revision: Option<String>,
162    language_revision: Option<String>,
163    headers: Vec<(String, String)>,
164    #[cfg(feature = "view")]
165    ssr: Option<SsrSpec>,
166}
167
168#[cfg(feature = "view")]
169#[derive(Debug, Clone)]
170struct SsrSpec {
171    template: String,
172    site: Option<Value>,
173    system: Vec<(String, String)>,
174    container: String,
175    document: bool,
176}
177
178#[derive(Serialize)]
179struct ShellViewPayload<T> {
180    saola_view: String,
181    saola_data: T,
182    #[serde(skip_serializing_if = "Option::is_none")]
183    saola_auth: Option<ClientAuthProjection>,
184    saola_envelope_json: String,
185    saola_boot_json: String,
186    #[serde(skip_serializing_if = "Option::is_none")]
187    saola_title: Option<String>,
188    saola_locale: String,
189    saola_context: String,
190    /// JSON for `<script type="application/json" data-ref="saola-ssr">`: tells the client to hydrate instead of mount.
191    #[serde(skip_serializing_if = "Option::is_none")]
192    saola_ssr_boot_json: Option<String>,
193}
194
195impl<T: Serialize> PageResponse<T> {
196    pub fn new(view_key: impl Into<String>, data: T) -> Self {
197        Self {
198            view_key: view_key.into(),
199            data,
200            shell: "app".to_owned(),
201            boot_config: None,
202            title: None,
203            locale: "vi".to_owned(),
204            context: "web".to_owned(),
205            auth: None,
206            status: StatusCode::OK,
207            view_revision: None,
208            language_revision: None,
209            headers: Vec::new(),
210            #[cfg(feature = "view")]
211            ssr: None,
212        }
213    }
214
215    /// Render the page on the server with the compiled Jinja template `template` (output of
216    /// `rust-saoc view-ssr`). The shell receives `saola_ssr_html` (print with `| safe`) and
217    /// `saola_ssr_meta.<title|description|…>` taken from the template's `@section('meta:…')` blocks.
218    #[cfg(feature = "view")]
219    pub fn ssr(mut self, template: impl Into<String>) -> Self {
220        self.ssr = Some(SsrSpec { template: template.into(), site: None, system: Vec::new(), container: "#app-root".to_owned(), document: false });
221        self
222    }
223
224    /// System string constants the template composes names with (`__layout__`, `__component__`, `__page__`, …):
225    /// the view-name prefix, e.g. `ssr_system("__layout__", "web.layouts.")` makes `@extends(__layout__ + 'main')` load `web.layouts.main`.
226    #[cfg(feature = "view")]
227    pub fn ssr_system(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
228        if let Some(spec) = self.ssr.as_mut() {
229            spec.system.push((name.into(), value.into()));
230        }
231        self
232    }
233
234    /// Like [`ssr`](Self::ssr), but the template renders the **whole HTML document**: its `@extends` chain ends in the system view
235    /// (`__system__ ~ 'app'`, e.g. `resources/views/_system/app.html`), which prints the boot data itself. The template receives
236    /// `saola_locale`, `saola_title`, `saola_context`, `saola_boot_json`, `saola_envelope_json` and `saola_ssr_boot_json`; the shell
237    /// view is not used. If the render fails the page falls back to the shell (client-side render).
238    #[cfg(feature = "view")]
239    pub fn ssr_document(mut self, template: impl Into<String>) -> Self {
240        self.ssr = Some(SsrSpec { template: template.into(), site: None, system: Vec::new(), container: "#app-root".to_owned(), document: true });
241        self
242    }
243
244    /// CSS selector of the element that holds the server-rendered HTML (default `#app-root`), echoed to the client boot script.
245    #[cfg(feature = "view")]
246    pub fn ssr_container(mut self, selector: impl Into<String>) -> Self {
247        if let Some(spec) = self.ssr.as_mut() {
248            spec.container = selector.into();
249        }
250        self
251    }
252
253    /// Public site data exposed to the template as `__site`.
254    #[cfg(feature = "view")]
255    pub fn ssr_site(mut self, site: Value) -> Self {
256        if let Some(spec) = self.ssr.as_mut() {
257            spec.site = Some(site);
258        }
259        self
260    }
261
262    pub fn shell(mut self, template: impl Into<String>) -> Self {
263        self.shell = template.into();
264        self
265    }
266
267    pub fn boot_config(mut self, boot_config: AppBootConfig) -> Self {
268        self.boot_config = Some(boot_config);
269        self
270    }
271
272    pub fn title(mut self, title: impl Into<String>) -> Self {
273        self.title = Some(title.into());
274        self
275    }
276
277    pub fn locale(mut self, locale: impl Into<String>) -> Self {
278        self.locale = locale.into();
279        self
280    }
281
282    pub fn context(mut self, context: impl Into<String>) -> Self {
283        self.context = context.into();
284        self
285    }
286
287    pub fn auth(mut self, auth: ClientAuthProjection) -> Self {
288        self.auth = Some(auth);
289        self
290    }
291
292    pub fn status(mut self, status: StatusCode) -> Self {
293        self.status = status;
294        self
295    }
296
297    pub fn view_revision(mut self, revision: impl Into<String>) -> Self {
298        self.view_revision = Some(revision.into());
299        self
300    }
301
302    pub fn language_revision(mut self, revision: impl Into<String>) -> Self {
303        self.language_revision = Some(revision.into());
304        self
305    }
306
307    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
308        self.headers.push((name.into(), value.into()));
309        self
310    }
311
312    pub fn into_envelope(self) -> Envelope<T> {
313        let mut envelope = Envelope::new(self.data)
314            .view(self.view_key)
315            .status(self.status);
316        if let Some(auth) = self.auth {
317            envelope = envelope.auth(auth);
318        }
319        if let Some(rev) = self.view_revision {
320            envelope = envelope.view_revision(rev);
321        }
322        if let Some(rev) = self.language_revision {
323            envelope = envelope.language_revision(rev);
324        }
325        for (k, v) in self.headers {
326            envelope = envelope.header(k, v);
327        }
328        envelope
329    }
330
331    pub fn into_response_for(self, request: &Request) -> Response {
332        if wants_saola_json(request) {
333            return self.into_envelope().into_response();
334        }
335
336        let envelope_json = safe_inline_json(&EnvelopeBody {
337            data: &self.data,
338            view: Some(self.view_key.clone()),
339            auth: self.auth.clone(),
340        });
341
342        let boot_json = match &self.boot_config {
343            Some(boot) => safe_inline_json(boot),
344            None => safe_inline_json(&AppBootConfig::default()),
345        };
346
347        // Lỗi SSR không được làm hỏng trang: ghi log, shell vẫn có bản CSR để client tự dựng.
348        #[cfg(feature = "view")]
349        let ssr_boot_json_wanted = self.ssr.as_ref().map(|spec| {
350            safe_inline_json(&serde_json::json!({
351                "container": spec.container,
352                "view": self.view_key,
353                "viewId": ssr::root_view_id(&self.view_key),
354            }))
355        });
356        #[cfg(feature = "view")]
357        let ssr_out = self.ssr.as_ref().and_then(|spec| {
358            let extras: Vec<(&str, String)> = if spec.document {
359                vec![
360                    ("saola_locale", self.locale.clone()),
361                    ("saola_title", self.title.clone().unwrap_or_default()),
362                    ("saola_context", self.context.clone()),
363                    ("saola_boot_json", boot_json.clone()),
364                    ("saola_envelope_json", envelope_json.clone()),
365                    ("saola_ssr_boot_json", ssr_boot_json_wanted.clone().unwrap_or_default()),
366                ]
367            } else {
368                Vec::new()
369            };
370            ssr::render_page(spec.template.as_str(), spec.site.as_ref(), &spec.system, &self.data, &self.view_key, &self.locale, self.auth.as_ref(), &extras, spec.document)
371                .map_err(|e| tracing::error!(error = %e, template = %spec.template, "SSR render failed"))
372                .ok()
373        });
374
375        // Chế độ tài liệu: kết quả render LÀ cả trang (view hệ thống nằm trong chuỗi @extends), không qua shell.
376        #[cfg(feature = "view")]
377        if let (Some(spec), Some(out)) = (&self.ssr, &ssr_out) {
378            if spec.document {
379                let mut response = out.html.clone().into_response();
380                response = response.with_status(self.status);
381                if let Some(rev) = self.view_revision.clone() {
382                    response = response.with_header(HEADER_VIEW_REVISION, rev);
383                }
384                if let Some(rev) = self.language_revision.clone() {
385                    response = response.with_header(HEADER_LANGUAGE_REVISION, rev);
386                }
387                for (name, value) in self.headers.clone() {
388                    response = response.with_header(name, value);
389                }
390                return response;
391            }
392        }
393
394        #[cfg(feature = "view")]
395        let ssr_boot_json = if ssr_out.is_some() { ssr_boot_json_wanted } else { None };
396        #[cfg(not(feature = "view"))]
397        let ssr_boot_json: Option<String> = None;
398
399        let payload = ShellViewPayload {
400            saola_view: self.view_key,
401            saola_data: self.data,
402            saola_auth: self.auth,
403            saola_envelope_json: envelope_json,
404            saola_boot_json: boot_json,
405            saola_title: self.title,
406            saola_locale: self.locale,
407            saola_context: self.context,
408            saola_ssr_boot_json: ssr_boot_json,
409        };
410
411        #[allow(unused_mut)]
412        let mut shell_view = laravel::view::view(self.shell.clone(), payload);
413        #[cfg(feature = "view")]
414        if let Some(out) = ssr_out {
415            shell_view = shell_view.with_html("saola_ssr_html", out.html);
416            for (key, html) in out.meta {
417                shell_view = shell_view.with_html(format!("saola_ssr_meta_{key}"), html);
418            }
419        }
420        let mut response = shell_view.with_status(self.status).into_response();
421
422        if let Some(rev) = self.view_revision {
423            response = response.with_header(HEADER_VIEW_REVISION, rev);
424        }
425        if let Some(rev) = self.language_revision {
426            response = response.with_header(HEADER_LANGUAGE_REVISION, rev);
427        }
428        for (name, value) in self.headers {
429            response = response.with_header(name, value);
430        }
431
432        response
433    }
434}
435
436fn safe_inline_json<T: Serialize>(value: &T) -> String {
437    let raw = serde_json::to_string(value).unwrap_or_else(|_| "{}".to_owned());
438    let mut escaped = String::with_capacity(raw.len());
439    for ch in raw.chars() {
440        match ch {
441            '<' => escaped.push_str("\\u003c"),
442            '>' => escaped.push_str("\\u003e"),
443            '&' => escaped.push_str("\\u0026"),
444            '\u{2028}' => escaped.push_str("\\u2028"),
445            '\u{2029}' => escaped.push_str("\\u2029"),
446            _ => escaped.push(ch),
447        }
448    }
449    escaped
450}
451
452/// Convenience constructor for [`PageResponse`], matching `saola::render(view, data)`.
453pub fn render<T: Serialize>(view_key: impl Into<String>, data: T) -> PageResponse<T> {
454    PageResponse::new(view_key, data)
455}