euv-docs 0.47.1

Cross-platform documentation viewer and static site generator powered by euv and euv-ui.
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
use super::*;

/// Escapes minimal HTML attribute/text characters (`&`, `<`, `>`, `"`) for generated WASM shell HTML.
///
/// # Arguments
///
/// - `&str` - Raw UTF-8 string.
///
/// # Returns
///
/// - `String` - Escaped HTML-safe string.
fn escape_bundle_html(raw: &str) -> String {
    let mut out: String = String::with_capacity(raw.len());
    for ch in raw.chars() {
        match ch {
            '&' => out.push_str(BUNDLE_ESC_AMP),
            '<' => out.push_str(BUNDLE_ESC_LT),
            '>' => out.push_str(BUNDLE_ESC_GT),
            '"' => out.push_str(BUNDLE_ESC_QUOT),
            _ => out.push(ch),
        }
    }
    out
}

/// Escapes a filesystem path for inclusion inside a TOML double-quoted string literal.
///
/// # Arguments
///
/// - `&Path` - Filesystem path.
///
/// # Returns
///
/// - `String` - TOML-escaped path string.
fn toml_path_string(path: &Path) -> String {
    path.display()
        .to_string()
        .replace('\\', "\\\\")
        .replace('"', "\\\"")
}

/// Generates the standalone wrapper crate `Cargo.toml` referencing the active `euv-docs` source or published crate version.
///
/// # Arguments
///
/// - `&Path` - Local `euv-docs` crate manifest directory resolved at compile time.
///
/// # Returns
///
/// - `String` - Complete standalone wrapper `Cargo.toml` contents.
fn render_wrapper_cargo_toml(manifest_dir: &Path) -> String {
    let pkg_ver: &str = env!("CARGO_PKG_VERSION");
    let has_local_crate: bool = manifest_dir.join(BUNDLE_CARGO_TOML).is_file();
    let workspace_root: Option<&Path> = manifest_dir.parent().filter(|parent: &&Path| {
        parent.join(BUNDLE_CARGO_TOML).is_file()
            && parent
                .join(BUNDLE_DIR_CORE)
                .join(BUNDLE_CARGO_TOML)
                .is_file()
            && parent.join(BUNDLE_DIR_UI).join(BUNDLE_CARGO_TOML).is_file()
    });
    let mut toml: String = String::with_capacity(1024);
    let _: fmt::Result = writeln!(toml, "[workspace]\n");
    let _: fmt::Result = writeln!(toml, "[package]");
    let _: fmt::Result = writeln!(toml, "name = \"{BUNDLE_CRATE_NAME}\"");
    let _: fmt::Result = writeln!(toml, "version = \"{pkg_ver}\"");
    let _: fmt::Result = writeln!(toml, "edition = \"2024\"\n");
    let _: fmt::Result = writeln!(toml, "[lib]");
    let _: fmt::Result = writeln!(toml, "crate-type = [\"cdylib\"]\n");
    let _: fmt::Result = writeln!(toml, "[dependencies]");
    if has_local_crate {
        let docs_path: String = toml_path_string(manifest_dir);
        let _: fmt::Result = writeln!(toml, "euv-docs = {{ path = \"{docs_path}\" }}");
    } else {
        let _: fmt::Result = writeln!(toml, "euv-docs = \"={pkg_ver}\"");
    }
    let _: fmt::Result = writeln!(toml, "wasm-bindgen = \"{BUNDLE_WASM_BINDGEN_VER}\"\n");
    if let Some(ws_root) = workspace_root {
        let root_p: String = toml_path_string(ws_root);
        let core_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_CORE));
        let macros_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_MACROS));
        let ui_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_UI));
        let docs_p: String = toml_path_string(manifest_dir);
        let _: fmt::Result = writeln!(toml, "[patch.crates-io]");
        let _: fmt::Result = writeln!(toml, "euv = {{ path = \"{root_p}\" }}");
        let _: fmt::Result = writeln!(toml, "euv-core = {{ path = \"{core_p}\" }}");
        let _: fmt::Result = writeln!(toml, "euv-macros = {{ path = \"{macros_p}\" }}");
        let _: fmt::Result = writeln!(toml, "euv-ui = {{ path = \"{ui_p}\" }}");
        let _: fmt::Result = writeln!(toml, "euv-docs = {{ path = \"{docs_p}\" }}\n");
    }
    let _: fmt::Result = writeln!(toml, "[profile.release]");
    let _: fmt::Result = writeln!(toml, "opt-level = \"z\"");
    let _: fmt::Result = writeln!(toml, "lto = true");
    let _: fmt::Result = writeln!(toml, "codegen-units = 1");
    let _: fmt::Result = writeln!(toml, "panic = \"abort\"");
    let _: fmt::Result = writeln!(toml, "strip = \"debuginfo\"\n");
    let _: fmt::Result = writeln!(toml, "[package.metadata.wasm-pack.profile.release]");
    let _: fmt::Result = writeln!(toml, "wasm-opt = false");
    toml
}

