hauchiwa 0.21.0

Flexible static website generator library with incremental rebuilds and cached image optimization
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
//! # Svelte hybrid rendering pipeline
//!
//! Compiles Svelte components for Server-Side Rendering (SSR) and Client-Side Hydration.
//!
//! This module bridges the gap between Rust and Svelte. It uses
//! [Deno](https://deno.land/) to compile your components into two parts: a
//! server-side renderer (callable from Rust) and a client-side hydration script
//! (loadable by the browser).
//!
//! **Note**: Requires the `deno` binary to be available in your system PATH.
//!
//! ## Capabilities
//!
//! * **Hybrid Rendering**: Generates static HTML at build time while keeping components interactive in the browser.
//! * **Type-Safe Props**: Pass data from Rust to Svelte using strongly-typed, serializable structs.
//! * **Sandboxed Compilation**: Uses Deno for a secure, standard-compliant build environment.
//! * **Automatic Hydration**: Injects the necessary code to "wake up" components on the client side.
//!
//! ## Usage
//!
//! Define your props struct, register the loader, and use the resulting handle
//! to render HTML strings within your page tasks.
//!
//! ```rust,no_run
//! use hauchiwa::Blueprint;
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Clone, Serialize, Deserialize)]
//! struct ButtonProps {
//!     label: String,
//!     count: i32,
//! }
//!
//! fn configure(config: &mut Blueprint<()>) -> Result<(), hauchiwa::error::HauchiwaError> {
//!     // 1. Load the component
//!     // Returns Many<Svelte<ButtonProps>>
//!     let buttons = config.load_svelte::<ButtonProps>()
//!         .entry("components/Counter.svelte")?
//!         .register();
//!
//!     // 2. Use it in a task to render HTML
//!     config
//!         .task()
//!         .using(buttons)
//!         .merge(|ctx, buttons| {
//!             let component = buttons.get("components/Counter.svelte").unwrap();
//!
//!             // SSR happens here (Rust -> JS -> HTML)
//!             let props = ButtonProps { label: "Click me".into(), count: 0 };
//!             let html = (component.prerender)(&props)?;
//!
//!             // The `component.hydration` field contains the path to the client-side JS
//!             println!("Rendered: {}", html);
//!             Ok(())
//!         });
//!
//!     Ok(())
//! }
//! ```
use std::{
    io::Write,
    process::{Command, Stdio},
    sync::{Arc, LazyLock},
};

use camino::Utf8Path;
use glob::Pattern;
use serde::{Serialize, de::DeserializeOwned};
use thiserror::Error;

use crate::core::Hash32;
use crate::{
    Blueprint,
    engine::Many,
    error::HauchiwaError,
    loader::{GlobBundle, Script},
};

