PhotoCraft: An open-source, photo editor written by scratch in pure Rust
CI: fix the tests that keep main red, and ship the wasm as compressed parts (#5926, #5302) (#5941)
Zuujisdf055f3dcb0b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex bec29abaf..dfc2564a5 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -65,7 +65,7 @@ jobs:# The browser build (a fat-LTO wasm build) runs only when something it compiles or# packages changed: the web app and its packaging, crate sources and manifests (the web# build compiles nearly every crate), the workspace manifests and this workflow.- if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/photocraft-web/|packaging/web/|packaging/env\.sh$|crates/[^/]+/(src/|Cargo\.toml$|build\.rs$)|Cargo\.(toml|lock)$|rust-toolchain(\.toml)?$|\.github/workflows/ci\.yml$)'; then+ if git diff --name-only "$BASE" HEAD | grep -Eq '^(apps/photocraft-web(-boot)?/|packaging/web/|packaging/env\.sh$|crates/[^/]+/(src/|Cargo\.toml$|build\.rs$)|Cargo\.(toml|lock)$|rust-toolchain(\.toml)?$|\.github/workflows/ci\.yml$)'; thenecho "web=true" >> "$GITHUB_OUTPUT"elseecho "web=false" >> "$GITHUB_OUTPUT"@@ -229,8 +229,8 @@ jobs:curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \| tar -xz -C "$HOME/.cargo/bin" trunktrunk --version- # package.sh runs Trunk's release build, validates relative URLs, checks the 24 MiB- # wasm limit and exercises the same packaging step used by release.yml.+ # package.sh runs Trunk's release builds, validates relative URLs, cuts the wasm into+ # parts, checks the 24 MiB per-file limit and exercises the packaging step release.yml uses.- name: Build and verify browser releaserun: packaging/web/package.sh- name: Report wasm size@@ -241,12 +241,15 @@ jobs:echoecho "| File | Bytes | MiB | Limit |"echo "| --- | ---: | ---: | ---: |"+ row() { echo "| $1 | $2 | $(awk -v n="$2" 'BEGIN { printf "%.2f", n / 1048576 }') | $3 |"; }+ # The app's wasm as built; it ships gzipped in parts, so only the download grows with it.for wasm in dist/web/*.wasm; do[ -f "$wasm" ] || continue- bytes=$(wc -c < "$wasm" | tr -d ' ')- mib=$(awk -v n="$bytes" 'BEGIN { printf "%.2f", n / 1048576 }')- echo "| $(basename "$wasm") | $bytes | $mib | 24 MiB |"+ row "$(basename "$wasm")" "$(wc -c < "$wasm" | tr -d ' ')" "none"done+ # What a host sees: the largest file of the packaged site.+ largest=$(find target/web-package -type f -printf '%s %f\n' | sort -n | tail -1)+ row "largest file in the site: ${largest#* }" "${largest%% *}" "24 MiB"} >> "$GITHUB_STEP_SUMMARY"fuzz:diff --git a/AGENTS.md b/AGENTS.mdindex 6adc5923d..97b5ccdbc 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -39,6 +39,7 @@ apps/photocraft desktop app (eframe/wgpu), TCP control serverphotocraft-cli headless CLI (convert/info/run/batch/commands/mcp)photocraft-web the same app in the browser (trunk + wasm-bindgen)+ photocraft-web-boot starts the packaged browser app from compressed parts of its wasm (no file over a host's size cap)xtask/ cargo xtask layers | wasm | ci | stats | corpus | test-corpus | parity | perf | scorecard```diff --git a/Cargo.lock b/Cargo.lockindex 54085cf44..b3a268add 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5073,6 +5073,17 @@ dependencies = ["web-sys",]+[[package]]+name = "photocraft-web-boot"+version = "0.9.0"+dependencies = [+ "flate2",+ "js-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]+[[package]]name = "pico-args"version = "0.5.0"diff --git a/apps/photocraft-web-boot/Cargo.toml b/apps/photocraft-web-boot/Cargo.tomlnew file mode 100644index 000000000..dd12341af--- /dev/null+++ b/apps/photocraft-web-boot/Cargo.toml@@ -0,0 +1,24 @@+[package]+name = "photocraft-web-boot"+description = "Starts Photocraft in the browser from compressed parts of its WebAssembly"+version.workspace = true+edition.workspace = true+license.workspace = true+publish = false++[lints]+workspace = true++[[bin]]+name = "photocraft-web-boot"+path = "src/main.rs"++[dependencies]+# Inflates the parts in browsers without `DecompressionStream`.+flate2 = { workspace = true }++[target.'cfg(target_arch = "wasm32")'.dependencies]+wasm-bindgen = "0.2"+wasm-bindgen-futures = "0.4"+js-sys = "0.3"+web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Node", "Request", "RequestInit", "RequestCache", "Response", "ResponseInit", "Headers", "ReadableStream", "WritableStream", "TransformStream", "TransformStreamDefaultController", "Transformer", "StreamPipeOptions", "ReadableWritablePair", "console"] }diff --git a/apps/photocraft-web-boot/Trunk.toml b/apps/photocraft-web-boot/Trunk.tomlnew file mode 100644index 000000000..56192a992--- /dev/null+++ b/apps/photocraft-web-boot/Trunk.toml@@ -0,0 +1,6 @@+# Built by packaging/web/package.sh: trunk build --release (from apps/photocraft-web-boot)+[build]+target = "index.html"+dist = "../../dist/web-boot"+public_url = "./"+filehash = truediff --git a/apps/photocraft-web-boot/index.html b/apps/photocraft-web-boot/index.htmlnew file mode 100644index 000000000..8ed9a6961--- /dev/null+++ b/apps/photocraft-web-boot/index.html@@ -0,0 +1,30 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">+ <title>PhotoCraft</title>+ <link data-trunk rel="rust" data-bin="photocraft-web-boot" data-cargo-profile="wasm-release" data-wasm-opt="z" data-wasm-opt-params="--converge" data-weak-refs />+ <style>+ html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #262626; }+ #photocraft_canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }+ #photocraft_loading { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center;+ padding: 0 16px; text-align: center; color: #b8b8b8; font: 14px system-ui, sans-serif; pointer-events: none; }+ #photocraft_loading p { margin: 0 0 8px; max-width: 420px; line-height: 1.5; }+ #photocraft_loading a { color: #e0e0e0; pointer-events: auto; }+ /* The app removes this element once it runs. If the WebAssembly never downloads or doesn't match+ this page, no Rust runs to say so, so the page itself shows what to do after a while. */+ #photocraft_stalled { color: #8c8c8c; visibility: hidden; animation: photocraft-stalled 0s 20s forwards; }+ @keyframes photocraft-stalled { to { visibility: visible; } }+ </style>+</head>+<body>+ <canvas id="photocraft_canvas"></canvas>+ <div id="photocraft_loading">+ <p>Loading PhotoCraft…</p>+ <p id="photocraft_stalled">This is taking longer than usual. If PhotoCraft doesn't start, its files may have failed to+ download or come from a different version of this page. <a href="">Reload</a> to try again; the browser+ console lists what failed.</p>+ </div>+</body>+</html>diff --git a/apps/photocraft-web-boot/src/main.rs b/apps/photocraft-web-boot/src/main.rsnew file mode 100644index 000000000..56c2bf151--- /dev/null+++ b/apps/photocraft-web-boot/src/main.rs@@ -0,0 +1,356 @@+//! Starts Photocraft in the browser from compressed parts of its WebAssembly.+//!+//! Static hosts cap the size of one file (Cloudflare Pages: 25 MiB), and the app's wasm is at+//! that size. `packaging/web/package.sh` gzips it and cuts it into parts listed in+//! `app/parts.txt`. This small module is what the packaged page loads: it fetches the parts in+//! order, joins and inflates them as they arrive, and hands the stream to the app's own generated+//! loader, so the browser still compiles while downloading. No file on the host is larger than+//! one part, however large the app grows.+//!+//! The browser inflates the parts (`DecompressionStream`: Safari 16.4, Firefox 113, Chrome 80).+//! In one that can't, this module inflates them itself, a little slower.+//!+//! A download that fails is tried again, the later tries past the browser's cache (a bad copy+//! there would otherwise fail forever). When every try fails the page says so and offers a reload.+//!+//! `trunk build` in `apps/photocraft-web` still gives the app as one `.wasm`, for development and+//! for hosts without a per-file cap; only the packaged site starts through this module.++#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]++/// First line of `parts.txt`. Some hosts answer a missing file with the home page and HTTP 200;+/// without this an HTML page would be read as a list of parts.+#[cfg(any(target_arch = "wasm32", test))]+const MARKER: &str = "photocraft-parts 1";++/// The part names in a `parts.txt`, in order, or `None` when the text isn't one. A name is a+/// file next to `parts.txt`: anything that could point elsewhere is refused.+#[cfg(any(target_arch = "wasm32", test))]+fn parts(list: &str) -> Option<Vec<String>> {+ let mut lines = list.lines().map(str::trim).filter(|l| !l.is_empty());+ if lines.next() != Some(MARKER) {+ return None;+ }+ let parts: Vec<String> = lines.map(str::to_owned).collect();+ let plain = |p: &String| !p.starts_with('.') && !p.contains(['/', '\\', '?', '#', ':', '%']);+ (!parts.is_empty() && parts.iter().all(plain)).then_some(parts)+}++/// Gzip inflated a chunk at a time, for browsers that can't do it themselves.+#[cfg(any(target_arch = "wasm32", test))]+struct Inflater(flate2::write::GzDecoder<Vec<u8>>);++#[cfg(any(target_arch = "wasm32", test))]+impl Inflater {+ fn new() -> Self {+ Inflater(flate2::write::GzDecoder::new(Vec::new()))+ }++ /// What the next `chunk` of the gzip stream inflates to (often nothing: the decoder holds on+ /// to input until it has a whole block).+ fn push(&mut self, chunk: &[u8]) -> std::io::Result<Vec<u8>> {+ std::io::Write::write_all(&mut self.0, chunk)?;+ Ok(std::mem::take(self.0.get_mut()))+ }++ /// The rest, once the stream has ended. An error when it ended early or its checksum is+ /// wrong, the same as the browser's inflater gives.+ fn finish(&mut self) -> std::io::Result<Vec<u8>> {+ self.0.try_finish()?;+ Ok(std::mem::take(self.0.get_mut()))+ }+}++#[cfg(target_arch = "wasm32")]+mod boot {+ use std::cell::RefCell;+ use std::rc::Rc;++ use wasm_bindgen::prelude::*;+ use wasm_bindgen_futures::{JsFuture, spawn_local};+ use web_sys::{+ Headers, ReadableStream, ReadableWritablePair, RequestCache, RequestInit, Response, ResponseInit, StreamPipeOptions, TransformStream,+ TransformStreamDefaultController, Transformer, WritableStream,+ };++ use super::Inflater;++ /// Where packaging puts the app, next to this module's own files.+ const PARTS: &str = "./app/parts.txt";+ /// Seconds to wait before each further try; one more than this many tries are made.+ const RETRY_AFTER: [u32; 2] = [1, 3];++ // The app's `wasm-bindgen` loader. Its default export instantiates the module it is given and+ // runs the app's `main`. The path is fixed at compile time, so packaging gives the file this+ // name (Trunk's own name for it carries a content hash).+ #[wasm_bindgen(raw_module = "./app/photocraft-web.js")]+ extern "C" {+ #[wasm_bindgen(js_name = default, catch)]+ async fn start_app(module: JsValue) -> Result<JsValue, JsValue>;+ }++ // The browser's own inflater. `web-sys` has it only behind its unstable-API flag, which would+ // have to be set for the whole build, so the three members used are declared here.+ #[wasm_bindgen]+ extern "C" {+ type DecompressionStream;+ #[wasm_bindgen(constructor, catch)]+ fn new(format: &str) -> Result<DecompressionStream, JsValue>;+ #[wasm_bindgen(method, getter)]+ fn readable(this: &DecompressionStream) -> ReadableStream;+ #[wasm_bindgen(method, getter)]+ fn writable(this: &DecompressionStream) -> WritableStream;+ }++ fn window() -> Result<web_sys::Window, JsValue> {+ web_sys::window().ok_or_else(|| JsValue::from_str("no window"))+ }++ /// `fresh` skips the browser's cache.+ async fn fetch(url: &str, fresh: bool) -> Result<Response, JsValue> {+ let init = RequestInit::new();+ if fresh {+ init.set_cache(RequestCache::Reload);+ }+ let response: Response = JsFuture::from(window()?.fetch_with_str_and_init(url, &init)).await?.dyn_into()?;+ if !response.ok() {+ return Err(JsValue::from_str(&format!("{url}: HTTP {}", response.status())));+ }+ if response.headers().get("Content-Type")?.is_some_and(|t| t.starts_with("text/html")) {+ return Err(JsValue::from_str(&format!("{url}: the server sent a web page, not the file")));+ }+ Ok(response)+ }++ /// Copies each part into `sink` in order, then closes it.+ async fn feed(parts: Vec<String>, sink: WritableStream, fresh: bool) -> Result<(), JsValue> {+ let keep_open = StreamPipeOptions::new();+ keep_open.set_prevent_close(true);+ for part in &parts {+ let body = fetch(&format!("./app/{part}"), fresh).await?.body().ok_or_else(|| JsValue::from_str("part without a body"))?;+ JsFuture::from(body.pipe_to_with_options(&sink, &keep_open)).await?;+ }+ JsFuture::from(sink.close()).await?;+ Ok(())+ }++ /// Passes inflated bytes on to the stream's reader.+ fn emit(inflated: std::io::Result<Vec<u8>>, out: &TransformStreamDefaultController) -> Result<(), JsValue> {+ let inflated = inflated.map_err(|e| JsValue::from_str(&format!("the download is damaged ({e})")))?;+ if inflated.is_empty() { Ok(()) } else { out.enqueue_with_chunk(&js_sys::Uint8Array::from(inflated.as_slice())) }+ }++ /// A gzip inflater with the shape of `DecompressionStream`, running in this module.+ fn own_inflater() -> Result<TransformStream, JsValue> {+ let inflater = Rc::new(RefCell::new(Inflater::new()));+ let last = inflater.clone();+ let busy = || JsValue::from_str("the inflater is in use");+ let transform = Closure::<dyn FnMut(JsValue, TransformStreamDefaultController) -> Result<(), JsValue>>::new(+ move |chunk: JsValue, out: TransformStreamDefaultController| {+ let chunk = js_sys::Uint8Array::new(&chunk).to_vec();+ emit(inflater.try_borrow_mut().map_err(|_| busy())?.push(&chunk), &out)+ },+ );+ let flush = Closure::<dyn FnMut(TransformStreamDefaultController) -> Result<(), JsValue>>::new(move |out: TransformStreamDefaultController| {+ emit(last.try_borrow_mut().map_err(|_| busy())?.finish(), &out)+ });+ let transformer = Transformer::new();+ transformer.set_transform(&transform.into_js_value().unchecked_into());+ transformer.set_flush(&flush.into_js_value().unchecked_into());+ TransformStream::new_with_transformer(&transformer)+ }++ /// `compressed` inflated: by the browser where it can, otherwise here.+ fn inflated(compressed: &ReadableStream) -> Result<ReadableStream, JsValue> {+ let pair = if js_sys::Reflect::has(&js_sys::global(), &JsValue::from_str("DecompressionStream"))? {+ let inflater = DecompressionStream::new("gzip")?;+ ReadableWritablePair::new(&inflater.readable(), &inflater.writable())+ } else {+ let inflater = own_inflater()?;+ ReadableWritablePair::new(&inflater.readable(), &inflater.writable())+ };+ Ok(compressed.pipe_through(&pair))+ }++ async fn run(fresh: bool) -> Result<(), JsValue> {+ let list = JsFuture::from(fetch(PARTS, fresh).await?.text()?).await?.as_string().unwrap_or_default();+ let parts = super::parts(&list).ok_or_else(|| JsValue::from_str("app/parts.txt is not a parts list"))?;+ let joined = TransformStream::new()?;+ let wasm = inflated(&joined.readable())?;+ // Why the download stopped: the app's loader only reports that its stream broke.+ let cause = Rc::new(RefCell::new(None));+ let failed = cause.clone();+ let sink = joined.writable();+ spawn_local(async move {+ if let Err(e) = feed(parts, sink.clone(), fresh).await {+ let _ = sink.abort_with_reason(&e);+ failed.replace(Some(e));+ }+ });+ let headers = Headers::new()?;+ headers.set("Content-Type", "application/wasm")?;+ let init = ResponseInit::new();+ init.set_headers(&headers);+ let response = Response::new_with_opt_readable_stream_and_init(Some(&wasm), &init)?;+ let arg = js_sys::Object::new();+ js_sys::Reflect::set(&arg, &JsValue::from_str("module_or_path"), &response)?;+ match start_app(arg.into()).await {+ Ok(_) => Ok(()),+ Err(e) => Err(cause.take().unwrap_or(e)),+ }+ }++ async fn sleep(seconds: u32) {+ let wait = js_sys::Promise::new(&mut |done, _| {+ let ms = i32::try_from(seconds.saturating_mul(1000)).unwrap_or(i32::MAX);+ if window().and_then(|w| w.set_timeout_with_callback_and_timeout_and_arguments_0(&done, ms)).is_err() {+ let _ = done.call0(&JsValue::NULL);+ }+ });+ let _ = JsFuture::from(wait).await;+ }++ /// Replaces the page's "Loading" text. `reload` adds a link that reloads the page.+ fn say(text: &str, reload: bool) {+ let Some(document) = web_sys::window().and_then(|w| w.document()) else { return };+ let Some(loading) = document.get_element_by_id("photocraft_loading") else { return };+ loading.set_text_content(None);+ let Ok(line) = document.create_element("p") else { return };+ line.set_text_content(Some(text));+ if reload && let Ok(link) = document.create_element("a") {+ link.set_text_content(Some("Reload"));+ let _ = link.set_attribute("href", "");+ let _ = line.append_child(&link);+ }+ let _ = loading.append_child(&line);+ }++ pub fn start() {+ spawn_local(async {+ let mut attempt = 0;+ loop {+ let error = match run(attempt > 0).await {+ Ok(()) => return,+ Err(e) => e,+ };+ web_sys::console::error_2(&JsValue::from_str("photocraft-web-boot: could not start PhotoCraft:"), &error);+ let Some(&wait) = RETRY_AFTER.get(attempt) else {+ say("PhotoCraft couldn't be downloaded. Check your connection, then try again: ", true);+ return;+ };+ say("Loading PhotoCraft\u{2026} (the download failed, trying again)", false);+ sleep(wait).await;+ attempt += 1;+ }+ });+ }+}++#[cfg(target_arch = "wasm32")]+fn main() {+ boot::start();+}++#[cfg(not(target_arch = "wasm32"))]+fn main() {+ eprintln!("photocraft-web-boot only runs in the browser: packaging/web/package.sh builds it with `trunk build --release` in apps/photocraft-web-boot");+}++#[cfg(test)]+mod tests {+ use super::{Inflater, MARKER, parts};++ fn gzip(bytes: &[u8]) -> Vec<u8> {+ let mut z = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());+ std::io::Write::write_all(&mut z, bytes).expect("gzip");+ z.finish().expect("gzip")+ }++ /// Bytes that don't compress to nothing, so the gzip stream spans many chunks.+ fn sample() -> Vec<u8> {+ let mut x = 0x2545_f491_4f6c_dd1d_u64;+ (0..200_000)+ .map(|i| {+ x ^= x << 13;+ x ^= x >> 7;+ x ^= x << 17;+ if i % 3 == 0 { x as u8 } else { (i / 7) as u8 }+ })+ .collect()+ }++ /// The parts arrive in whatever pieces the network gives; the inflater must not care where+ /// they are cut.+ #[test]+ fn the_inflater_gives_back_the_bytes_however_the_stream_is_cut() {+ let (plain, packed) = (sample(), gzip(&sample()));+ for cut in [1, 7, 4096, 65_536, packed.len()] {+ let mut inflater = Inflater::new();+ let mut out = Vec::new();+ for chunk in packed.chunks(cut) {+ out.extend(inflater.push(chunk).expect("push"));+ }+ out.extend(inflater.finish().expect("finish"));+ assert_eq!(out, plain, "chunks of {cut}");+ }+ }++ /// A download that stops early, or whose bytes changed on the way, must fail (the boot module+ /// then tries again), never start a damaged app.+ #[test]+ fn the_inflater_refuses_a_short_or_damaged_stream() {+ let packed = gzip(&sample());+ let run = |bytes: &[u8]| -> std::io::Result<Vec<u8>> {+ let mut inflater = Inflater::new();+ let mut out = inflater.push(bytes)?;+ out.extend(inflater.finish()?);+ Ok(out)+ };+ assert!(run(&packed).is_ok());+ assert!(run(&packed[..packed.len() / 2]).is_err(), "cut short");+ assert!(run(&packed[..packed.len() - 4]).is_err(), "trailer cut");+ let mut damaged = packed.clone();+ let middle = damaged.len() / 2;+ damaged[middle] ^= 0x55;+ assert!(run(&damaged).is_err(), "a changed byte");+ assert!(run(b"<!DOCTYPE html><html>not gzip</html>").is_err(), "a web page");+ assert!(run(b"").is_err(), "nothing at all");+ }++ #[test]+ fn a_parts_list_gives_its_names_in_order() {+ let list = format!("{MARKER}\nphotocraft-web-0123abcd.part-aa\r\n\n photocraft-web-0123abcd.part-ab \n");+ assert_eq!(parts(&list), Some(vec!["photocraft-web-0123abcd.part-aa".to_owned(), "photocraft-web-0123abcd.part-ab".to_owned()]));+ }++ /// A host that answers a missing file with its home page must not have that page read as a+ /// list of parts.+ #[test]+ fn a_web_page_is_not_a_parts_list() {+ assert_eq!(parts(include_str!("../index.html")), None);+ assert_eq!(parts(""), None);+ assert_eq!(parts("photocraft-web.part-aa\n"), None, "no marker");+ assert_eq!(parts(&format!("{MARKER}\n")), None, "no parts");+ assert_eq!(parts("photocraft-parts 2\na.part-aa\n"), None, "a later layout this build doesn't know");+ }++ /// Part names are joined onto `./app/`, so one that could leave that folder, or name another+ /// origin, refuses the whole list.+ #[test]+ fn a_part_name_cannot_point_outside_the_app_folder() {+ for bad in ["../index.html", "a/b.part-aa", "a\\b", "https://example.com/x", "//example.com/x", "x?y", "x#y", ".hidden", "%2e%2e"] {+ assert_eq!(parts(&format!("{MARKER}\ngood.part-aa\n{bad}\n")), None, "{bad}");+ }+ }++ /// The packaged site shows this crate's page, the development build the app's own. They are+ /// the same page apart from which program the `<link data-trunk>` line builds.+ #[test]+ fn the_page_is_the_apps_page() {+ let trunk = |html: &str| html.lines().filter(|l| !l.contains("data-trunk")).collect::<Vec<_>>().join("\n");+ let (boot, app) = (include_str!("../index.html"), include_str!("../../photocraft-web/index.html"));+ assert_eq!(trunk(boot), trunk(app));+ assert!(boot.contains(r#"data-bin="photocraft-web-boot""#) && boot.contains(r#"data-cargo-profile="wasm-release""#), "{boot}");+ assert!(boot.contains(r#"id="photocraft_loading""#), "the element the failure message replaces");+ }+}diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rsindex 92b96f914..fa7cb9524 100644--- a/crates/ui-egui/src/filter_dialog.rs+++ b/crates/ui-egui/src/filter_dialog.rs@@ -1956,9 +1956,13 @@ mod tests {assert_eq!(sm.smart_filters.len(), 1, "the preview adds the Curves smart filter");assert_eq!(shown.size, crate::proxy::proxy_document(&doc, k).size);// The 16 px square at (16, 16) is a 4 px square at (4, 4) on the proxy, not 16 px at (16, 16).- for (x, y) in [(4, 4), (5, 6), (7, 7)] {+ // Its corners are partly covered by the smart object's resampling (220/255), its inside fully.+ for (x, y) in [(5, 5), (5, 6), (6, 6)] {assert!(alpha(&shown, x, y) > 0.99, "({x}, {y}) is inside the reduced square");}+ for (x, y) in [(4, 4), (7, 7)] {+ assert!(alpha(&shown, x, y) > 0.5, "({x}, {y}) is a corner of the reduced square");+ }for (x, y) in [(2, 2), (9, 9), (12, 12), (15, 15)] {assert!(alpha(&shown, x, y) < 0.01, "({x}, {y}) is outside the reduced square");}diff --git a/crates/ui-egui/src/profile_open_tests.rs b/crates/ui-egui/src/profile_open_tests.rsindex 2ede8ffef..3eeb06b00 100644--- a/crates/ui-egui/src/profile_open_tests.rs+++ b/crates/ui-egui/src/profile_open_tests.rs@@ -13,7 +13,7 @@ use photocraft_doc::{Color, ColorMode, Document, SampleType, Size};use photocraft_engine::Session;use serde_json::Value;-const USE: &str = "Use the embedded profile (Adobe RGB (1998)-compatible (Photocraft))";+const USE: &str = "Use the embedded profile (Adobe RGB (1998)-compatible (PhotoCraft))";const CONVERT: &str = "Convert to the working space (sRGB IEC61966-2.1)";const DISCARD: &str = "Discard the embedded profile (don't color manage)";diff --git a/crates/ui-egui/tests/full_res_preview.rs b/crates/ui-egui/tests/full_res_preview.rsindex 6ac2a513c..191a071b9 100644--- a/crates/ui-egui/tests/full_res_preview.rs+++ b/crates/ui-egui/tests/full_res_preview.rs@@ -109,6 +109,10 @@ fn mean(r: &[i32]) -> f32 {r.iter().sum::<i32>() as f32 / r.len() as f32}+/// Dragging an adjustment layer's control (Properties panel) previews through the reduced copy+/// only as coarse as the screen (#5764): at 100 % every column shows even with low-resolution+/// previews on; zoomed out to 50 % the default drag runs on the reduced copy (only the black columns, inverted), and with+/// them off it matches the committed view (the columns' mipmapped grey).#[test]fn adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off() {let _gpu = photocraft_testkit::gpu_lock();@@ -126,12 +130,19 @@ fn adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off() {app.live_adjust = Some((id, json!({})));id};- let reduced = row(&mut h);- assert!(columns(&reduced) < 0.1, "default: the reduced copy loses the columns ({})", columns(&reduced));+ let at_100 = row(&mut h);+ assert!(columns(&at_100) > 0.9, "default at 100 %: the drag is never coarser than the screen ({})", columns(&at_100));+ control(&mut h, "ui.set", json!({"zoom": 0.5, "center": [W / 2, H / 2]}));+ h.state_mut().live_adjust = None;+ let committed = mean(&row(&mut h));+ assert!(committed > 60.0, "zoomed out the inverted columns average to grey ({committed})");+ h.state_mut().live_adjust = Some((layer, json!({})));+ let reduced = mean(&row(&mut h));+ assert!(reduced > 225.0, "default at 50 %: the reduced copy keeps only the (inverted) black columns ({reduced})");low_res(&mut h, false);h.state_mut().live_adjust = Some((layer, json!({})));- let full = row(&mut h);- assert!(columns(&full) > 0.9, "low-res previews off: every column shows ({})", columns(&full));+ let full = mean(&row(&mut h));+ assert!((full - committed).abs() < 8.0, "low-res previews off: the drag matches the committed view ({full} vs {committed})");}#[test]diff --git a/docs/architecture.md b/docs/architecture.mdindex 67eebe9cc..614cabfb0 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -7,8 +7,8 @@What exists on `main` today. The numbered sections below are the original design plan of2026-09-30; where the code differs, this summary wins.-- **Workspace:** 25 library crates under `crates/`, 3 apps (`photocraft` desktop, `photocraft-cli`,- `photocraft-web`), `xtask`, an example plug-in and 5 fuzz crates; ~539,000 lines of Rust in+- **Workspace:** 25 library crates under `crates/`, 4 apps (`photocraft` desktop, `photocraft-cli`,+ `photocraft-web`, `photocraft-web-boot`), `xtask`, an example plug-in and 5 fuzz crates; ~539,000 lines of Rust in~1,310 files; ~8,040 `#[test]` functions (ui-egui 2,809, engine 1,796, algo 572, io 539,codecs 426, psd 341), counted 2026-10-13. Crate map and layers: [`AGENTS.md`](../AGENTS.md) §2 and`xtask/src/layers.rs` (enforced by `cargo xtask layers`).@@ -146,7 +146,8 @@ photocraft/├─ apps/│ ├─ photocraft/ desktop binary (winit + wgpu + ui-egui + platform-native)│ ├─ photocraft-cli/ headless batch CLI (open → commands → export), also hosts `mcp` subcommand-│ └─ photocraft-web/ wasm32 binary (ui-egui + platform-web), demo+│ ├─ photocraft-web/ wasm32 binary (ui-egui + platform-web), demo+│ └─ photocraft-web-boot/ wasm32 binary that starts the packaged web app from parts of its wasm├─ shaders/ (or inside gpu/) WGSL, with generated struct headers├─ assets/ icons, bundled fonts, default brushes/swatches/presets├─ fuzz/ cargo-fuzz targets (psd, codecs, format)diff --git a/docs/development.md b/docs/development.mdindex 8bfc53df8..ceb679f5f 100644--- a/docs/development.md+++ b/docs/development.md@@ -377,7 +377,7 @@ trunk build --release # writes ../../dist/web (index.html, .js gluetrunk serve --release # dev server on http://127.0.0.1:8765```-Any static file server works for `dist/web`, for example `python3 -m http.server 8765` run inside that directory. Trunk downloads the matching `wasm-bindgen` and `wasm-opt` itself. `trunk build --release` uses the `wasm-release` Cargo profile (`data-cargo-profile` in `index.html`: fat LTO, opt-level "z" for the UI, engine, I/O and web shells and for large crates off the hot paths (document model, file parsers, JSON, SVG parsing, shader translation), "s" for other crates except pixel processing, which keeps level 3). The UI override reduces browser code size while retaining the speed-oriented settings for filters and compositing. Serve the `.wasm` with compression; its raw size varies with the source and compiler. Keep it under 24 MiB (`packaging/web/package.sh` enforces this; Cloudflare's per-file cap is 25 MiB). Pull-request CI also builds the actual browser app with the same pinned Trunk version as the release job and runs `packaging/web/package.sh`, including the relative-URL and 24 MiB checks. The `web build and wasm size gate` check runs on main and on PRs that change something the web build compiles or packages (`apps/photocraft-web`, `packaging/web`, crate sources and manifests, `Cargo.toml`/`Cargo.lock`, the CI workflow), and reports the resulting wasm size in the Actions job summary. The web build never embeds craft-fonts (see Fonts above). To see where the bytes go, run `twiggy top -n 40` on `target/wasm32-unknown-unknown/wasm-release/photocraft-web.wasm` (before wasm-opt strips the names).+Any static file server works for `dist/web`, for example `python3 -m http.server 8765` run inside that directory. Trunk downloads the matching `wasm-bindgen` and `wasm-opt` itself. `trunk build --release` uses the `wasm-release` Cargo profile (`data-cargo-profile` in `index.html`: fat LTO, opt-level "z" for the UI, engine, I/O and web shells and for large crates off the hot paths (document model, file parsers, JSON, SVG parsing, shader translation), "s" for other crates except pixel processing, which keeps level 3). The UI override reduces browser code size while retaining the speed-oriented settings for filters and compositing. Serve the `.wasm` with compression; its raw size varies with the source and compiler. Some static hosts refuse a file that large (Cloudflare's per-file cap is 25 MiB), so the release site doesn't hold it as one file: `packaging/web/package.sh` gzips it, cuts it into parts of at most 20 MiB under `app/`, and ships the page of `apps/photocraft-web-boot`, a small module that fetches the parts, has the browser inflate them (or inflates them itself where the browser can't) and passes the stream to the app's own loader (issue #5302). The script fails if any file in the site is over 24 MiB; the wasm's own size is no longer limited, but it is still what every visitor downloads, so watch it. Pull-request CI also builds the actual browser app with the same pinned Trunk version as the release job and runs `packaging/web/package.sh`, including the relative-URL and file-size checks. The `web build and wasm size gate` check runs on main and on PRs that change something the web build compiles or packages (`apps/photocraft-web`, `apps/photocraft-web-boot`, `packaging/web`, crate sources and manifests, `Cargo.toml`/`Cargo.lock`, the CI workflow), and reports the wasm's size and the site's largest file in the Actions job summary. The web build never embeds craft-fonts (see Fonts above). To see where the bytes go, run `twiggy top -n 40` on `target/wasm32-unknown-unknown/wasm-release/photocraft-web.wasm` (before wasm-opt strips the names).URL flags: `?webgl` forces the WebGL2 backend, and `?cpu` forces the CPU canvas path.diff --git a/docs/releasing.md b/docs/releasing.mdindex 6d35b6379..def1911aa 100644--- a/docs/releasing.md+++ b/docs/releasing.md@@ -284,11 +284,14 @@ and lists the tarball, which checks the layout without a FreeBSD machine.### Web-`packaging/web/package.sh` runs `trunk build --release` (see `apps/photocraft-web/Trunk.toml`)-and zips `dist/web` together with sample `_headers` and `.htaccess` files and the hosting guide.-The site only uses relative URLs, so it works under any path and in an iframe. The wasm builds-with the size-optimized `wasm-release` Cargo profile (set in `apps/photocraft-web/index.html`),-and the script fails if any `.wasm` exceeds 24 MiB, below Cloudflare's 25 MiB per-file limit.+`packaging/web/package.sh` runs `trunk build --release` for the app (`apps/photocraft-web`, into+`dist/web`) and for the module that starts it (`apps/photocraft-web-boot`, into `dist/web-boot`).+It gzips the app's wasm, cuts it into parts of at most 20 MiB and zips the boot module's page with+the parts, sample `_headers` and `.htaccess` files and the hosting guide. The site only uses+relative URLs, so it works under any path and in an iframe. The wasm builds with the+size-optimized `wasm-release` Cargo profile (set in `apps/photocraft-web/index.html`), and the+script fails if any file in the site exceeds 24 MiB, below Cloudflare's 25 MiB per-file limit;+the app's wasm itself may be larger, since it ships as parts.[`packaging/web/README.md`](../packaging/web/README.md) covers MIME types, compression,caching, the iframe snippet and the `?webgl` / `?cpu` flags.diff --git a/docs/scorecard.md b/docs/scorecard.mdindex 01a8f76ed..1e0576ba0 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -12,7 +12,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 166 (target 0) || [Type](#type) | 4 | 3 | 2 | || [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) |-| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present |+| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 29 of 29 crates; panic_hunt present || [Distribution](#distribution) | 5 | 4 | 2 | || [Open bugs](#open-bugs) | 29 | 2 | 1 | |@@ -241,7 +241,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T## Reliability-Never-crash attribute on 28 of 28 crate roots.+Never-crash attribute on 29 of 29 crate roots.| Id | Target | Status | Issue | Note ||---|---|---|---|---|diff --git a/packaging/web/.htaccess b/packaging/web/.htaccessindex 7b7e6e185..4aca774cc 100644--- a/packaging/web/.htaccess+++ b/packaging/web/.htaccess@@ -13,4 +13,12 @@ AddType text/javascript .js<FilesMatch "^index\.html$">Header set Cache-Control "no-cache"</FilesMatch>+ # app/: the app's loader and its list of parts keep their names from release to release; the+ # parts (the app's wasm, gzipped and cut up) carry a content hash.+ <FilesMatch "^(photocraft-web\.js|parts\.txt)$">+ Header set Cache-Control "no-cache"+ </FilesMatch>+ <FilesMatch "\.part-[a-z]+$">+ Header set Cache-Control "public, max-age=31536000, immutable"+ </FilesMatch></IfModule>diff --git a/packaging/web/README.md b/packaging/web/README.mdindex 5ca375f6c..e96dc3825 100644--- a/packaging/web/README.md+++ b/packaging/web/README.md@@ -6,8 +6,10 @@ static site in `photocraft-web-<version>/`:| File | What it is ||---|---|| `index.html` | The page. It loads everything through relative URLs. |-| `photocraft-web-<hash>.js` | wasm-bindgen glue (generated, ES module) |-| `photocraft-web-<hash>_bg.wasm` | The app: about 23 MiB raw, 10.5 MiB with gzip (see [Sizes](#sizes)) |+| `photocraft-web-boot-<hash>.js`, `photocraft-web-boot-<hash>_bg.wasm` | A small module (about 120 KB) that starts the app from its parts, with its wasm-bindgen glue |+| `app/photocraft-web-<hash>.part-aa`, `-ab`, … | The app's WebAssembly, gzipped and cut into parts of at most 20 MiB (see [Sizes](#sizes)) |+| `app/parts.txt` | The parts, in order |+| `app/photocraft-web.js` | The app's wasm-bindgen glue (generated, ES module) || `_headers`, `.htaccess` | Sample header rules for Netlify/Cloudflare Pages and Apache || `fonts/` (optional) | Fonts loaded on demand, listed in `fonts/manifest.txt` (see [Fonts](#fonts)) |@@ -68,44 +70,63 @@ The editor and image processing run on the visitor's device. Open uses the browspicker; Save and Export download files. Preferences use browser localStorage. There is noserver-side document storage, desktop TCP control server, or web autosave/crash recovery;save/download work before closing or reloading the page. A browser with WebGPU or WebGL2 is-required; `?webgl` forces the fallback when troubleshooting.+required; `?webgl` forces the fallback when troubleshooting. In a browser that can't+inflate a stream itself (no `DecompressionStream`: before Safari 16.4 and Firefox 113), the+release zip's site inflates the app's parts in its own code, a little slower.To verify the browser deployment, open the page, open an image and save/export it.## Sizes-Measured on 2026-10-12 (0.8.0, `packaging/web/package.sh`; gzip `-9`):+Measured on 2026-10-13 (0.8.2, `packaging/web/package.sh`):-| File | Raw | gzip |-|---|---|---|-| `photocraft-web-<hash>_bg.wasm` | 24,167,186 bytes (23.0 MiB) | 10,998,053 (10.5 MiB) |-| `photocraft-web-<hash>.js` | about 170 KB | about 26 KB |+| File | Size |+|---|---|+| `app/photocraft-web-<hash>.part-aa` (the only part today) | 11,401,527 bytes (10.9 MiB) |+| `app/photocraft-web.js` | about 170 KB (26 KB with gzip) |+| `photocraft-web-boot-<hash>_bg.wasm` and `.js` | about 120 KB together |++The app's WebAssembly is 25,019,043 bytes (23.9 MiB) before gzip.Per-file upload limits: Cloudflare Pages and Workers static assets reject any file over-**25 MiB** (26,214,400 bytes). The wasm fits, and `packaging/web/package.sh` fails the build if-it ever grows past 24 MiB, so a release can't ship a file a common host refuses. (Releases up to-0.2.0 shipped a 25.8 MiB wasm, which Cloudflare rejected; issue #198.) The size comes from the-`wasm-release` Cargo profile (fat LTO, size-optimized code with the pixel and file-decoding-crates kept at speed) plus `wasm-opt -Oz`, and from storing the bundled fonts (PhotoCraft's and-egui's) and the translation catalogs compressed, unpacked on first use.+**25 MiB** (26,214,400 bytes), and the app's WebAssembly is at that size. (Releases up to 0.2.0+shipped a 25.8 MiB wasm, which Cloudflare rejected; issue #198.) So the site doesn't hold it as+one file: packaging gzips it and cuts the result into parts of at most 20 MiB, and the page puts+them back together while it downloads them. `packaging/web/package.sh` fails if any file in the+site is over 24 MiB, so a release can't ship a file a common host refuses, and the app can grow+without reaching that limit (issue #5302). A build straight from Trunk (`trunk build --release`+in `apps/photocraft-web`, or the Docker image above) still has the app in one `.wasm`, for hosts+without such a cap.++The app is built with the `wasm-release` Cargo profile (fat LTO, size-optimized code with the+pixel and file-decoding crates kept at speed) plus `wasm-opt -Oz`, and stores the bundled fonts+(PhotoCraft's and egui's) and the translation catalogs compressed, unpacked on first use.## Any path worksAll URLs in `index.html` are relative (`public_url = "./"` in `apps/photocraft-web/Trunk.toml`),so the site works at a domain root (`https://example.com/`), under a prefix(`https://example.com/tools/photocraft/`) and from a CDN bucket. The asset names carry a content-hash, so they can be cached forever. Only `index.html` needs revalidation.+hash, so they can be cached forever. `index.html`, `app/photocraft-web.js` and `app/parts.txt` keep+their names and need revalidation.## Required server settings- **MIME type:** serve `.wasm` as `application/wasm`. Browsers refuse to stream-compile it underany other type, and the app then loads slowly or not at all. Serve `.js` as `text/javascript`.Most hosts already do both. For nginx, check that `mime.types` has `application/wasm wasm;`.-- **Compression:** turn on gzip or Brotli for `.wasm`, `.js` and `.html`. That takes the- download from about 19 MiB to about 8 MiB (gzip) or 5.6 MiB (Brotli). You can also- precompress (`brotli -k *.wasm`) and let the server send `Content-Encoding: br`.-- **Caching:** `Cache-Control: public, max-age=31536000, immutable` on the hashed `.wasm` and- `.js` files, and `no-cache` on `index.html`.+- **The parts as they are:** serve `app/*.part-*` byte for byte, with no `Content-Encoding` (they+ are gzip already, and the page inflates them). Their extension is one servers don't+ know, so the usual result, `application/octet-stream` and no compression, is right.+- **Missing files are 404s:** a host that answers every unknown path with `index.html` (a+ single-page-app fallback) hides a failed upload. PhotoCraft notices and says the download+ failed, but a 404 is clearer in the server's logs.+- **Compression:** turn on gzip or Brotli for `.wasm`, `.js` and `.html`. It matters little for+ the download, since the parts are compressed already; it shrinks the two `.js` files and the+ small boot module. You can also precompress and let the server send `Content-Encoding: br`.+- **Caching:** `Cache-Control: public, max-age=31536000, immutable` on the files whose names+ carry a hash (the parts and `photocraft-web-boot-<hash>.*`), and `no-cache` on `index.html`,+ `app/photocraft-web.js` and `app/parts.txt`. The sample `_headers` and `.htaccess` do this.- **HTTPS:** WebGPU (and the clipboard) only work in a secure context, which means `https://`or `http://localhost`. Over plain HTTP elsewhere, the app falls back to WebGL2.- **No special isolation headers:** PhotoCraft doesn't use `SharedArrayBuffer`, so it doesn't@@ -120,8 +141,9 @@ location /photocraft/ {types { application/wasm wasm; text/javascript js; text/html html; }gzip on;gzip_types application/wasm text/javascript text/html;- location ~* \.(wasm|js)$ { add_header Cache-Control "public, max-age=31536000, immutable"; }- location ~* index\.html$ { add_header Cache-Control "no-cache"; }+ # The first matching line wins, so the files that keep their names come first.+ location ~* (index\.html|app/photocraft-web\.js|app/parts\.txt)$ { add_header Cache-Control "no-cache"; }+ location ~* (\.(wasm|js)|\.part-[a-z]+)$ { add_header Cache-Control "public, max-age=31536000, immutable"; }}```diff --git a/packaging/web/_headers b/packaging/web/_headersindex fac0fbe1f..f8a7e7ca4 100644--- a/packaging/web/_headers+++ b/packaging/web/_headers@@ -11,3 +11,16 @@/index.htmlCache-Control: no-cache++# app/ holds the app's wasm, gzipped and cut into parts whose names carry a content hash...+/app/*+ Cache-Control: public, max-age=31536000, immutable++# ...and the app's loader and its list of parts, which keep their names from release to release.+/app/photocraft-web.js+ ! Cache-Control+ Cache-Control: no-cache++/app/parts.txt+ ! Cache-Control+ Cache-Control: no-cachediff --git a/packaging/web/package.sh b/packaging/web/package.shindex 8c6c1f8e2..58b9bccd0 100755--- a/packaging/web/package.sh+++ b/packaging/web/package.sh@@ -6,6 +6,10 @@# Needs: trunk (brew install trunk / cargo install trunk --locked) and the wasm32-unknown-unknown# target. The zip holds a self-contained static site in photocraft-web-<version>/ that works# from any URL path and inside an <iframe>. Hosting notes: packaging/web/README.md.+#+# The site holds the app's wasm gzipped and cut into parts (app/), started by the small+# photocraft-web-boot module, so no file is larger than a part however large the app grows+# (issue #5302). dist/web still holds the app as Trunk builds it, in one .wasm.set -euo pipefail# shellcheck source=../env.sh. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"@@ -14,38 +18,61 @@ HERE="$ROOT/packaging/web"if [ "${1:-}" != "--skip-build" ]; thencommand -v trunk >/dev/null || { echo "error: trunk not found (cargo install trunk --locked)" >&2; exit 1; }(cd "$ROOT/apps/photocraft-web" && trunk build --release)+ (cd "$ROOT/apps/photocraft-web-boot" && trunk build --release)fi-SITE="$ROOT/dist/web"-[ -f "$SITE/index.html" ] || { echo "error: $SITE/index.html missing; run without --skip-build" >&2; exit 1; }-# Paths must be relative so the site works under any prefix (public_url = "./" in Trunk.toml).-if grep -Eq '(src|href)="/[^/]' "$SITE/index.html"; then- echo "error: $SITE/index.html has root-absolute URLs; it would break when served from a sub-path" >&2+APP="$ROOT/dist/web" # the app: index.html, wasm-bindgen glue, one .wasm+BOOT="$ROOT/dist/web-boot" # the page that ships, and the module that starts the app from parts+for site in "$APP" "$BOOT"; do+ [ -f "$site/index.html" ] || { echo "error: $site/index.html missing; run without --skip-build" >&2; exit 1; }+ # Paths must be relative so the site works under any prefix (public_url = "./" in Trunk.toml).+ if grep -Eq '(src|href)="/[^/]' "$site/index.html"; then+ echo "error: $site/index.html has root-absolute URLs; it would break when served from a sub-path" >&2+ exit 1+ fi+done++# Size limit (issues #198, #5302): Cloudflare Pages/Workers reject any single file over 25 MiB,+# and other hosts and CDNs have similar caps. No file in the site may come near that; the app's+# wasm, the one file that does, ships as parts of PART_BYTES. Override only to investigate.+MAX_FILE_BYTES="${PHOTOCRAFT_WEB_MAX_FILE_BYTES:-25165824}" # 24 MiB+PART_BYTES="${PHOTOCRAFT_WEB_PART_BYTES:-20971520}" # 20 MiB+if [ "$PART_BYTES" -le 0 ] || [ "$PART_BYTES" -gt "$MAX_FILE_BYTES" ]; then+ echo "error: a part of $PART_BYTES bytes doesn't fit the $MAX_FILE_BYTES-byte file limit" >&2exit 1fi-# Size gate (issue #198): Cloudflare Pages/Workers reject any single file over 25 MiB, and other-# hosts and CDNs have similar caps. Fail well before that so a regression shows up here, not at-# upload time. Override with PHOTOCRAFT_WASM_MAX_BYTES only to investigate.-MAX_WASM_BYTES="${PHOTOCRAFT_WASM_MAX_BYTES:-25165824}" # 24 MiB-WASM_COUNT=0-for wasm in "$SITE"/*.wasm; do+WASM=""+for wasm in "$APP"/*_bg.wasm; do[ -f "$wasm" ] || continue- WASM_COUNT=$((WASM_COUNT + 1))- size=$(wc -c <"$wasm" | tr -d ' ')- echo "$(basename "$wasm"): $size bytes ($((size / 1048576)) MiB; limit $MAX_WASM_BYTES)"- if [ "$size" -gt "$MAX_WASM_BYTES" ]; then- echo "error: $(basename "$wasm") is $size bytes, over the $MAX_WASM_BYTES-byte limit (Cloudflare's per-file cap is 25 MiB)" >&2- exit 1- fi+ [ -z "$WASM" ] || { echo "error: more than one .wasm in $APP; remove it and run without --skip-build" >&2; exit 1; }+ WASM="$wasm"done-[ "$WASM_COUNT" -gt 0 ] || { echo "error: no .wasm in $SITE" >&2; exit 1; }+[ -n "$WASM" ] || { echo "error: no .wasm in $APP" >&2; exit 1; }+STEM="$(basename "$WASM" _bg.wasm)" # photocraft-web-<content hash>+GLUE="$APP/$STEM.js"+[ -f "$GLUE" ] || { echo "error: $GLUE missing" >&2; exit 1; }NAME="photocraft-web-$VERSION"WORK="$CARGO_TARGET_DIR/web-package"rm -rf "$WORK"-mkdir -p "$WORK/$NAME"-cp -R "$SITE/." "$WORK/$NAME/"+mkdir -p "$WORK/$NAME/app"+cp -R "$BOOT/." "$WORK/$NAME/"+# The boot module imports the app's glue by this name (it can't know Trunk's content hash).+cp "$GLUE" "$WORK/$NAME/app/photocraft-web.js"+# The parts keep the content hash, so they can be cached forever. Their extension is one no+# server knows: a server that recognised gzip might decode it or label it, and the page inflates+# the parts itself.+gzip -9 -n -c "$WASM" | (cd "$WORK/$NAME/app" && split -b "$PART_BYTES" - "$STEM.part-")+{+ echo "photocraft-parts 1"+ for part in "$WORK/$NAME/app/$STEM".part-*; do basename "$part"; done+} >"$WORK/$NAME/app/parts.txt"+size() { wc -c <"$1" | tr -d ' '; }+wasm_bytes=$(size "$WASM")+gzip_bytes=$(cat "$WORK/$NAME/app/$STEM".part-* | wc -c | tr -d ' ')+part_count=$(($(wc -l <"$WORK/$NAME/app/parts.txt") - 1))+echo "$(basename "$WASM"): $wasm_bytes bytes ($((wasm_bytes / 1048576)) MiB), shipped as $gzip_bytes bytes of gzip in $part_count part(s) of up to $PART_BYTES"# Sample server configs (MIME type, caching, compression); harmless where unused.cp "$HERE/_headers" "$HERE/.htaccess" "$WORK/$NAME/"cp "$HERE/README.md" "$WORK/$NAME/HOSTING.md"@@ -68,6 +95,16 @@ if [ -n "${PHOTOCRAFT_WEB_FONTS_DIR:-}" ]; thendoneecho "served fonts: $(grep -cvE '^[[:space:]]*(#|$)' "$FONTS_MANIFEST") manifest lines from $PHOTOCRAFT_WEB_FONTS_DIR"fi+largest=0+while IFS= read -r file; do+ bytes=$(size "$file")+ [ "$bytes" -le "$largest" ] || largest=$bytes+ if [ "$bytes" -gt "$MAX_FILE_BYTES" ]; then+ echo "error: ${file#"$WORK/$NAME/"} is $bytes bytes, over the $MAX_FILE_BYTES-byte limit (Cloudflare's per-file cap is 25 MiB)" >&2+ exit 1+ fi+done < <(find "$WORK/$NAME" -type f)+echo "largest file in the site: $largest bytes (limit $MAX_FILE_BYTES)"rm -f "$DIST/$NAME.zip"(cd "$WORK" && zip -qr9 "$DIST/$NAME.zip" "$NAME")echo "wrote $DIST/$NAME.zip"diff --git a/xtask/src/layers.rs b/xtask/src/layers.rsindex 212834514..ce34e8c25 100644--- a/xtask/src/layers.rs+++ b/xtask/src/layers.rs@@ -69,6 +69,7 @@ pub const TABLE: &[(&str, Class)] = &[("photocraft", Class::Exempt),("cli", Class::Exempt),("web", Class::Exempt),+ ("web-boot", Class::Exempt),("xtask", Class::Exempt),];@@ -373,7 +374,7 @@ mod tests {#[test]fn apps_and_xtask_exempt() {- for app in ["photocraft", "photocraft-cli", "photocraft-web", "xtask"] {+ for app in ["photocraft", "photocraft-cli", "photocraft-web", "photocraft-web-boot", "xtask"] {assert!(check(&[c(app, &[("egui", Normal, false), ("photocraft-ui-egui", Normal, true)])]).is_empty());}}