/// Checks whether a filename carries a forbidden external script or stylesheet suffix (`.js`, `.mjs`, `.css`).
///
/// # Arguments
///
/// - `&Path` - Candidate file path.
///
/// # Returns
///
/// - `bool` - `true` when the file must be excluded from the zero-JS/zero-CSS artifact tree.
fn is_forbidden_asset_file(path: &Path) -> bool {
    let lower: String = path
        .file_name()
        .map(|s: &OsStr| s.to_string_lossy().to_ascii_lowercase())
        .unwrap_or_default();
    lower.ends_with(BUNDLE_JS_EXT)
        || lower.ends_with(BUNDLE_MJS_EXT)
        || lower.ends_with(BUNDLE_CSS_EXT)
        || BUNDLE_SKIP_FILES
            .iter()
            .any(|skip: &&str| lower.eq_ignore_ascii_case(skip))
}

/// Recursively copies `src` into `dst`, dereferencing directory and file symlinks into real files while omitting forbidden script/CSS/font trees.
///
/// # Arguments
///
/// - `&Path` - Source directory (may be a symlink).
/// - `&Path` - Destination directory.
/// - `bool` - Whether this call is at the top level of `public/`.
///
/// # Returns
///
/// - `io::Result<()>` - Copy result.
fn copy_public_tree_real(src: &Path, dst: &Path, is_top_level: bool) -> io::Result<()> {
    fs::create_dir_all(dst)?;
    for entry_res in fs::read_dir(src)? {
        let entry: DirEntry = entry_res?;
        let file_name: OsString = entry.file_name();
        let name_str: Cow<'_, str> = file_name.to_string_lossy();
        if name_str.starts_with('.') {
            continue;
        }
        let path: PathBuf = entry.path();
        if path.is_dir() {
            if is_top_level
                && BUNDLE_FORBIDDEN_DIRS
                    .iter()
                    .any(|f: &&str| name_str.eq_ignore_ascii_case(f))
            {
                continue;
            }
            copy_public_tree_real(&path, &dst.join(&file_name), false)?;
        } else if path.is_file() && !is_forbidden_asset_file(&path) {
            let target: PathBuf = dst.join(&file_name);
            let resolved_src: PathBuf = fs::canonicalize(&path).unwrap_or(path);
            let _: u64 = fs::copy(&resolved_src, &target)?;
        }
    }
    Ok(())
}

/// Copies `<src_dir>/public/` (or fallback `<src_dir>/../public/`) into `out_dir/` as real non-symlink files.
///
/// # Arguments
///
/// - `&Path` - Documentation Markdown source directory.
/// - `&Path` - Root build output directory.
///
/// # Returns
///
/// - `io::Result<()>` - Copy result.
fn copy_site_public_assets(src_dir: &Path, out_dir: &Path) -> io::Result<()> {
    let direct_public: PathBuf = src_dir.join(BUNDLE_PUBLIC_DIR);
    if direct_public.is_dir() {
        return copy_public_tree_real(&direct_public, out_dir, true);
    }
    if let Some(parent) = src_dir.parent() {
        let parent_public: PathBuf = parent.join(BUNDLE_PUBLIC_DIR);
        if parent_public.is_dir() {
            return copy_public_tree_real(&parent_public, out_dir, true);
        }
    }
    Ok(())
}