#[derive(Debug, Error)]
pub enum SvelteError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("UTF-8 conversion error: {0}")]
    Utf8(#[from] std::string::FromUtf8Error),

    #[error("Serialization error: {0}")]
    Json(#[from] serde_json::Error),

    #[error("Deno execution failed: {0}")]
    Deno(String),

    #[error("Failed to capture child process stdin")]
    StdinCapture,

    #[error("Svelte runtime compilation failed: {0}")]
    Runtime(String),

    #[error("Failed to parse Deno output: {0}")]
    ParseOutput(String),
}

struct MappedJs {
    code: String,
    map: Vec<u8>,
}

// Update the Prerender type alias to use the specific error
type Prerender<P> = Arc<dyn Fn(&P) -> Result<String, SvelteError> + Send + Sync>;

// The LazyLock now holds a specific Result type.
static RUNTIME: LazyLock<Result<MappedJs, SvelteError>> = LazyLock::new(compile_svelte_runtime);

/// Represents a compiled Svelte component.
///
/// This struct allows you to:
/// 1. Server-side render (SSR) the component into HTML string using the `prerender` closure.
/// 2. Client-side hydrate the component using the scripts in `hydration` and `runtime`.
///
/// # Generics
///
/// * `P`: The type of the component's props.
#[derive(Clone)]
pub struct Svelte<P = ()>
where
    P: serde::Serialize,
{
    /// A closure that takes props `P` and returns the rendered HTML string.
    /// This is used for Server-Side Rendering (SSR).
    pub prerender: Prerender<P>,
    /// The initialization script for this specific component (client-side hydration).
    pub hydration: Script,
    /// The shared Svelte runtime library script.
    pub runtime: Script,
}

/// A builder for configuring the Svelte loader task.
pub struct SvelteLoader<'a, G, P>
where
    G: Send + Sync,
    P: Clone + DeserializeOwned + Serialize + 'static,
{
    blueprint: &'a mut Blueprint<G>,
    entry_globs: Vec<String>,
    entry_patterns: Vec<Pattern>,
    watch_globs: Vec<Pattern>,
    _phantom: std::marker::PhantomData<P>,
}

impl<'a, G, P> SvelteLoader<'a, G, P>
where
    G: Send + Sync + 'static,
    P: Clone + DeserializeOwned + Serialize + 'static,
{
    fn new(blueprint: &'a mut Blueprint<G>) -> Self {
        Self {
            blueprint,
            entry_globs: Vec::new(),
            entry_patterns: Vec::new(),
            watch_globs: Vec::new(),
            _phantom: std::marker::PhantomData,
        }
    }

    /// Adds a glob pattern for the entry components (e.g., "components/Button.svelte").
    pub fn entry(mut self, glob: impl Into<String>) -> Result<Self, HauchiwaError> {
        let glob = glob.into();
        let pattern = Pattern::new(&glob)?;
        self.entry_globs.push(glob);
        self.entry_patterns.push(pattern);
        Ok(self)
    }

    /// Adds a glob pattern for files to watch (e.g., "components/**/*.svelte").
    ///
    /// If never called, defaults to watching the entry globs.
    pub fn watch(mut self, glob: impl Into<String>) -> Result<Self, HauchiwaError> {
        let glob = glob.into();
        let pattern = Pattern::new(&glob)?;
        self.watch_globs.push(pattern);
        Ok(self)
    }

    /// Registers the task with the Blueprint.
    pub fn register(self) -> Many<Svelte<P>> {
        let watch_globs = if self.watch_globs.is_empty() {
            self.entry_patterns
        } else {
            self.watch_globs
        };

        let task = GlobBundle::new(self.entry_globs, watch_globs, move |_, store, input| {
            let runtime = match RUNTIME.as_ref() {
                Ok(runtime) => {
                    let srcmap = store.save(&runtime.map, "js.map")?;
                    let script = format!("{}\n//# sourceMappingURL={}", runtime.code, srcmap);
                    store.save(script.as_bytes(), "js")?
                }
                Err(err) => return Err(SvelteError::Runtime(err.to_string()).into()),
            };

            // In the import map "svelte" should be registered, so that it
            // points to the runtime file.
            store.register("svelte", runtime.as_str());
            store.register("svelte/internal/client", runtime.as_str());
            store.register("svelte/internal/disclose-version", runtime.as_str());

            // Compile the SSR script
            let server = compile_svelte_server(&input.path)?;
            let anchor = Hash32::hash(&server);

            // Compile lean browser glue
            let client = {
                let client = compile_svelte_init(&input.path, anchor)?;
                let srcmap = store.save(&client.map, "js.map")?;
                let script = format!("{}\n//# sourceMappingURL={}", client.code, srcmap);
                store.save(script.as_bytes(), "js")?
            };

            // With the compiled SSR script we can now pre-render the
            // component on demand.
            let prerender = Arc::new({
                let anchor = anchor.to_hex();

                move |props: &P| {
                    let json = serde_json::to_string(props)?;
                    let html = run_ssr(&server, &json)?;

                    Ok(format!(
                        "<div class='_{anchor}' data-props='{json}'>{html}</div>"
                    ))
                }
            });

            Ok((
                anchor,
                input.path,
                Svelte::<P> {
                    prerender,
                    hydration: Script { path: client },
                    runtime: Script { path: runtime },
                },
            ))
        });

        let task = task.require(crate::preflight::Requirement::Binary("deno"));

        self.blueprint.add_task_fine(task)
    }
}

impl<G> Blueprint<G>
where
    G: Send + Sync + 'static,
{
    /// Starts configuring a Svelte loader task.
    ///
    /// This loader uses Deno to compile Svelte components found by the entry glob.
    /// It produces an SSR-capable script and a client-side hydration script.
    ///
    /// # Generics
    ///
    /// * `P`: The type of the properties (props) that the Svelte component accepts.
    ///   This type must be serializable and deserializable.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # let mut config = hauchiwa::Blueprint::<()>::new();
    /// #[derive(serde::Serialize, serde::Deserialize, Clone)]
    /// struct ButtonProps {
    ///     label: String,
    /// }
    ///
    /// let buttons = config.load_svelte::<ButtonProps>()
    ///     .entry("components/Button.svelte")?
    ///     .watch("components/**/*.svelte")?
    ///     .register();
    /// # Ok::<(), hauchiwa::error::HauchiwaError>(())
    /// ```
    pub fn load_svelte<P>(&mut self) -> SvelteLoader<'_, G, P>
    where
        P: Clone + DeserializeOwned + Serialize + 'static,
    {
        SvelteLoader::new(self)
    }
}

fn compile_svelte_server(file: &Utf8Path) -> Result<String, SvelteError> {
    const SERVER: &[u8] = include_bytes!("./server.ts");

    let mut child = Command::new("deno")
        .arg("run")
        .arg("--quiet")
        .arg("--allow-env")
        .arg("--allow-read")
        .arg("--allow-run")
        .arg("-")
        .arg(file.as_str())
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    {
        let stdin = child.stdin.as_mut().ok_or(SvelteError::StdinCapture)?;
        stdin.write_all(SERVER)?;
        stdin.flush()?;
    }

    let output = child.wait_with_output()?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(SvelteError::Deno(format!("Deno bundler failed:\n{stderr}")));
    }

    Ok(String::from_utf8(output.stdout)?)
}

