Skip to main content

euv_docs/bundle/
fn.rs

1use super::*;
2
3/// Escapes minimal HTML attribute/text characters (`&`, `<`, `>`, `"`) for generated WASM shell HTML.
4///
5/// # Arguments
6///
7/// - `&str` - Raw UTF-8 string.
8///
9/// # Returns
10///
11/// - `String` - Escaped HTML-safe string.
12fn escape_bundle_html(raw: &str) -> String {
13    let mut out: String = String::with_capacity(raw.len());
14    for ch in raw.chars() {
15        match ch {
16            '&' => out.push_str(BUNDLE_ESC_AMP),
17            '<' => out.push_str(BUNDLE_ESC_LT),
18            '>' => out.push_str(BUNDLE_ESC_GT),
19            '"' => out.push_str(BUNDLE_ESC_QUOT),
20            _ => out.push(ch),
21        }
22    }
23    out
24}
25
26/// Escapes a filesystem path for inclusion inside a TOML double-quoted string literal.
27///
28/// # Arguments
29///
30/// - `&Path` - Filesystem path.
31///
32/// # Returns
33///
34/// - `String` - TOML-escaped path string.
35fn toml_path_string(path: &Path) -> String {
36    path.display()
37        .to_string()
38        .replace('\\', "\\\\")
39        .replace('"', "\\\"")
40}
41
42/// Generates the standalone wrapper crate `Cargo.toml` referencing the active `euv-docs` source or published crate version.
43///
44/// # Arguments
45///
46/// - `&Path` - Local `euv-docs` crate manifest directory resolved at compile time.
47///
48/// # Returns
49///
50/// - `String` - Complete standalone wrapper `Cargo.toml` contents.
51fn render_wrapper_cargo_toml(manifest_dir: &Path) -> String {
52    let pkg_ver: &str = env!("CARGO_PKG_VERSION");
53    let has_local_crate: bool = manifest_dir.join(BUNDLE_CARGO_TOML).is_file();
54    let workspace_root: Option<&Path> = manifest_dir.parent().filter(|parent: &&Path| {
55        parent.join(BUNDLE_CARGO_TOML).is_file()
56            && parent
57                .join(BUNDLE_DIR_CORE)
58                .join(BUNDLE_CARGO_TOML)
59                .is_file()
60            && parent.join(BUNDLE_DIR_UI).join(BUNDLE_CARGO_TOML).is_file()
61    });
62    let mut toml: String = String::with_capacity(1024);
63    let _: fmt::Result = writeln!(toml, "[workspace]\n");
64    let _: fmt::Result = writeln!(toml, "[package]");
65    let _: fmt::Result = writeln!(toml, "name = \"{BUNDLE_CRATE_NAME}\"");
66    let _: fmt::Result = writeln!(toml, "version = \"{pkg_ver}\"");
67    let _: fmt::Result = writeln!(toml, "edition = \"2024\"\n");
68    let _: fmt::Result = writeln!(toml, "[lib]");
69    let _: fmt::Result = writeln!(toml, "crate-type = [\"cdylib\"]\n");
70    let _: fmt::Result = writeln!(toml, "[dependencies]");
71    if has_local_crate {
72        let docs_path: String = toml_path_string(manifest_dir);
73        let _: fmt::Result = writeln!(toml, "euv-docs = {{ path = \"{docs_path}\" }}");
74    } else {
75        let _: fmt::Result = writeln!(toml, "euv-docs = \"={pkg_ver}\"");
76    }
77    let _: fmt::Result = writeln!(toml, "wasm-bindgen = \"{BUNDLE_WASM_BINDGEN_VER}\"\n");
78    if let Some(ws_root) = workspace_root {
79        let root_p: String = toml_path_string(ws_root);
80        let core_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_CORE));
81        let macros_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_MACROS));
82        let ui_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_UI));
83        let docs_p: String = toml_path_string(manifest_dir);
84        let _: fmt::Result = writeln!(toml, "[patch.crates-io]");
85        let _: fmt::Result = writeln!(toml, "euv = {{ path = \"{root_p}\" }}");
86        let _: fmt::Result = writeln!(toml, "euv-core = {{ path = \"{core_p}\" }}");
87        let _: fmt::Result = writeln!(toml, "euv-macros = {{ path = \"{macros_p}\" }}");
88        let _: fmt::Result = writeln!(toml, "euv-ui = {{ path = \"{ui_p}\" }}");
89        let _: fmt::Result = writeln!(toml, "euv-docs = {{ path = \"{docs_p}\" }}\n");
90    }
91    let _: fmt::Result = writeln!(toml, "[profile.release]");
92    let _: fmt::Result = writeln!(toml, "opt-level = \"z\"");
93    let _: fmt::Result = writeln!(toml, "lto = true");
94    let _: fmt::Result = writeln!(toml, "codegen-units = 1");
95    let _: fmt::Result = writeln!(toml, "panic = \"abort\"");
96    let _: fmt::Result = writeln!(toml, "strip = \"debuginfo\"\n");
97    let _: fmt::Result = writeln!(toml, "[package.metadata.wasm-pack.profile.release]");
98    let _: fmt::Result = writeln!(toml, "wasm-opt = false");
99    toml
100}
101
102/// Checks whether a filename carries a forbidden external script or stylesheet suffix (`.js`, `.mjs`, `.css`).
103///
104/// # Arguments
105///
106/// - `&Path` - Candidate file path.
107///
108/// # Returns
109///
110/// - `bool` - `true` when the file must be excluded from the zero-JS/zero-CSS artifact tree.
111fn is_forbidden_asset_file(path: &Path) -> bool {
112    let lower: String = path
113        .file_name()
114        .map(|s: &OsStr| s.to_string_lossy().to_ascii_lowercase())
115        .unwrap_or_default();
116    lower.ends_with(BUNDLE_JS_EXT)
117        || lower.ends_with(BUNDLE_MJS_EXT)
118        || lower.ends_with(BUNDLE_CSS_EXT)
119        || BUNDLE_SKIP_FILES
120            .iter()
121            .any(|skip: &&str| lower.eq_ignore_ascii_case(skip))
122}
123
124/// Recursively copies `src` into `dst`, dereferencing directory and file symlinks into real files while omitting forbidden script/CSS/font trees.
125///
126/// # Arguments
127///
128/// - `&Path` - Source directory (may be a symlink).
129/// - `&Path` - Destination directory.
130/// - `bool` - Whether this call is at the top level of `public/`.
131///
132/// # Returns
133///
134/// - `io::Result<()>` - Copy result.
135fn copy_public_tree_real(src: &Path, dst: &Path, is_top_level: bool) -> io::Result<()> {
136    fs::create_dir_all(dst)?;
137    for entry_res in fs::read_dir(src)? {
138        let entry: DirEntry = entry_res?;
139        let file_name: OsString = entry.file_name();
140        let name_str: Cow<'_, str> = file_name.to_string_lossy();
141        if name_str.starts_with('.') {
142            continue;
143        }
144        let path: PathBuf = entry.path();
145        if path.is_dir() {
146            if is_top_level
147                && BUNDLE_FORBIDDEN_DIRS
148                    .iter()
149                    .any(|f: &&str| name_str.eq_ignore_ascii_case(f))
150            {
151                continue;
152            }
153            copy_public_tree_real(&path, &dst.join(&file_name), false)?;
154        } else if path.is_file() && !is_forbidden_asset_file(&path) {
155            let target: PathBuf = dst.join(&file_name);
156            let resolved_src: PathBuf = fs::canonicalize(&path).unwrap_or(path);
157            let _: u64 = fs::copy(&resolved_src, &target)?;
158        }
159    }
160    Ok(())
161}
162
163/// Copies `<src_dir>/public/` (or fallback `<src_dir>/../public/`) into `out_dir/` as real non-symlink files.
164///
165/// # Arguments
166///
167/// - `&Path` - Documentation Markdown source directory.
168/// - `&Path` - Root build output directory.
169///
170/// # Returns
171///
172/// - `io::Result<()>` - Copy result.
173fn copy_site_public_assets(src_dir: &Path, out_dir: &Path) -> io::Result<()> {
174    let direct_public: PathBuf = src_dir.join(BUNDLE_PUBLIC_DIR);
175    if direct_public.is_dir() {
176        return copy_public_tree_real(&direct_public, out_dir, true);
177    }
178    if let Some(parent) = src_dir.parent() {
179        let parent_public: PathBuf = parent.join(BUNDLE_PUBLIC_DIR);
180        if parent_public.is_dir() {
181            return copy_public_tree_real(&parent_public, out_dir, true);
182        }
183    }
184    Ok(())
185}
186
187/// Strips ES module `export` statements from `wasm-bindgen`'s generated glue script and rewrites the `.wasm` URL to `./pkg/<wasm_file>`.
188///
189/// # Arguments
190///
191/// - `&str` - Raw `wasm-bindgen` web-target JS glue contents.
192/// - `&str` - Exact `<name>_bg.wasm` filename.
193///
194/// # Returns
195///
196/// - `String` - Clean inline ES module script ready to embed inside `<script type="module">`.
197pub fn transform_wasm_glue_inline(raw_js: &str, wasm_file: &str) -> String {
198    let single_pat: String = format!("new URL('{wasm_file}', import.meta.url)");
199    let double_pat: String = format!("new URL(\"{wasm_file}\", import.meta.url)");
200    let target_ref: String = format!("'./pkg/{wasm_file}'");
201    let rewritten: String = raw_js
202        .replace(&single_pat, &target_ref)
203        .replace(&double_pat, &target_ref);
204    let mut out: String = String::with_capacity(rewritten.len());
205    for line in rewritten.lines() {
206        let trimmed: &str = line.trim_start();
207        if trimmed.starts_with(BUNDLE_EXPORT_BRACE) || trimmed.starts_with(BUNDLE_EXPORT_DEFAULT) {
208            continue;
209        }
210        if let Some(rest) = line.strip_prefix(BUNDLE_EXPORT_PREFIX) {
211            out.push_str(rest);
212        } else {
213            out.push_str(line);
214        }
215        out.push('\n');
216    }
217    out
218}
219
220/// Renders the self-contained zero-JS-file, zero-CSS-file `index.html` / `404.html` shell for a single locale WASM bundle.
221///
222/// # Arguments
223///
224/// - `&str` - BCP 47 HTML language code (for example `"zh-CN"`, `"en-US"`).
225/// - `&str` - Localized site title.
226/// - `&str` - Localized site description meta content.
227/// - `&str` - Transformed inline `wasm-bindgen` loader script.
228/// - `&str` - Exact `<name>_bg.wasm` filename inside `./pkg/`.
229///
230/// # Returns
231///
232/// - `String` - Complete HTML document referencing `./pkg/<wasm_file>` with zero external `.js` or `.css` assets.
233#[must_use]
234pub fn render_wasm_locale_shell_html(
235    lang: &str,
236    title: &str,
237    description: &str,
238    inline_glue: &str,
239    wasm_file: &str,
240) -> String {
241    let safe_title: String = escape_bundle_html(title);
242    let mut html: String = String::with_capacity(
243        inline_glue.len()
244            + safe_title.len() * 2
245            + description.len()
246            + EUV_BRAND_LOGO_DATA_URI.len() * 3
247            + 4096,
248    );
249    html.push_str(BUNDLE_HTML_DOCTYPE_OPEN);
250    html.push_str(&escape_bundle_html(lang));
251    html.push_str(BUNDLE_HTML_HEAD_MID);
252    html.push_str(&escape_bundle_html(description));
253    html.push_str(BUNDLE_HTML_DESC_END);
254    html.push_str(EUV_BRAND_LOGO_DATA_URI);
255    html.push_str(BUNDLE_HTML_ICON_MID);
256    html.push_str(EUV_BRAND_LOGO_DATA_URI);
257    html.push_str(BUNDLE_HTML_TITLE_OPEN);
258    html.push_str(&safe_title);
259    html.push_str(BUNDLE_HTML_STYLE_AND_BODY);
260    html.push_str(EUV_BRAND_LOGO_DATA_URI);
261    html.push_str(BUNDLE_HTML_LOGO_END);
262    html.push_str(&safe_title);
263    html.push_str(BUNDLE_HTML_LOADER_END);
264    html.push_str(inline_glue);
265    html.push_str(BUNDLE_HTML_BOOT_PREFIX);
266    html.push_str(wasm_file);
267    html.push_str(BUNDLE_HTML_BOOT_SUFFIX);
268    html
269}
270
271/// Selects unique locales matching an optional `--locale` filter (prefix, dir, lang, or label).
272///
273/// # Arguments
274///
275/// - `&[DocLocaleConfig]` - Deduplicated locale entries.
276/// - `Option<&str>` - Optional user filter string.
277///
278/// # Returns
279///
280/// - `Vec<DocLocaleConfig>` - Locales scheduled for compilation.
281fn select_locales(unique: &[DocLocaleConfig], filter: Option<&str>) -> Vec<DocLocaleConfig> {
282    let Some(raw_filter) = filter else {
283        return unique.to_vec();
284    };
285    let needle: String = raw_filter.trim().trim_matches('/').to_ascii_lowercase();
286    unique
287        .iter()
288        .filter(|loc: &&DocLocaleConfig| {
289            loc.get_dir().trim().eq_ignore_ascii_case(&needle)
290                || loc
291                    .get_prefix()
292                    .trim_matches('/')
293                    .eq_ignore_ascii_case(&needle)
294                || loc.get_lang().trim().eq_ignore_ascii_case(&needle)
295                || loc
296                    .get_label()
297                    .trim()
298                    .eq_ignore_ascii_case(raw_filter.trim())
299        })
300        .cloned()
301        .collect()
302}
303
304/// Compiles one locale `DocSite` into an independent zero-JS/zero-CSS `euv` + `euv-ui` WebAssembly bundle inside `locale_out`.
305///
306/// # Arguments
307///
308/// - `&DocSite` - Loaded documentation site for this locale.
309/// - `&DocLocaleConfig` - Active locale configuration.
310/// - `&Path` - Output directory for this locale (`<out>/` for root or `<out>/<dir>/`).
311/// - `&Path` - Shared wrapper crate working directory.
312/// - `&Path` - Shared `CARGO_TARGET_DIR` caching compiled `wasm32` dependencies across locales.
313/// - `bool` - When `true`, compiles with `wasm-pack --release`; otherwise `--dev`.
314///
315/// # Returns
316///
317/// - `io::Result<()>` - Build result.
318fn compile_locale_wasm_bundle(
319    site: &DocSite,
320    locale: &DocLocaleConfig,
321    locale_out: &Path,
322    builder_dir: &Path,
323    shared_target_dir: &Path,
324    release: bool,
325) -> io::Result<()> {
326    let src_dir: PathBuf = builder_dir.join(BUNDLE_SRC_DIR);
327    fs::create_dir_all(&src_dir)?;
328    let packed: PackedSiteBundle =
329        pack_site_bundle(site).map_err(|err: DocsCodecError| Error::other(err.to_string()))?;
330    fs::write(
331        src_dir.join(BUNDLE_SHELL_JSON_FILE),
332        packed.get_shell_json(),
333    )?;
334    fs::write(
335        src_dir.join(BUNDLE_BODIES_BIN_FILE),
336        packed.get_compressed_bodies(),
337    )?;
338    let safe_dir: String = slugify(locale.get_dir());
339    let suffix: &str = if safe_dir.is_empty() {
340        BUNDLE_DEFAULT_LOCALE_SUFFIX
341    } else {
342        safe_dir.as_str()
343    };
344    let bundle_name: String = format!("{BUNDLE_NAME_PREFIX}{suffix}");
345    let pkg_dir: PathBuf = locale_out.join(BUNDLE_PKG_DIR);
346    fs::create_dir_all(&pkg_dir)?;
347    let mut cmd: Command = Command::new(BUNDLE_WASM_PACK_BIN);
348    let _: &mut Command = cmd
349        .current_dir(builder_dir)
350        .env(BUNDLE_ENV_TARGET_DIR, shared_target_dir)
351        .env_remove(BUNDLE_ENV_RUSTC_WRAPPER)
352        .arg(BUNDLE_ARG_BUILD)
353        .arg(BUNDLE_ARG_TARGET)
354        .arg(BUNDLE_ARG_WEB)
355        .arg(BUNDLE_ARG_NO_TS)
356        .arg(if release {
357            DOCS_FLAG_RELEASE
358        } else {
359            BUNDLE_ARG_DEV
360        })
361        .arg(BUNDLE_ARG_OUT_DIR)
362        .arg(&pkg_dir)
363        .arg(BUNDLE_ARG_OUT_NAME)
364        .arg(&bundle_name);
365    let status: ExitStatus = cmd
366        .status()
367        .map_err(|err: Error| Error::other(format!("{BUNDLE_ERR_WASM_PACK}: {err}")))?;
368    if !status.success() {
369        return Err(Error::other(format!(
370            "{BUNDLE_ERR_WASM_PACK} (locale={} status={status})",
371            locale.get_dir()
372        )));
373    }
374    let wasm_file: String = format!("{bundle_name}{BUNDLE_BG_WASM_SUFFIX}");
375    let js_path: PathBuf = pkg_dir.join(format!("{bundle_name}{BUNDLE_JS_EXT}"));
376    let raw_js: String = fs::read_to_string(&js_path)?;
377    let inline_glue: String = transform_wasm_glue_inline(&raw_js, &wasm_file);
378    let html: String = render_wasm_locale_shell_html(
379        site.resolved_lang(),
380        site.get_title(),
381        site.get_tagline(),
382        &inline_glue,
383        &wasm_file,
384    );
385    fs::write(locale_out.join(BUNDLE_INDEX_HTML), &html)?;
386    fs::write(locale_out.join(BUNDLE_NOT_FOUND_HTML), &html)?;
387    for entry_res in fs::read_dir(&pkg_dir)? {
388        let entry: DirEntry = entry_res?;
389        let path: PathBuf = entry.path();
390        if path.is_file()
391            && path
392                .file_name()
393                .and_then(|s: &OsStr| s.to_str())
394                .is_none_or(|name: &str| name != wasm_file)
395        {
396            fs::remove_file(&path)?;
397        }
398    }
399    Ok(())
400}
401
402/// Builds a complete multi-locale zero-JS/zero-CSS `euv` + `euv-ui` WebAssembly documentation site into `out_dir`.
403///
404/// # Arguments
405///
406/// - `&Path` - Root Markdown source directory (e.g. `docs/`).
407/// - `&Path` - Destination artifact output directory.
408/// - `bool` - When `true`, builds optimized release WASM bundles (`--release`).
409/// - `Option<&str>` - Optional single-locale filter (`dir`, `prefix`, `lang`, or `label`).
410///
411/// # Returns
412///
413/// - `io::Result<GeneratedSiteReport>` - Summary of total built pages and output index path.
414pub fn build_multilocale_wasm_site(
415    src_dir: &Path,
416    out_dir: &Path,
417    release: bool,
418    single_locale: Option<&str>,
419) -> io::Result<GeneratedSiteReport> {
420    let cfg: DocSiteConfig = load_site_config(src_dir)
421        .filter(|c: &DocSiteConfig| !c.get_locales().is_empty())
422        .ok_or_else(|| Error::new(ErrorKind::NotFound, BUNDLE_ERR_NO_LOCALES))?;
423    let unique: Vec<DocLocaleConfig> = unique_locales(cfg.get_locales());
424    let targets: Vec<DocLocaleConfig> = select_locales(&unique, single_locale);
425    if targets.is_empty() {
426        return Err(Error::new(
427            ErrorKind::InvalidInput,
428            BUNDLE_ERR_NO_MATCHING_LOCALE,
429        ));
430    }
431    fs::create_dir_all(out_dir)?;
432    copy_site_public_assets(src_dir, out_dir)?;
433    let abs_out: PathBuf = fs::canonicalize(out_dir).unwrap_or_else(|_| out_dir.to_path_buf());
434    let temp_root: PathBuf = env::temp_dir();
435    let builder_dir: PathBuf = temp_root.join(BUNDLE_BUILDER_DIR);
436    let shared_target_dir: PathBuf = temp_root.join(BUNDLE_TARGET_DIR);
437    fs::create_dir_all(builder_dir.join(BUNDLE_SRC_DIR))?;
438    let manifest_dir: PathBuf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
439    let cargo_toml: String = render_wrapper_cargo_toml(&manifest_dir);
440    let cargo_toml_path: PathBuf = builder_dir.join(BUNDLE_CARGO_TOML);
441    if fs::read_to_string(&cargo_toml_path).ok().as_deref() != Some(cargo_toml.as_str()) {
442        fs::write(&cargo_toml_path, &cargo_toml)?;
443    }
444    let lib_rs_path: PathBuf = builder_dir.join(BUNDLE_SRC_DIR).join(BUNDLE_LIB_RS);
445    if fs::read_to_string(&lib_rs_path).ok().as_deref() != Some(BUNDLE_WRAPPER_LIB_RS) {
446        fs::write(&lib_rs_path, BUNDLE_WRAPPER_LIB_RS)?;
447    }
448    let mut total_pages: usize = 0;
449    for (idx, locale) in targets.iter().enumerate() {
450        let is_root_locale: bool =
451            locale.get_prefix().trim() == "/" || (single_locale.is_some() && idx == 0);
452        let locale_out: PathBuf = if is_root_locale {
453            abs_out.clone()
454        } else {
455            let sub: &str = locale.get_dir().trim().trim_matches('/');
456            abs_out.join(sub)
457        };
458        let site: DocSite = load_locale_site(src_dir, &cfg, locale, Some(&abs_out))?;
459        total_pages += site.get_pages().len();
460        compile_locale_wasm_bundle(
461            &site,
462            locale,
463            &locale_out,
464            &builder_dir,
465            &shared_target_dir,
466            release,
467        )?;
468    }
469    let generated_at: String = Utc::now().to_rfc3339();
470    Ok(GeneratedSiteReport::new(
471        total_pages,
472        generated_at,
473        out_dir.join(BUNDLE_INDEX_HTML).display().to_string(),
474    ))
475}