/// Strips ES module `export` statements from `wasm-bindgen`'s generated glue script and rewrites the `.wasm` URL to `./pkg/<wasm_file>`.
///
/// # Arguments
///
/// - `&str` - Raw `wasm-bindgen` web-target JS glue contents.
/// - `&str` - Exact `<name>_bg.wasm` filename.
///
/// # Returns
///
/// - `String` - Clean inline ES module script ready to embed inside `<script type="module">`.
pub fn transform_wasm_glue_inline(raw_js: &str, wasm_file: &str) -> String {
    let single_pat: String = format!("new URL('{wasm_file}', import.meta.url)");
    let double_pat: String = format!("new URL(\"{wasm_file}\", import.meta.url)");
    let target_ref: String = format!("'./pkg/{wasm_file}'");
    let rewritten: String = raw_js
        .replace(&single_pat, &target_ref)
        .replace(&double_pat, &target_ref);
    let mut out: String = String::with_capacity(rewritten.len());
    for line in rewritten.lines() {
        let trimmed: &str = line.trim_start();
        if trimmed.starts_with(BUNDLE_EXPORT_BRACE) || trimmed.starts_with(BUNDLE_EXPORT_DEFAULT) {
            continue;
        }
        if let Some(rest) = line.strip_prefix(BUNDLE_EXPORT_PREFIX) {
            out.push_str(rest);
        } else {
            out.push_str(line);
        }
        out.push('\n');
    }
    out
}

/// Renders the self-contained zero-JS-file, zero-CSS-file `index.html` / `404.html` shell for a single locale WASM bundle.
///
/// # Arguments
///
/// - `&str` - BCP 47 HTML language code (for example `"zh-CN"`, `"en-US"`).
/// - `&str` - Localized site title.
/// - `&str` - Localized site description meta content.
/// - `&str` - Transformed inline `wasm-bindgen` loader script.
/// - `&str` - Exact `<name>_bg.wasm` filename inside `./pkg/`.
///
/// # Returns
///
/// - `String` - Complete HTML document referencing `./pkg/<wasm_file>` with zero external `.js` or `.css` assets.
#[must_use]
pub fn render_wasm_locale_shell_html(
    lang: &str,
    title: &str,
    description: &str,
    inline_glue: &str,
    wasm_file: &str,
) -> String {
    let mut html: String =
        String::with_capacity(inline_glue.len() + title.len() + description.len() + 1024);
    html.push_str(BUNDLE_HTML_DOCTYPE_OPEN);
    html.push_str(&escape_bundle_html(lang));
    html.push_str(BUNDLE_HTML_HEAD_MID);
    html.push_str(&escape_bundle_html(description));
    html.push_str(BUNDLE_HTML_DESC_END);
    html.push_str(&escape_bundle_html(title));
    html.push_str(BUNDLE_HTML_STYLE_AND_BODY);
    html.push_str(inline_glue);
    html.push_str(BUNDLE_HTML_BOOT_PREFIX);
    html.push_str(wasm_file);
    html.push_str(BUNDLE_HTML_BOOT_SUFFIX);
    html
}

/// Selects unique locales matching an optional `--locale` filter (prefix, dir, lang, or label).
///
/// # Arguments
///
/// - `&[DocLocaleConfig]` - Deduplicated locale entries.
/// - `Option<&str>` - Optional user filter string.
///
/// # Returns
///
/// - `Vec<DocLocaleConfig>` - Locales scheduled for compilation.
fn select_locales(unique: &[DocLocaleConfig], filter: Option<&str>) -> Vec<DocLocaleConfig> {
    let Some(raw_filter) = filter else {
        return unique.to_vec();
    };
    let needle: String = raw_filter.trim().trim_matches('/').to_ascii_lowercase();
    unique
        .iter()
        .filter(|loc: &&DocLocaleConfig| {
            loc.get_dir().trim().eq_ignore_ascii_case(&needle)
                || loc
                    .get_prefix()
                    .trim_matches('/')
                    .eq_ignore_ascii_case(&needle)
                || loc.get_lang().trim().eq_ignore_ascii_case(&needle)
                || loc
                    .get_label()
                    .trim()
                    .eq_ignore_ascii_case(raw_filter.trim())
        })
        .cloned()
        .collect()
}

