Skip to main content

htmlpacker/
packer.rs

1/*
2* packer.rs
3*
4* the main packing logic
5*/
6
7/*
8This is the main of the program that packs everything together
9
10we fetch scripts from here
11might turn into some type of cli tool that you use with yaml files
12
13local/remote: css, js, text, png, etc
14pack it up
15
16compress it with brotli
17then encode it in base64
18*/
19
20
21use crate::config::{
22    AssetSource, 
23    WasmModule, 
24    CompressionType, 
25    PackerConfig,
26};
27use crate::cli::{YamlRoot, Cli};
28use crate::encoder::{Base};
29use crate::encoder;
30use crate::wasmbuilder;
31use crate::html;
32use crate::fetcher;
33
34//
35use std::error::Error;
36use std::fs;
37use std::path::PathBuf;
38
39use clap::{Parser};
40use base64::prelude::*;
41use sha2::{Sha256, Digest};
42
43// runtime assets on default
44const RUNTIME_ICON: &str = include_str!("../core/icon.svg");
45const RUNTIME_CORE_JS: &str = include_str!("../core/core.js");
46const RUNTIME_DECODER_JS: &str = include_str!("../core/wasm_decoder.js");
47const RUNTIME_DECODER_WASM: &[u8] = include_bytes!("../core/wasm_decoder_bg.wasm");
48
49// read yaml from file
50// set config from yaml
51// need serde structs
52
53// the basic run for API
54pub async fn run() -> Result<(), Box<dyn Error>> {
55    // parse CLI
56    let cli = Cli::parse();
57    println!("Config: {}", cli.config.display());
58    println!("Output: {}", cli.output.display());
59    
60    let config = load_config(cli.config).await?;
61    pack(config, cli.output).await?;
62    Ok(())
63}
64
65// loads config from given path, serde yaml->config magic
66pub async fn load_config(
67    config_path: PathBuf,
68) -> Result<PackerConfig, Box<dyn Error>> {
69    let yaml_text = fs::read_to_string(config_path)?;
70    let yaml_root: YamlRoot = serde_yaml::from_str(&yaml_text)?;
71    println!("Extracted yaml");
72    //println!("{:?}", yaml_text);
73    //println!("{:#?}", &yaml_root.pack);
74    let config = crate::cli::set_config_from_yaml(yaml_root.pack).await?;
75    println!("Loaded config from yaml");
76    Ok(config)
77}
78
79// extremely wonky
80fn default_runtime(
81//    config: &mut PackerConfig,
82    icons: &mut Vec<String>,
83    scripts: &mut Vec<String>,
84    bin: &mut Vec<Base>,
85) {
86    println!("Default runtime is enabled. \
87        Adding icon, core.js and wasm_decoder");
88
89    // favicon
90    let encoded_icon_string = 
91        BASE64_STANDARD.encode(RUNTIME_ICON.as_bytes());
92    icons.insert(0, encoded_icon_string);
93
94    // default scripts
95    scripts.push(RUNTIME_DECODER_JS.to_string());
96    scripts.push(RUNTIME_CORE_JS.to_string());
97
98    // decoder wasm binary
99    let wasm_hash = Sha256::digest(RUNTIME_DECODER_WASM);
100    let wasm_hash_string = format!("{:x}", wasm_hash);
101    let wasm_encoded_text = BASE64_STANDARD.encode(RUNTIME_DECODER_WASM);
102    let decoder_module = Base {
103        id: "bin-wasm-decoder".to_string(),
104        hash: wasm_hash_string,
105        text: wasm_encoded_text,
106    };
107
108    bin.push(decoder_module);
109}
110
111// have to separate pack from parse cli
112// pack takes in a config and an output filename
113pub async fn pack(
114    config: PackerConfig,
115    output: PathBuf,
116) -> Result<(), Box<dyn Error>> {
117    // make sure to compile our wasm binaries and js glue first
118    // how to disable this if already done?
119    if let Some(ref modules) = config.wasm {
120        wasmbuilder::compile_wasm_modules(modules).await?;
121    }
122
123    
124    // favicon multiple allowed but forcing only one supported rn
125    let icon_sources = match config.favicon {
126        Some(source) => get_icons(source).await?,
127        None => vec![],
128    };
129    // this is sort of good but also SLOP
130    let mut icons = vec![];
131    if !icon_sources.is_empty() {
132        icons.push(icon_sources[0].clone());
133    }
134    
135    //styles as one big string
136    //let styles_text = get_styles_text(config.styles).await?;
137    let styles_text = match config.styles {
138        Some(source) => get_styles_text(source).await?,
139        None => "".to_string(),
140    };
141    
142    // scripts as a vec
143    let mut scripts = match config.scripts {
144        Some(source) => get_sources(source).await?,
145        None => vec![],
146    };
147
148    // this is super brittle
149    // we don't do it
150    // just add wasm_decoder pkg to core
151    /*
152    if !scripts.is_empty() {
153        // rename wasm_bindgen so that we don't have double definition conflicts
154        scripts[0] = scripts[0].replace("wasm_bindgen", "wasm_decoder");
155    }
156    */
157
158    // binary wasm files
159    //let bin = get_wasm(config.wasm)?;
160    let mut bin = match config.wasm {
161        Some(source) => get_wasm(source)?,
162        None => vec![],
163    };
164
165    // set default runtime for the given configuration
166    if config.runtime.enabled {
167        default_runtime(
168            &mut icons,
169            &mut scripts,
170            &mut bin,
171        );
172    }
173
174
175    let markup = html::page(
176        styles_text,
177        icons,
178        scripts,
179        bin,
180    );
181
182    let html = markup.into_string();
183    //println!("html: {}", html);
184    html::save_html(html, output)?;
185
186    Ok(())
187}
188
189async fn get_icons(
190    icon_sources: Vec<AssetSource> 
191) -> Result<Vec<String>, Box<dyn Error>> {
192    let mut icons: Vec<String> = vec![];
193    for icon in icon_sources {
194        // we get the path of the file
195        // must be local (for now)
196        let path_str = match icon {
197            AssetSource::Local(path) => path.to_str().ok_or("Invalid favicon path")?.to_string(),
198            AssetSource::Remote(_) => return Err("Remote favicons not yet supported".into()),
199        };
200        // then we get the buffer and encode
201        let encoded_icon = crate::encoder::encode_base64(&path_str, "favicon")?;
202        icons.push(encoded_icon.text);
203    }
204    Ok(icons)
205}
206
207// append each css file together
208async fn get_styles_text(
209    style_sources: Vec<AssetSource>
210) -> Result<String, Box<dyn Error>> {
211    //let styles_text = fetcher::get_css_string(css_urls).await?;
212    // init empty string
213    let mut styles_text = String::from("");
214    for source in style_sources {
215        let text = match source {
216            AssetSource::Local(path) => fetcher::get_local_file(&path)?,
217            AssetSource::Remote(url) => fetcher::get_remote_file(url).await?,
218        };
219        // append
220        styles_text.push_str(&text);
221    }
222    Ok(styles_text)
223}
224
225async fn get_sources(
226    sources: Vec<AssetSource>
227) -> Result<Vec<String>, Box<dyn Error>> {
228    let mut source_text_list: Vec<String> = vec![];
229    for source in sources {
230        let text = match source {
231            AssetSource::Local(path) => fetcher::get_local_file(&path)?,
232            AssetSource::Remote(url) => fetcher::get_remote_file(url).await?,
233        };
234        //append
235        source_text_list.push(text);
236    }
237    Ok(source_text_list)
238}
239
240fn get_wasm(
241    wasm_modules: Vec<WasmModule> 
242) -> Result<Vec<Base>, Box<dyn Error>> {
243    let mut bin: Vec<Base> = vec![];
244    for module in wasm_modules {
245        // we get the path of the file
246        // must be local (for now)
247        let path_str = match module.source{
248            AssetSource::Local(path) => path.to_str().ok_or("Invalid WASM path")?.to_string(),
249            AssetSource::Remote(_) => return Err("Remote WASM modules not yet supported".into()),
250        };
251        // then we get the buffer and encode
252        let encoded_module = match module.compression {
253            CompressionType::Brotli => encoder::encode_brotli_base64(&path_str, &module.id)?,
254            CompressionType::None => encoder::encode_base64(&path_str, &module.id)?,
255        };
256        bin.push(encoded_module);
257    }
258    Ok(bin)
259}
260
261
262
263
264    /*
265    let core_icon = vec![
266        AssetSource::Local(PathBuf::from(RUNTIME_ICON)),
267    ];
268    
269    for source in core_icon {
270        config.favicon.get_or_insert_with(Vec::new).push(source);
271    }
272
273    let core_js = vec![
274        AssetSource::Local(PathBuf::from(RUNTIME_DECODER_JS)),
275        AssetSource::Local(PathBuf::from(RUNTIME_CORE_JS)),
276    ];
277
278    for source in core_js {
279        config.scripts.get_or_insert_with(Vec::new).push(source);
280    }
281
282    let core_wasm = vec![
283        WasmModule {
284            compile_wasm: false,
285            source: AssetSource::Local(PathBuf::from(RUNTIME_DECODER_WASM)),
286            id: "bin-wasm-decoder".into(),
287            compression: CompressionType::None,
288        },
289    ];
290
291    for source in core_wasm {
292        config.wasm.get_or_insert_with(Vec::new).push(source);
293    }
294    */