saola-kit 0.1.0

Saola core toolkit for Laravel for Rust (contexts, envelope protocol, i18n, masks, modules, Sanctum-compatible tokens)
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
pub mod auth;
pub mod context_state;
pub mod share;
#[cfg(feature = "view")]
pub mod ssr;

use laravel::http::{IntoResponse, Json, Request, Response, StatusCode};
use serde::Serialize;
#[cfg(feature = "view")]
use serde_json::Value;

pub use auth::{ClientAuthProjection, ClientAuthUser, ClientGuardState};
pub use context_state::{AppBootConfig, ViewContextState};
pub use share::{ClientShare, InvalidShareKeyError};

pub const HEADER_ENVELOPE: &str = "x-saola-envelope";
pub const HEADER_CLIENT: &str = "x-saola-client";
pub const HEADER_VIEW_REVISION: &str = "x-saola-view-revision";
pub const HEADER_LANGUAGE: &str = "x-saola-language";
pub const HEADER_LANGUAGE_REVISION: &str = "x-saola-language-revision";
pub const HEADER_SAO_RESPONSE: &str = "x-sao-response";
pub const HEADER_ONE_RESPONSE: &str = "x-one-response";

/// Returns `true` when the client expects a Saola JSON envelope instead of the HTML shell.
pub fn wants_saola_json(request: &Request) -> bool {
    if request.wants_json() {
        return true;
    }
    if header_eq_ignore_ascii_case(request, HEADER_SAO_RESPONSE, "json")
        || header_eq_ignore_ascii_case(request, HEADER_ONE_RESPONSE, "json")
    {
        return true;
    }
    request.header(HEADER_CLIENT).is_some()
}

/// Returns `true` when the request identifies a v2 Saola client (`X-Saola-Client: 2`).
pub fn is_client_v2(request: &Request) -> bool {
    request.header(HEADER_CLIENT) == Some("2")
}

fn header_eq_ignore_ascii_case(request: &Request, name: &str, expected: &str) -> bool {
    request
        .header(name)
        .is_some_and(|value| value.trim().eq_ignore_ascii_case(expected))
}

#[derive(Debug, Clone, Serialize)]
struct EnvelopeBody<T> {
    data: T,
    #[serde(skip_serializing_if = "Option::is_none")]
    view: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    auth: Option<ClientAuthProjection>,
}

/// Standard Saola JSON response envelope: `{ data, view?, auth? }` with `X-Saola-Envelope: 1`.
#[derive(Debug, Clone)]
pub struct Envelope<T> {
    data: T,
    view: Option<String>,
    auth: Option<ClientAuthProjection>,
    status: StatusCode,
    view_revision: Option<String>,
    language_revision: Option<String>,
    headers: Vec<(String, String)>,
}

impl<T: Serialize> Envelope<T> {
    pub fn new(data: T) -> Self {
        Self {
            data,
            view: None,
            auth: None,
            status: StatusCode::OK,
            view_revision: None,
            language_revision: None,
            headers: Vec::new(),
        }
    }

    pub fn ok(data: T) -> Self {
        Self::new(data)
    }

    pub fn created(data: T) -> Self {
        Self::new(data).status(StatusCode::CREATED)
    }

    pub fn view(mut self, view_key: impl Into<String>) -> Self {
        self.view = Some(view_key.into());
        self
    }

    pub fn auth(mut self, auth: ClientAuthProjection) -> Self {
        self.auth = Some(auth);
        self
    }

    pub fn status(mut self, status: StatusCode) -> Self {
        self.status = status;
        self
    }

    pub fn view_revision(mut self, revision: impl Into<String>) -> Self {
        self.view_revision = Some(revision.into());
        self
    }

