mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-05 23:10:07 +08:00
A theme is a stylesheet under :root[data-desktop] and React parts in place of the top bar, the Dock, the launcher and a window's title bar (web/src/themes); it loads when first shown and switches without a reload. Without a choice the device picks it: iOS, Android, else KDE. Also: the desktop's headless core (window manager, commands, apps, pins) moves to web/src/core with its tests; terminal tabs are drawn by the theme's title bar; Settings and System get a sidebar drawer in narrow windows; the first paint is a minimal splash; the console's auto-hide is removed.
208 lines
10 KiB
TypeScript
208 lines
10 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// The page's kernel as a Vite plugin (kernelPlugin()): the page's
|
|
// vite.config.ts uses it, and so can another app of this repository that
|
|
// boots the page's kernel. The kernel and the
|
|
// images are what pageSource() (kernel.ts) picks before anything is served
|
|
// or built, as a virtual module (default virtual:unkernel-kernel):
|
|
//
|
|
// kernelUrl the base bundle's UP kernel: a /@fs/ file in dev, a hashed
|
|
// asset in a build, or the release mirror's URL
|
|
// kernelSmpUrl its SMP kernel the same way, or null (no SMP patch, or `smp: false`)
|
|
// glUrl the guest GL renderer (virgl.mjs), or null (none, or `gl: false`)
|
|
// vkShaderUrl the guest Vulkan translator (kwvk-naga.wasm), or null (none, or `vk: false`)
|
|
// distros the images: { name, url, size, imageId? }
|
|
// kernelFrom why this kernel (pageSource()'s `why`)
|
|
//
|
|
// The dev server answers the files itself:
|
|
// - /distros/<name>.erofs (serveDistros()): with Range support and as they
|
|
// are (erofs compresses inside), revalidated (a local image is rebuilt in
|
|
// place); the list is read again on the next load after an image changes.
|
|
// - /_gl/virgl.mjs and virgl.wasm, /_vk/kwvk-naga.wasm (serveGl()): as they
|
|
// are on disk (Vite's transform would rewrite the module), revalidated.
|
|
// - A new base bundle (kernel/build.sh base) is split again (splitBase()).
|
|
// A build emits the kernels as hashed assets, virgl.mjs and virgl.wasm into
|
|
// /assets/virgl-<sha256 prefix>/ (virgl.mjs finds virgl.wasm next to
|
|
// itself), kwvk-naga.wasm as /assets/kwvk-naga-<sha256 prefix>.wasm, and
|
|
// lists the images by their served names (servedName()), which the app
|
|
// copies into its output itself (the page: unkernel:distro-images in its
|
|
// vite.config.ts); `buildImages: false` lists none. A release's files are
|
|
// the mirror's URLs in both, and nothing is emitted.
|
|
import { createReadStream } from "node:fs";
|
|
import { readFile, stat } from "node:fs/promises";
|
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
import type { Plugin } from "vite";
|
|
import { distroReply } from "../server/range.ts";
|
|
import { GL_FILES, VK_FILE, baseSplit, pageSource, rescanImages, splitBase, type PageImage } from "./kernel.ts";
|
|
|
|
export interface KernelPluginOptions {
|
|
/** The virtual module's id (default "virtual:unkernel-kernel"). */
|
|
id?: string;
|
|
/** The SMP kernel (kernelSmpUrl; default true). */
|
|
smp?: boolean;
|
|
/** The guest GL renderer (glUrl; default true). */
|
|
gl?: boolean;
|
|
/** The guest Vulkan translator (vkShaderUrl; default true). */
|
|
vk?: boolean;
|
|
/** A build lists the local images (the app copies them into its output; default true). */
|
|
buildImages?: boolean;
|
|
}
|
|
|
|
/** The dev server's images as they are now (sizes and hashes read again: an image may have been rebuilt). */
|
|
let devImages: Promise<PageImage[]> | undefined;
|
|
|
|
/** The page's kernel and images as a virtual module, and the dev server's answers for their files (see the top of this file). */
|
|
export function kernelPlugin(options: KernelPluginOptions = {}): Plugin {
|
|
const id = options.id ?? "virtual:unkernel-kernel";
|
|
const resolved = `\0${id}`;
|
|
const { smp: wantSmp = true, gl: wantGl = true, vk: wantVk = true, buildImages = true } = options;
|
|
return {
|
|
name: "unkernel:kernel",
|
|
configureServer(server) {
|
|
server.middlewares.use(serveDistros);
|
|
if (wantGl || wantVk) server.middlewares.use(serveGl);
|
|
// A new base bundle: split it again. A rebuilt image: the list is read again on the next page load.
|
|
void pageSource(true).then((s) => {
|
|
if (s.remote) return; // the mirror's files: nothing to watch
|
|
const images = s.distros.map((d) => d.file);
|
|
server.watcher.add([s.base, ...images]);
|
|
const invalidate = () => {
|
|
const mod = server.environments.client.moduleGraph.getModuleById(resolved);
|
|
if (mod) server.environments.client.moduleGraph.invalidateModule(mod);
|
|
};
|
|
const onFile = (file: string) => {
|
|
if (file === s.base) {
|
|
splitBase(file, true).catch((e: unknown) => console.error(`[kernel] ${(e as Error).message}`));
|
|
invalidate();
|
|
}
|
|
if (images.includes(file)) {
|
|
devImages = undefined;
|
|
invalidate();
|
|
}
|
|
};
|
|
server.watcher.on("change", onFile);
|
|
server.watcher.on("add", onFile);
|
|
});
|
|
},
|
|
resolveId: (source) => (source === id ? resolved : null),
|
|
async load(source) {
|
|
if (source !== resolved) return null;
|
|
const dev = this.environment.mode === "dev";
|
|
const s = await pageSource(dev);
|
|
let up: string, smp = "null";
|
|
const abs = (u: string) => `new URL(${JSON.stringify(u)})`;
|
|
if (s.remote) {
|
|
up = abs(s.remote.kernel);
|
|
if (wantSmp && s.remote.kernelSmp) smp = abs(s.remote.kernelSmp);
|
|
} else if (dev) {
|
|
const files = await splitBase(s.base);
|
|
up = `new URL(${JSON.stringify(`/@fs${files.up}`)}, import.meta.url)`;
|
|
if (wantSmp && files.smp) smp = `new URL(${JSON.stringify(`/@fs${files.smp}`)}, import.meta.url)`;
|
|
} else {
|
|
const split = await baseSplit(s.base);
|
|
const asset = (name: string, source: Uint8Array) =>
|
|
`new URL(import.meta.ROLLUP_FILE_URL_${this.emitFile({ type: "asset", name, source })}, import.meta.url)`;
|
|
up = asset("unkernel.wasm", split.up);
|
|
if (wantSmp && split.smp) smp = asset("unkernel-smp.wasm", split.smp);
|
|
}
|
|
let gl = "null";
|
|
// Against the location, not import.meta.url, which Vite would turn into an /@fs/ path.
|
|
if (!wantGl) { /* left out */ }
|
|
else if (!s.gl && s.remote?.gl) gl = abs(s.remote.gl);
|
|
else if (s.gl && dev) gl = `new URL("/_gl/${GL_FILES[0]}", globalThis.location.href)`;
|
|
else if (s.gl) {
|
|
// Fixed names in a directory named by their content: virgl.mjs loads ./virgl.wasm.
|
|
const dir = `assets/virgl-${s.gl.sha256.slice(0, 16)}`;
|
|
const ref = this.emitFile({ type: "asset", fileName: `${dir}/${GL_FILES[0]}`, source: await readFile(s.gl.mjs) });
|
|
this.emitFile({ type: "asset", fileName: `${dir}/${GL_FILES[1]}`, source: await readFile(s.gl.wasm) });
|
|
gl = `new URL(import.meta.ROLLUP_FILE_URL_${ref}, import.meta.url)`;
|
|
}
|
|
let vk = "null";
|
|
if (!wantVk) { /* left out */ }
|
|
else if (!s.vk && s.remote?.vk) vk = abs(s.remote.vk);
|
|
else if (s.vk && dev) vk = `new URL("/_vk/${VK_FILE}", globalThis.location.href)`;
|
|
else if (s.vk) {
|
|
const ref = this.emitFile({ type: "asset", fileName: `assets/kwvk-naga-${s.vk.sha256.slice(0, 16)}.wasm`, source: await readFile(s.vk.wasm) });
|
|
vk = `new URL(import.meta.ROLLUP_FILE_URL_${ref}, import.meta.url)`;
|
|
}
|
|
const images = dev ? await (devImages ??= rescanImages(s)) : buildImages || s.remote ? s.distros : [];
|
|
const distros = images.map(({ name, url, size, imageId }) => ({ name, url, size, ...(imageId ? { imageId } : {}) }));
|
|
return [
|
|
`export const kernelUrl = ${up};`,
|
|
`export const kernelSmpUrl = ${smp};`,
|
|
`export const glUrl = ${gl};`,
|
|
`export const vkShaderUrl = ${vk};`,
|
|
`export const distros = ${JSON.stringify(distros)};`,
|
|
`export const kernelFrom = ${JSON.stringify(s.why)};`,
|
|
].join("\n");
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The dev server's /_gl/virgl.mjs and /_gl/virgl.wasm: the page's GL
|
|
* renderer files (kernel.ts), as they are on disk (gl/wasm/build.sh
|
|
* rewrites them in place, so revalidated: no-cache), with the isolation
|
|
* headers. 404 without a GL renderer. Likewise /_vk/kwvk-naga.wasm, the
|
|
* Vulkan renderer's translator (vk/naga/build.sh).
|
|
*/
|
|
function serveGl(req: IncomingMessage, res: ServerResponse, next: () => void): void {
|
|
const url = (req.url ?? "").split("?")[0]!;
|
|
const vk = url.startsWith("/_vk/");
|
|
if (!vk && !url.startsWith("/_gl/")) return next();
|
|
const name = url.slice("/_gl/".length);
|
|
void pageSource(true).then(async (s) => {
|
|
const file = vk ? (s.vk && name === VK_FILE ? s.vk.wasm : null)
|
|
: !s.gl ? null : name === GL_FILES[0] ? s.gl.mjs : name === GL_FILES[1] ? s.gl.wasm : null;
|
|
const isolation = { "cross-origin-opener-policy": "same-origin", "cross-origin-embedder-policy": "require-corp", "cross-origin-resource-policy": "same-origin" };
|
|
if (!file) {
|
|
res.writeHead(404, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", ...isolation });
|
|
return void res.end(`no ${name} on this dev server (${vk ? s.vkWhy : s.glWhy})\n`);
|
|
}
|
|
const st = await stat(file);
|
|
const etag = `"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`;
|
|
const headers = { "content-type": file.endsWith(".wasm") ? "application/wasm" : "text/javascript; charset=utf-8", "cache-control": "no-cache", etag, ...isolation };
|
|
if (req.headers["if-none-match"] === etag) {
|
|
res.writeHead(304, headers);
|
|
return void res.end();
|
|
}
|
|
res.writeHead(200, { ...headers, "content-length": String(st.size) });
|
|
if (req.method === "HEAD") return void res.end();
|
|
const stream = createReadStream(file);
|
|
stream.on("error", () => res.destroy());
|
|
stream.pipe(res);
|
|
}).catch((e: unknown) => {
|
|
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
|
res.end(`${(e as Error).message}\n`);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* The dev server's /distros/<name>.erofs: the image of that name in the
|
|
* page's list, answered by server/range.ts's distroReply() (one range per
|
|
* request, uncompressed, revalidated with a strong ETag from size and
|
|
* mtime, the isolation headers). Anything else under /distros/ is a 404.
|
|
*/
|
|
function serveDistros(req: IncomingMessage, res: ServerResponse, next: () => void): void {
|
|
const url = (req.url ?? "").split("?")[0]!;
|
|
if (!url.startsWith("/distros/")) return next();
|
|
let name = url.slice("/distros/".length);
|
|
try { name = decodeURIComponent(name); } catch {}
|
|
void pageSource(true).then((s) => {
|
|
const file = s.distros.find((d) => d.url === url)?.file ?? null;
|
|
const r = distroReply(file, name, req.method ?? "GET", (h) => {
|
|
const v = req.headers[h];
|
|
return Array.isArray(v) ? v.join(", ") : v;
|
|
}, `no distro image ${name} on this dev server (${s.distros.map((d) => d.url).join(", ")})`);
|
|
res.writeHead(r.status, r.headers);
|
|
if (typeof r.body === "string") return void res.end(r.body);
|
|
if (!r.body) return void res.end();
|
|
const stream = createReadStream(r.body.file, { start: r.body.start, end: r.body.end });
|
|
stream.on("error", () => res.destroy());
|
|
stream.pipe(res);
|
|
}, (e: unknown) => {
|
|
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
|
res.end(`${(e as Error).message}\n`);
|
|
});
|
|
}
|