/// Compiles one locale `DocSite` into an independent zero-JS/zero-CSS `euv` + `euv-ui` WebAssembly bundle inside `locale_out`.
///
/// # Arguments
///
/// - `&DocSite` - Loaded documentation site for this locale.
/// - `&DocLocaleConfig` - Active locale configuration.
/// - `&Path` - Output directory for this locale (`<out>/` for root or `<out>/<dir>/`).
/// - `&Path` - Shared wrapper crate working directory.
/// - `&Path` - Shared `CARGO_TARGET_DIR` caching compiled `wasm32` dependencies across locales.
/// - `bool` - When `true`, compiles with `wasm-pack --release`; otherwise `--dev`.
///
/// # Returns
///
/// - `io::Result<()>` - Build result.
fn compile_locale_wasm_bundle(
    site: &DocSite,
    locale: &DocLocaleConfig,
    locale_out: &Path,
    builder_dir: &Path,
    shared_target_dir: &Path,
    release: bool,
) -> io::Result<()> {
    let src_dir: PathBuf = builder_dir.join(BUNDLE_SRC_DIR);
    fs::create_dir_all(&src_dir)?;
    let packed: PackedSiteBundle =
        pack_site_bundle(site).map_err(|err: DocsCodecError| Error::other(err.to_string()))?;
    fs::write(
        src_dir.join(BUNDLE_SHELL_JSON_FILE),
        packed.get_shell_json(),
    )?;
    fs::write(
        src_dir.join(BUNDLE_BODIES_BIN_FILE),
        packed.get_compressed_bodies(),
    )?;
    let safe_dir: String = slugify(locale.get_dir());
    let suffix: &str = if safe_dir.is_empty() {
        BUNDLE_DEFAULT_LOCALE_SUFFIX
    } else {
        safe_dir.as_str()
    };
    let bundle_name: String = format!("{BUNDLE_NAME_PREFIX}{suffix}");
    let pkg_dir: PathBuf = locale_out.join(BUNDLE_PKG_DIR);
    fs::create_dir_all(&pkg_dir)?;
    let mut cmd: Command = Command::new(BUNDLE_WASM_PACK_BIN);
    let _: &mut Command = cmd
        .current_dir(builder_dir)
        .env(BUNDLE_ENV_TARGET_DIR, shared_target_dir)
        .env_remove(BUNDLE_ENV_RUSTC_WRAPPER)
        .arg(BUNDLE_ARG_BUILD)
        .arg(BUNDLE_ARG_TARGET)
        .arg(BUNDLE_ARG_WEB)
        .arg(BUNDLE_ARG_NO_TS)
        .arg(if release {
            DOCS_FLAG_RELEASE
        } else {
            BUNDLE_ARG_DEV
        })
        .arg(BUNDLE_ARG_OUT_DIR)
        .arg(&pkg_dir)
        .arg(BUNDLE_ARG_OUT_NAME)
        .arg(&bundle_name);
    let status: ExitStatus = cmd
        .status()
        .map_err(|err: Error| Error::other(format!("{BUNDLE_ERR_WASM_PACK}: {err}")))?;
    if !status.success() {
        return Err(Error::other(format!(
            "{BUNDLE_ERR_WASM_PACK} (locale={} status={status})",
            locale.get_dir()
        )));
    }
    let wasm_file: String = format!("{bundle_name}{BUNDLE_BG_WASM_SUFFIX}");
    let js_path: PathBuf = pkg_dir.join(format!("{bundle_name}{BUNDLE_JS_EXT}"));
    let raw_js: String = fs::read_to_string(&js_path)?;
    let inline_glue: String = transform_wasm_glue_inline(&raw_js, &wasm_file);
    let html: String = render_wasm_locale_shell_html(
        site.resolved_lang(),
        site.get_title(),
        site.get_tagline(),
        &inline_glue,
        &wasm_file,
    );
    fs::write(locale_out.join(BUNDLE_INDEX_HTML), &html)?;
    fs::write(locale_out.join(BUNDLE_NOT_FOUND_HTML), &html)?;
    for entry_res in fs::read_dir(&pkg_dir)? {
        let entry: DirEntry = entry_res?;
        let path: PathBuf = entry.path();
        if path.is_file()
            && path
                .file_name()
                .and_then(|s: &OsStr| s.to_str())
                .is_none_or(|name: &str| name != wasm_file)
        {
            fs::remove_file(&path)?;
        }
    }
    Ok(())
}