    pub fn language_revision(mut self, revision: impl Into<String>) -> Self {
        self.language_revision = Some(revision.into());
        self
    }

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

impl<T: Serialize> IntoResponse for Envelope<T> {
    fn into_response(self) -> Response {
        let body = EnvelopeBody {
            data: self.data,
            view: self.view,
            auth: self.auth,
        };

        let mut response = Json(body)
            .with_status(self.status)
            .with_header("content-type", "application/json; charset=utf-8")
            .with_header(HEADER_ENVELOPE, "1");

        if let Some(rev) = self.view_revision {
            response = response.with_header(HEADER_VIEW_REVISION, rev);
        }
        if let Some(rev) = self.language_revision {
            response = response.with_header(HEADER_LANGUAGE_REVISION, rev);
        }
        for (name, value) in self.headers {
            response = response.with_header(name, value);
        }

        response
    }
}

/// Hybrid Saola page response: returns [`Envelope`] JSON for SPA/API requests, or renders the root
/// HTML shell view for initial browser document requests.
#[derive(Debug, Clone)]
pub struct PageResponse<T> {
    view_key: String,
    data: T,
    shell: String,
    boot_config: Option<AppBootConfig>,
    title: Option<String>,
    locale: String,
    context: String,
    auth: Option<ClientAuthProjection>,
    status: StatusCode,
    view_revision: Option<String>,
    language_revision: Option<String>,
    headers: Vec<(String, String)>,
    #[cfg(feature = "view")]
    ssr: Option<SsrSpec>,
}

#[cfg(feature = "view")]
#[derive(Debug, Clone)]
struct SsrSpec {
    template: String,
    site: Option<Value>,
    system: Vec<(String, String)>,
    container: String,
}

#[derive(Serialize)]
struct ShellViewPayload<T> {
    saola_view: String,
    saola_data: T,
    #[serde(skip_serializing_if = "Option::is_none")]
    saola_auth: Option<ClientAuthProjection>,
    saola_envelope_json: String,
    saola_boot_json: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    saola_title: Option<String>,
    saola_locale: String,
    saola_context: String,
    /// JSON for `<script type="application/json" data-ref="saola-ssr">`: tells the client to hydrate instead of mount.
    #[serde(skip_serializing_if = "Option::is_none")]
    saola_ssr_boot_json: Option<String>,
}

impl<T: Serialize> PageResponse<T> {
    pub fn new(view_key: impl Into<String>, data: T) -> Self {
        Self {
            view_key: view_key.into(),
            data,
            shell: "app".to_owned(),
            boot_config: None,
            title: None,
            locale: "vi".to_owned(),
            context: "web".to_owned(),
            auth: None,
            status: StatusCode::OK,
            view_revision: None,
            language_revision: None,
            headers: Vec::new(),
            #[cfg(feature = "view")]
            ssr: None,
        }
    }

    /// Render the page on the server with the compiled Jinja template `template` (output of
    /// `rust-saoc view-ssr`). The shell receives `saola_ssr_html` (print with `| safe`) and
    /// `saola_ssr_meta.<title|description|…>` taken from the template's `@section('meta:…')` blocks.
    #[cfg(feature = "view")]
    pub fn ssr(mut self, template: impl Into<String>) -> Self {
        self.ssr = Some(SsrSpec { template: template.into(), site: None, system: Vec::new(), container: "#app-root".to_owned() });
        self
    }

    /// System string constants the template composes names with (`__layout__`, `__component__`, `__page__`, …):
    /// the view-name prefix, e.g. `ssr_system("__layout__", "web.layouts.")` makes `@extends(__layout__ + 'main')` load `web.layouts.main`.
    #[cfg(feature = "view")]
    pub fn ssr_system(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        if let Some(spec) = self.ssr.as_mut() {
            spec.system.push((name.into(), value.into()));
        }
        self
    }

    /// CSS selector of the element that holds the server-rendered HTML (default `#app-root`), echoed to the client boot script.
    #[cfg(feature = "view")]
    pub fn ssr_container(mut self, selector: impl Into<String>) -> Self {
        if let Some(spec) = self.ssr.as_mut() {
            spec.container = selector.into();
        }
        self
    }

    /// Public site data exposed to the template as `__site`.
    #[cfg(feature = "view")]
    pub fn ssr_site(mut self, site: Value) -> Self {
        if let Some(spec) = self.ssr.as_mut() {
            spec.site = Some(site);
        }
        self
    }

    pub fn shell(mut self, template: impl Into<String>) -> Self {
        self.shell = template.into();
        self
    }

    pub fn boot_config(mut self, boot_config: AppBootConfig) -> Self {
        self.boot_config = Some(boot_config);
        self
    }

    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn locale(mut self, locale: impl Into<String>) -> Self {
        self.locale = locale.into();
        self
    }

    pub fn context(mut self, context: impl Into<String>) -> Self {
        self.context = context.into();
        self
    }

    pub fn auth(mut self, auth: ClientAuthProjection) -> Self {
        self.auth = Some(auth);
        self
    }

