Web: WebAssembly build served cross-origin isolated, immutable and precompressed

The web app is built with --wasm (skwasm, JS/CanvasKit fallback beside it).
The proxy serves it with COOP same-origin + COEP credentialless so skwasm
renders on a worker; an installed build loads from /_v/<buildId>/ cached as
immutable, other files revalidate by ETag, and the installer precompresses
.br/.gz variants the proxy sends by Accept-Encoding. The bootstrap no
longer registers Flutter's deprecated service worker (a reload per install).
Read aloud on the web uses the Web Speech API through package:web: the
flutter_tts web plugin's interop casts fail under wasm. Bench kit: isolation
and headed modes, renderer and memory reporting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 21:05:17 +00:00
parent 23d8658e80
commit 3b1760fe8e
17 changed files with 737 additions and 17 deletions
+156
View File
@@ -0,0 +1,156 @@
// How the proxy serves the Flutter web build: cross-origin isolation, cache
// policy, validators and precompressed variants.
//
// Flutter's output names are not content-hashed (main.dart.js, canvaskit/…), so
// a long-lived cache needs a versioned address instead. An installed build
// carries release.json with its buildId; the shell page then names
// `/_v/<buildId>/` as the asset base (see app/web/flutter_bootstrap.js), and
// everything under it is immutable for a year. A new install changes the id,
// so the next page load fetches the new files. The shell, the bootstrap script
// and the small metadata files are revalidated on every load (ETag, 304).
import { createReadStream } from "node:fs";
import { readFile, stat } from "node:fs/promises";
import { extname, join, normalize, resolve, sep } from "node:path";
/**
* Cross-origin isolation, so the WebAssembly build's renderer (skwasm) can run
* multi-threaded (SharedArrayBuffer). `credentialless` rather than
* `require-corp`: images and other no-cors loads from other sites (in chat
* markdown or a sandboxed HTML preview) still load, without cookies, instead
* of being blocked for lacking a Cross-Origin-Resource-Policy header.
*/
export const ISOLATION_HEADERS = Object.freeze({
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "credentialless",
});
/** The versioned asset prefix: `/_v/<buildId>/<file>`. */
export const VERSIONED_PREFIX = "/_v/";
const IMMUTABLE = "private, max-age=31536000, immutable";
const REVALIDATE = "no-cache";
const BUILD_ID = /^[A-Za-z0-9._-]{1,80}$/;
/** Encodings precompressed at install time (scripts/app_build.py), best first. */
const ENCODINGS = [
["br", ".br"],
["gzip", ".gz"],
];
/** The encodings a request accepts (`q=0` excluded). */
export function acceptedEncodings(header) {
const accepted = new Set();
for (const part of String(header ?? "").split(",")) {
const [name, ...params] = part.trim().toLowerCase().split(";");
const q = params.map((p) => p.trim()).find((p) => p.startsWith("q="));
if (name && !(q && Number(q.slice(2)) === 0)) accepted.add(name);
}
return accepted;
}
export class AppFiles {
/** [root] is the web build directory; [mime] maps extensions to types. */
constructor(root, mime) {
this.root = resolve(root);
this.mime = mime;
this._release = { mtimeMs: -1, id: null };
}
/** The installed build's id from release.json, or null (a dev build). */
async buildId() {
const path = join(this.root, "release.json");
const info = await stat(path).catch(() => null);
if (!info?.isFile()) return null;
if (info.mtimeMs !== this._release.mtimeMs) {
let id = null;
try {
const value = JSON.parse(await readFile(path, "utf8"))?.buildId;
id = typeof value === "string" && BUILD_ID.test(value) ? value : null;
} catch {
id = null;
}
this._release = { mtimeMs: info.mtimeMs, id };
}
return this._release.id;
}
/** The asset base the shell page names, or null when the build has no id. */
async assetBase() {
const id = await this.buildId();
return id ? `${VERSIONED_PREFIX}${id}/` : null;
}
/**
* A versioned request's file: `{ path, immutable }`, false when it escapes
* the root, or null for a malformed one. A request for another build's id
* (a tab left open across an install) gets the current file, revalidated.
*/
async versioned(pathname) {
const rest = pathname.slice(VERSIONED_PREFIX.length);
const slash = rest.indexOf("/");
if (slash <= 0) return null;
const id = rest.slice(0, slash);
let rel;
try {
rel = decodeURIComponent(rest.slice(slash + 1));
} catch {
return null;
}
rel = normalize(rel).replace(/^([/\\])+/, "");
if (!rel || rel === ".") return null;
const path = resolve(join(this.root, rel));
if (!path.startsWith(this.root + sep)) return false;
return { path, immutable: id === (await this.buildId()) };
}
/**
* Sends one file of the build: an ETag (304 when it matches), the cache
* policy, the isolation headers and, when the client accepts it, the
* precompressed variant beside the file. Rejects when the file is missing.
*/
async send(req, res, path, { immutable = false } = {}) {
const info = await stat(path);
if (!info.isFile()) throw new Error("not a file");
const etag = `W/"${info.size.toString(36)}-${Math.floor(info.mtimeMs).toString(36)}"`;
const headers = {
...ISOLATION_HEADERS,
"Content-Type": this.mime[extname(path)] ?? "application/octet-stream",
"Cache-Control": immutable ? IMMUTABLE : REVALIDATE,
ETag: etag,
Vary: "Accept-Encoding",
};
const match = String(req.headers["if-none-match"] ?? "");
if (match && match.split(",").some((tag) => tag.trim() === etag || tag.trim() === "*")) {
res.writeHead(304, headers).end();
return;
}
let file = path;
let size = info.size;
const accepted = acceptedEncodings(req.headers["accept-encoding"]);
for (const [encoding, suffix] of ENCODINGS) {
if (!accepted.has(encoding)) continue;
const variant = await stat(path + suffix).catch(() => null);
// A variant older than its file is stale (a hand-copied build).
if (variant?.isFile() && variant.mtimeMs >= info.mtimeMs) {
file = path + suffix;
size = variant.size;
headers["Content-Encoding"] = encoding;
break;
}
}
headers["Content-Length"] = size;
res.writeHead(200, headers);
if (req.method === "HEAD") {
res.end();
return;
}
await new Promise((done) => {
const stream = createReadStream(file);
stream.on("error", () => {
res.destroy();
done();
});
stream.on("end", done);
stream.pipe(res);
});
}
}