Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added hashes generated from cargo-leptos #2373

Merged
merged 2 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 53 additions & 5 deletions integrations/utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use futures::{Stream, StreamExt};
use leptos::{nonce::use_nonce, use_context, RuntimeId};
use leptos_config::LeptosOptions;
use leptos_meta::MetaContext;
use std::borrow::Cow;
use std::{borrow::Cow, collections::HashMap, env, fs};

extern crate tracing;

Expand Down Expand Up @@ -103,15 +103,23 @@ pub fn html_parts_separated(
} else {
"() => mod.hydrate()"
};

let (js_hash, wasm_hash, css_hash) = get_hashes(&options);

let head = head.replace(
&format!("{output_name}.css"),
&format!("{output_name}{css_hash}.css"),
);

let head = format!(
r#"<!DOCTYPE html>
<html{html_metadata}>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
{head}
<link rel="modulepreload" href="{pkg_path}/{output_name}.js"{nonce}>
<link rel="preload" href="{pkg_path}/{wasm_output_name}.wasm" as="fetch" type="application/wasm" crossorigin=""{nonce}>
<link rel="modulepreload" href="{pkg_path}/{output_name}{js_hash}.js"{nonce}>
<link rel="preload" href="{pkg_path}/{wasm_output_name}{wasm_hash}.wasm" as="fetch" type="application/wasm" crossorigin=""{nonce}>
<script type="module"{nonce}>
function idle(c) {{
if ("requestIdleCallback" in window) {{
Expand All @@ -121,9 +129,9 @@ pub fn html_parts_separated(
}}
}}
idle(() => {{
import('{pkg_path}/{output_name}.js')
import('{pkg_path}/{output_name}{js_hash}.js')
.then(mod => {{
mod.default('{pkg_path}/{wasm_output_name}.wasm').then({import_callback});
mod.default('{pkg_path}/{wasm_output_name}{wasm_hash}.wasm').then({import_callback});
}})
}});
</script>
Expand All @@ -134,6 +142,46 @@ pub fn html_parts_separated(
(head, tail)
}

#[tracing::instrument(level = "trace", fields(error), skip_all)]
fn get_hashes(options: &LeptosOptions) -> (String, String, String) {
let mut ext_to_hash = HashMap::from([
("js".to_string(), "".to_string()),
("wasm".to_string(), "".to_string()),
("css".to_string(), "".to_string()),
]);

if options.frontend_files_content_hashes {
let hash_path = env::current_exe()
.map(|path| {
path.parent().map(|p| p.to_path_buf()).unwrap_or_default()
})
.unwrap_or_default()
.join(&options.hash_file);

if hash_path.exists() {
let hashes = fs::read_to_string(&hash_path)
.expect("failed to read hash file");
for line in hashes.lines() {
let line = line.trim();
if !line.is_empty() {
if let Some((k, v)) = line.split_once(':') {
ext_to_hash.insert(
k.trim().to_string(),
format!(".{}", v.trim()),
);
}
}
}
}
}

(
ext_to_hash["js"].clone(),
ext_to_hash["wasm"].clone(),
ext_to_hash["css"].clone(),
)
}

#[tracing::instrument(level = "trace", fields(error), skip_all)]
pub async fn build_async_response(
stream: impl Stream<Item = String> + 'static,
Expand Down
8 changes: 7 additions & 1 deletion leptos_config/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{net::AddrParseError, num::ParseIntError};
use std::{net::AddrParseError, num::ParseIntError, str::ParseBoolError};
use thiserror::Error;

#[derive(Debug, Error, Clone)]
Expand Down Expand Up @@ -31,3 +31,9 @@ impl From<AddrParseError> for LeptosConfigError {
Self::ConfigError(e.to_string())
}
}

impl From<ParseBoolError> for LeptosConfigError {
fn from(e: ParseBoolError) -> Self {
Self::ConfigError(e.to_string())
}
}
26 changes: 26 additions & 0 deletions leptos_config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ pub struct LeptosOptions {
#[builder(default = default_not_found_path())]
#[serde(default = "default_not_found_path")]
pub not_found_path: String,
/// The file name of the hash text file generated by cargo-leptos. Defaults to `hash.txt`.
#[builder(default = default_hash_file_name())]
#[serde(default = "default_hash_file_name")]
pub hash_file: String,
/// If true, hashes will be generated for all files in the site_root and added to their file names.
/// Defaults to `true`.
#[builder(default = default_frontend_files_content_hashes())]
#[serde(default = "default_frontend_files_content_hashes")]
pub frontend_files_content_hashes: bool,
}

impl LeptosOptions {
Expand Down Expand Up @@ -108,6 +117,15 @@ impl LeptosOptions {
env_w_default("LEPTOS_RELOAD_WS_PROTOCOL", "ws")?.as_str(),
)?,
not_found_path: env_w_default("LEPTOS_NOT_FOUND_PATH", "/404")?,
hash_file: env_w_default("LEPTOS_HASH_FILE_NAME", "hash.txt")?,
frontend_files_content_hashes: env_w_default(
"LEPTOS_FRONTEND_FILES_CONTENT_HASHES",
"ON",
)?
.to_uppercase()
.replace("ON", "true")
.replace("OFF", "false")
.parse()?,
})
}
}
Expand Down Expand Up @@ -146,6 +164,14 @@ fn default_not_found_path() -> String {
"/404".to_string()
}

fn default_hash_file_name() -> String {
"hash.txt".to_string()
}

fn default_frontend_files_content_hashes() -> bool {
true
}

fn env_wo_default(key: &str) -> Result<Option<String>, LeptosConfigError> {
match std::env::var(key) {
Ok(val) => Ok(Some(val)),
Expand Down
Loading