    pub fn status(mut self, status: StatusCode) -> Self {
        self.status = status;
        self
    }

    pub fn view_revision(mut self, revision: impl Into<String>) -> Self {
        self.view_revision = Some(revision.into());
        self
    }

    pub fn language_revision(mut self, revision: impl Into<String>) -> Self {
        self.language_revision = Some(revision.into());
        self
    }

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

    pub fn into_envelope(self) -> Envelope<T> {
        let mut envelope = Envelope::new(self.data)
            .view(self.view_key)
            .status(self.status);
        if let Some(auth) = self.auth {
            envelope = envelope.auth(auth);
        }
        if let Some(rev) = self.view_revision {
            envelope = envelope.view_revision(rev);
        }
        if let Some(rev) = self.language_revision {
            envelope = envelope.language_revision(rev);
        }
        for (k, v) in self.headers {
            envelope = envelope.header(k, v);
        }
        envelope
    }

    pub fn into_response_for(self, request: &Request) -> Response {
        if wants_saola_json(request) {
            return self.into_envelope().into_response();
        }

        let envelope_json = safe_inline_json(&EnvelopeBody {
            data: &self.data,
            view: Some(self.view_key.clone()),
            auth: self.auth.clone(),
        });

        let boot_json = match &self.boot_config {
            Some(boot) => safe_inline_json(boot),
            None => safe_inline_json(&AppBootConfig::default()),
        };

        // Lỗi SSR không được làm hỏng trang: ghi log, shell vẫn có bản CSR để client tự dựng.
        #[cfg(feature = "view")]
        let ssr_out = self.ssr.as_ref().and_then(|spec| {
            ssr::render_page(spec.template.as_str(), spec.site.as_ref(), &spec.system, &self.data, &self.view_key, &self.locale, self.auth.as_ref())
                .map_err(|e| tracing::error!(error = %e, template = %spec.template, "SSR render failed"))
                .ok()
        });

        #[cfg(feature = "view")]
        let ssr_boot_json = match (&self.ssr, &ssr_out) {
            (Some(spec), Some(_)) => Some(safe_inline_json(&serde_json::json!({
                "container": spec.container,
                "view": self.view_key,
                "viewId": ssr::root_view_id(&self.view_key),
            }))),
            _ => None,
        };
        #[cfg(not(feature = "view"))]
        let ssr_boot_json: Option<String> = None;

        let payload = ShellViewPayload {
            saola_view: self.view_key,
            saola_data: self.data,
            saola_auth: self.auth,
            saola_envelope_json: envelope_json,
            saola_boot_json: boot_json,
            saola_title: self.title,
            saola_locale: self.locale,
            saola_context: self.context,
            saola_ssr_boot_json: ssr_boot_json,
        };

        #[allow(unused_mut)]
        let mut shell_view = laravel::view::view(self.shell.clone(), payload);
        #[cfg(feature = "view")]
        if let Some(out) = ssr_out {
            shell_view = shell_view.with_html("saola_ssr_html", out.html);
            for (key, html) in out.meta {
                shell_view = shell_view.with_html(format!("saola_ssr_meta_{key}"), html);
            }
        }
        let mut response = shell_view.with_status(self.status).into_response();

        if let Some(rev) = self.view_revision {
            response = response.with_header(HEADER_VIEW_REVISION, rev);
        }
        if let Some(rev) = self.language_revision {
            response = response.with_header(HEADER_LANGUAGE_REVISION, rev);
        }
        for (name, value) in self.headers {
            response = response.with_header(name, value);
        }

        response
    }
}

fn safe_inline_json<T: Serialize>(value: &T) -> String {
    let raw = serde_json::to_string(value).unwrap_or_else(|_| "{}".to_owned());
    let mut escaped = String::with_capacity(raw.len());
    for ch in raw.chars() {
        match ch {
            '<' => escaped.push_str("\\u003c"),
            '>' => escaped.push_str("\\u003e"),
            '&' => escaped.push_str("\\u0026"),
            '\u{2028}' => escaped.push_str("\\u2028"),
            '\u{2029}' => escaped.push_str("\\u2029"),
            _ => escaped.push(ch),
        }
    }
    escaped
}

/// Convenience constructor for [`PageResponse`], matching `saola::render(view, data)`.
pub fn render<T: Serialize>(view_key: impl Into<String>, data: T) -> PageResponse<T> {
    PageResponse::new(view_key, data)
}