forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

editor_assets.rs60 lines, 2.2 KiBHistoryRawDownload
1//! The editor bundle's content-hashed file names, read from `assets/editor.manifest`.
2//!
3//! The build tool writes `editor-<16 hex>.js` and `editor-<16 hex>.wasm` into `assets/`
4//! and a manifest with two lines, `js=<name>` and `wasm=<name>`.
5
6/// The names of the current editor files, as served at the site root.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct EditorAssets {
9 pub js: String,
10 pub wasm: String,
11}
12
13/// The manifest, relative to the working directory like `public_dir`.
14const MANIFEST: &str = "assets/editor.manifest";
15
16impl EditorAssets {
17 /// Reads the manifest. Returns `None` when it is missing or malformed, logging why.
18 pub fn load() -> Option<EditorAssets> {
19 let text = match std::fs::read_to_string(MANIFEST) {
20 Ok(text) => text,
21 Err(err) => {
22 eprintln!("editor assets: cannot read {MANIFEST}: {err}; editor not preloaded");
23 return None;
24 }
25 };
26 let mut js = None;
27 let mut wasm = None;
28 for line in text.lines() {
29 match line.split_once('=') {
30 Some(("js", name)) => js = Some(name.trim().to_owned()),
31 Some(("wasm", name)) => wasm = Some(name.trim().to_owned()),
32 _ => {}
33 }
34 }
35 match (js, wasm) {
36 (Some(js), Some(wasm)) if content_type(&js) == Some("text/javascript") && content_type(&wasm) == Some("application/wasm") => {
37 Some(EditorAssets { js, wasm })
38 }
39 _ => {
40 eprintln!("editor assets: {MANIFEST} must name a hashed js and wasm file; editor not preloaded");
41 None
42 }
43 }
44 }
45}
46
47/// The content type for a content-hashed editor file name (`editor-<16 hex>.js` or
48/// `editor-<16 hex>.wasm`), or `None` for any other name.
49pub fn content_type(name: &str) -> Option<&'static str> {
50 let (stem, ext) = name.rsplit_once('.')?;
51 let hash = stem.strip_prefix("editor-")?;
52 if hash.len() != 16 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
53 return None;
54 }
55 match ext {
56 "js" => Some("text/javascript"),
57 "wasm" => Some("application/wasm"),
58 _ => None,
59 }
60}