/// Builds a complete multi-locale zero-JS/zero-CSS `euv` + `euv-ui` WebAssembly documentation site into `out_dir`.
///
/// # Arguments
///
/// - `&Path` - Root Markdown source directory (e.g. `docs/`).
/// - `&Path` - Destination artifact output directory.
/// - `bool` - When `true`, builds optimized release WASM bundles (`--release`).
/// - `Option<&str>` - Optional single-locale filter (`dir`, `prefix`, `lang`, or `label`).
///
/// # Returns
///
/// - `io::Result<GeneratedSiteReport>` - Summary of total built pages and output index path.
pub fn build_multilocale_wasm_site(
    src_dir: &Path,
    out_dir: &Path,
    release: bool,
    single_locale: Option<&str>,
) -> io::Result<GeneratedSiteReport> {
    let cfg: DocSiteConfig = load_site_config(src_dir)
        .filter(|c: &DocSiteConfig| !c.get_locales().is_empty())
        .ok_or_else(|| Error::new(ErrorKind::NotFound, BUNDLE_ERR_NO_LOCALES))?;
    let unique: Vec<DocLocaleConfig> = unique_locales(cfg.get_locales());
    let targets: Vec<DocLocaleConfig> = select_locales(&unique, single_locale);
    if targets.is_empty() {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            BUNDLE_ERR_NO_MATCHING_LOCALE,
        ));
    }
    fs::create_dir_all(out_dir)?;
    copy_site_public_assets(src_dir, out_dir)?;
    let abs_out: PathBuf = fs::canonicalize(out_dir).unwrap_or_else(|_| out_dir.to_path_buf());
    let temp_root: PathBuf = env::temp_dir();
    let builder_dir: PathBuf = temp_root.join(BUNDLE_BUILDER_DIR);
    let shared_target_dir: PathBuf = temp_root.join(BUNDLE_TARGET_DIR);
    fs::create_dir_all(builder_dir.join(BUNDLE_SRC_DIR))?;
    let manifest_dir: PathBuf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let cargo_toml: String = render_wrapper_cargo_toml(&manifest_dir);
    let cargo_toml_path: PathBuf = builder_dir.join(BUNDLE_CARGO_TOML);
    if fs::read_to_string(&cargo_toml_path).ok().as_deref() != Some(cargo_toml.as_str()) {
        fs::write(&cargo_toml_path, &cargo_toml)?;
    }
    let lib_rs_path: PathBuf = builder_dir.join(BUNDLE_SRC_DIR).join(BUNDLE_LIB_RS);
    if fs::read_to_string(&lib_rs_path).ok().as_deref() != Some(BUNDLE_WRAPPER_LIB_RS) {
        fs::write(&lib_rs_path, BUNDLE_WRAPPER_LIB_RS)?;
    }
    let mut total_pages: usize = 0;
    for (idx, locale) in targets.iter().enumerate() {
        let is_root_locale: bool =
            locale.get_prefix().trim() == "/" || (single_locale.is_some() && idx == 0);
        let locale_out: PathBuf = if is_root_locale {
            abs_out.clone()
        } else {
            let sub: &str = locale.get_dir().trim().trim_matches('/');
            abs_out.join(sub)
        };
        let site: DocSite = load_locale_site(src_dir, &cfg, locale, Some(&abs_out))?;
        total_pages += site.get_pages().len();
        compile_locale_wasm_bundle(
            &site,
            locale,
            &locale_out,
            &builder_dir,
            &shared_target_dir,
            release,
        )?;
    }
    let generated_at: String = Utc::now().to_rfc3339();
    Ok(GeneratedSiteReport::new(
        total_pages,
        generated_at,
        out_dir.join(BUNDLE_INDEX_HTML).display().to_string(),
    ))
}