fn run_ssr(server: &str, props: &str) -> Result<String, SvelteError> {
    const SSR: &str = include_str!("./ssr.ts");

    let mut child = Command::new("deno")
        .arg("run")
        .arg("--allow-env")
        .arg("--quiet")
        .arg("-")
        .arg(props)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    {
        let stdin = child.stdin.as_mut().ok_or(SvelteError::StdinCapture)?;
        stdin.write_all(SSR.replace("__PLACEHOLDER__", server).as_bytes())?;
        stdin.flush()?;
    }

    let output = child.wait_with_output()?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(SvelteError::Deno(format!("Deno SSR failed:\n{stderr}")));
    }

    Ok(String::from_utf8(output.stdout)?)
}

fn compile_svelte_init(file: &Utf8Path, hash_class: Hash32) -> Result<MappedJs, SvelteError> {
    const INIT: &[u8] = include_bytes!("./init.ts");

    let mut child = Command::new("deno")
        .arg("run")
        .arg("--quiet")
        .arg("--allow-env")
        .arg("--allow-read")
        .arg("--allow-run")
        .arg("-")
        .arg(file.canonicalize()?)
        .arg(hash_class.to_hex())
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    {
        let stdin = child.stdin.as_mut().ok_or(SvelteError::StdinCapture)?;
        stdin.write_all(INIT)?;
        stdin.flush()?;
    }

    let output = child.wait_with_output()?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(SvelteError::Deno(format!("Deno bundler failed:\n{stderr}")));
    }

    parse_deno_output(&output.stdout)
}

fn compile_svelte_runtime() -> Result<MappedJs, SvelteError> {
    const RT: &[u8] = include_bytes!("./rt.ts");

    let mut child = Command::new("deno")
        .arg("run")
        .arg("--quiet")
        .arg("--allow-env")
        .arg("--allow-read")
        .arg("--allow-run")
        .arg("-")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    {
        let stdin = child.stdin.as_mut().ok_or(SvelteError::StdinCapture)?;
        stdin.write_all(RT)?;
        stdin.flush()?;
    }

    let output = child.wait_with_output()?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(SvelteError::Deno(format!(
            "Failed to bundle Svelte runtime:\n{stderr}"
        )));
    }

    parse_deno_output(&output.stdout)
}

fn parse_deno_output(output: &[u8]) -> Result<MappedJs, SvelteError> {
    // Header format: "CODE_LEN MAP_LEN\n"
    let header_end = output
        .iter()
        .position(|&b| b == b'\n')
        .ok_or_else(|| SvelteError::ParseOutput("Missing header newline".into()))?;

    let header_str = String::from_utf8(output[0..header_end].to_vec())?;
    let parts: Vec<&str> = header_str.split_whitespace().collect();

    if parts.len() != 2 {
        return Err(SvelteError::ParseOutput("Invalid header format".into()));
    }

    let code_len: usize = parts[0]
        .parse()
        .map_err(|_| SvelteError::ParseOutput("Invalid code length".into()))?;
    let map_len: usize = parts[1]
        .parse()
        .map_err(|_| SvelteError::ParseOutput("Invalid map length".into()))?;

    let body_start = header_end + 1;
    if output.len() < body_start + code_len + map_len {
        return Err(SvelteError::ParseOutput("Incomplete data".into()));
    }

    let code_bytes = &output[body_start..body_start + code_len];
    let map_bytes = &output[body_start + code_len..body_start + code_len + map_len];

    Ok(MappedJs {
        code: String::from_utf8(code_bytes.to_vec())?,
        map: map_bytes.to_vec(),
    })
}