Improve desktop app !

This commit is contained in:
2026-09-27 20:30:34 -03:00
parent 2207eea1e1
commit c74ebcda4e
6 changed files with 332 additions and 13 deletions
+20 -1
View File
@@ -1,4 +1,7 @@
import { copy } from "@std/fs";
import { copy, walk } from "@std/fs";
import { relative } from "@std/path";
import { PROTOCOL_VERSION } from "./common/protocol.ts";
import { CLIENT_MANIFEST, client_manifest, sha256 } from "./desktop/client_updates.ts";
import { createCanvas, loadImage } from "@gfx/canvas-wasm";
import { ENGINE_TEXTURE_DIR, load_and_check, load_order, LoadedMod } from "./tools/check_mods.ts";
import { pack_mod } from "./tools/pack_mod.ts";
@@ -127,6 +130,21 @@ async function build_client() {
await copy("./client/index.html", `${BUILD_FOLDER}/client/index.html`);
}
// every file the client needs with its hash, and the protocol it speaks. the desktop app compares it with the site's
// to update its client, see desktop/client_updates.ts
async function write_client_manifest(build_dir: string) {
const files: Record<string, string> = {};
for (const top of ["client", "assets"]) {
for await (const entry of walk(`${build_dir}/${top}`, { includeDirs: false })) {
const path = relative(build_dir, entry.path).replaceAll("\\", "/");
if (path === CLIENT_MANIFEST) continue;
files[path] = await sha256(Deno.readFileSync(entry.path));
}
}
const manifest = await client_manifest(files, PROTOCOL_VERSION);
Deno.writeTextFileSync(`${build_dir}/${CLIENT_MANIFEST}`, JSON.stringify(manifest, null, "\t"));
}
async function build() {
try {
const now = performance.now();
@@ -135,6 +153,7 @@ async function build() {
const mods = load_mods();
await build_assets();
await build_client();
await write_client_manifest(BUILD_FOLDER);
await build_mods(mods);
console.log(`Built in ${(performance.now() - now).toFixed(2)}ms`);
} catch (e) {
+1 -1
View File
@@ -7,7 +7,7 @@
"check-mods": "deno run --allow-read --allow-run tools/check_mods.ts",
"pack-mod": "deno run --allow-read --allow-write --allow-run --allow-env tools/pack_mod.ts",
"test": "deno test --allow-read --allow-write --allow-run tests/",
"desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-env=BWORLD_SERVER,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME --include build --include server_mods --include server/game/worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld"
"desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-env=BWORLD_SERVER,BWORLD_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME --include build --include server_mods --include server/game/worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld"
},
"compilerOptions": {
"lib": ["dom", "dom.asynciterable", "dom.iterable", "deno.ns", "deno.unstable", "deno.webgpu"]
+175
View File
@@ -0,0 +1,175 @@
// keeps the desktop app's client (build/client and build/assets) the same as the site's, like a game launcher: the
// build writes a manifest of every file's hash, the app downloads the site's when it's different and plays that
// copy from its data folder. the singleplayer server is part of the app and can't update this way, so a client for
// a different protocol is never used. anything that goes wrong leaves the app on the client it has
import { join } from "@std/path";
// where the manifest is, in a build folder and on the site
export const CLIENT_MANIFEST = "client/manifest.json";
export interface ClientManifest {
// the protocol the client speaks, see common/protocol.ts
protocol: number;
// changes whenever any file does
build: string;
// path in the build folder to its sha-256, as hex
files: Record<string, string>;
}
export async function sha256(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
}
export async function client_manifest(files: Record<string, string>, protocol: number): Promise<ClientManifest> {
const sorted = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b)));
const listing = Object.entries(sorted).map(([path, hash]) => `${path} ${hash}`).join("\n");
return { protocol, build: (await sha256(new TextEncoder().encode(listing))).slice(0, 16), files: sorted };
}
export interface ClientUpdateOptions {
// the site, like https://bworld.moder.fans
source: string;
// the client the app was built with
bundled_dir: string;
// where downloaded clients go, one folder per build
cache_dir: string;
// what the app's singleplayer server speaks
protocol: number;
fetch?: typeof fetch;
}
// the folder to serve the client from: the site's if it could be had, else the last one downloaded, else the bundled
// one. clients for another protocol are skipped
export async function update_client(options: ClientUpdateOptions): Promise<string> {
const fallback = () => current_client(options);
const bundled = read_manifest(options.bundled_dir);
let remote: ClientManifest;
try {
const response = await (options.fetch ?? fetch)(`${options.source}/${CLIENT_MANIFEST}`);
if (!response.ok) throw new Error(`manifest: ${response.status}`);
remote = await response.json();
} catch (e) {
console.log(`Couldn't check for a newer client: ${(e as Error).message}`);
return fallback();
}
if (remote.protocol !== options.protocol) {
console.log(`The site's client speaks protocol ${remote.protocol}, this app's server ${options.protocol}`);
return fallback();
}
if (remote.build === bundled?.build) {
return options.bundled_dir;
}
const folder = join(options.cache_dir, remote.build);
if (read_manifest(folder)?.build === remote.build) {
return folder;
}
try {
await download_client(remote, folder, options).catch((e) => {
remove(`${folder}.partial`);
throw e;
});
console.log(`Updated the client to ${remote.build}`);
remove_old_clients(options.cache_dir);
return folder;
} catch (e) {
console.log(`Couldn't update the client: ${(e as Error).message}`);
return fallback();
}
}
// every file into a temporary folder, taking the ones that didn't change from the bundled client or an older
// download, then the folder is renamed into place so a half done download is never used
async function download_client(manifest: ClientManifest, folder: string, options: ClientUpdateOptions) {
const partial = `${folder}.partial`;
remove(partial);
const known = local_files(options);
for (const [path, hash] of Object.entries(manifest.files)) {
if (path.split("/").includes("..")) throw new Error(`bad path ${path}`);
let bytes = known.get(hash)?.();
if (!bytes) {
const response = await (options.fetch ?? fetch)(`${options.source}/${path}`);
if (!response.ok) throw new Error(`${path}: ${response.status}`);
bytes = new Uint8Array(await response.arrayBuffer());
}
if (await sha256(bytes) !== hash) throw new Error(`${path} doesn't match the manifest`);
const target = join(partial, path);
Deno.mkdirSync(join(target, ".."), { recursive: true });
Deno.writeFileSync(target, bytes);
}
Deno.writeTextFileSync(join(partial, CLIENT_MANIFEST), JSON.stringify(manifest));
remove(folder);
Deno.renameSync(partial, folder);
}
// files the app already has, by hash, read only if they're needed
function local_files(options: ClientUpdateOptions) {
const files = new Map<string, () => Uint8Array<ArrayBuffer> | undefined>();
const folders = [options.bundled_dir, ...cache_folders(options.cache_dir)];
for (const folder of folders) {
for (const [path, hash] of Object.entries(read_manifest(folder)?.files ?? {})) {
if (!files.has(hash)) files.set(hash, () => try_read(join(folder, path)));
}
}
return files;
}
// the newest download for this protocol
function cached_client(options: ClientUpdateOptions): string | undefined {
return cache_folders(options.cache_dir)
.filter((folder) => read_manifest(folder)?.protocol === options.protocol)
.sort(by_newest)[0];
}
// what to play without checking the site, like when checking takes too long
export function current_client(options: ClientUpdateOptions): string {
return cached_client(options) ?? options.bundled_dir;
}
// the newest two are kept: the one just downloaded, and the one the app may still be playing if the download took
// longer than it waited
function remove_old_clients(cache_dir: string) {
const newest_first = cache_folders(cache_dir).sort(by_newest);
for (const folder of newest_first.slice(2)) remove(folder);
}
function by_newest(a: string, b: string) {
return Deno.statSync(b).mtime!.getTime() - Deno.statSync(a).mtime!.getTime();
}
function cache_folders(cache_dir: string): string[] {
try {
return [...Deno.readDirSync(cache_dir)]
.filter((entry) => entry.isDirectory && !entry.name.endsWith(".partial"))
.map((entry) => join(cache_dir, entry.name));
} catch {
return [];
}
}
function read_manifest(folder: string): ClientManifest | undefined {
const bytes = try_read(join(folder, CLIENT_MANIFEST));
try {
return bytes && JSON.parse(new TextDecoder().decode(bytes));
} catch {
return undefined;
}
}
function remove(path: string) {
try {
Deno.removeSync(path, { recursive: true });
} catch (e) {
if (!(e instanceof Deno.errors.NotFound)) throw e;
}
}
function try_read(path: string): Uint8Array<ArrayBuffer> | undefined {
try {
return Deno.readFileSync(path);
} catch {
return undefined;
}
}
+2 -1
View File
@@ -1,3 +1,4 @@
{
"server": "bworld.moder.fans"
"server": "bworld.moder.fans",
"client_updates": "https://bworld.moder.fans"
}
+31 -10
View File
@@ -5,17 +5,38 @@
// singleplayer, like minecraft java. build it with deno task desktop, see the desktop/ docs for how deno desktop works
import { fromFileUrl, join } from "@std/path";
import { type Host, serve_static, start_host } from "../server/host.ts";
import { PROTOCOL_VERSION } from "../common/protocol.ts";
import { current_client, update_client } from "./client_updates.ts";
// where the project was built from: build/ and server_mods/ (the .bmod files) are bundled into the app with --include
const ROOT = fromFileUrl(new URL("../", import.meta.url));
const BUILD_DIR = join(ROOT, "build");
// the server the address field starts with. "" leaves it empty for the player to fill in
const config: { server?: string } = JSON.parse(
const config: { server?: string; client_updates?: string } = JSON.parse(
await Deno.readTextFile(new URL("./config.json", import.meta.url)),
);
const default_server = Deno.env.get("BWORLD_SERVER") ?? config.server ?? "";
// the site the client updates from, see client_updates.ts. BWORLD_CLIENT_UPDATES=off plays the client the app was
// built with (to test a local build), or it can point at a local server to test updating
const updates_from = (Deno.env.get("BWORLD_CLIENT_UPDATES") ?? config.client_updates ?? "off").replace(/\/+$/, "");
// how long the first page waits for an update, a slower one is played next time
const UPDATE_WAIT_MS = 3000;
const client_options = {
source: updates_from,
bundled_dir: BUILD_DIR,
cache_dir: join(data_dir(), "client"),
protocol: PROTOCOL_VERSION,
};
const client_dir: Promise<string> = updates_from === "off" || updates_from === ""
? Promise.resolve(BUILD_DIR)
: Promise.race([
update_client(client_options),
new Promise<string>((resolve) => setTimeout(() => resolve(current_client(client_options)), UPDATE_WAIT_MS)),
]);
client_dir.then((dir) => console.log(`Playing the client in ${dir}`));
const win = new Deno.BrowserWindow({ title: "bworld", width: 1280, height: 720 });
// the singleplayer game server, started the first time singleplayer connects so players who only join other servers
@@ -40,16 +61,16 @@ function singleplayer_host(): Promise<Host> {
return host;
}
// the world gets saved before the app closes
// the world gets saved before the app closes. it always exits by itself: deno desktop's own shutdown freezes on the
// last frame when chromium's ctrl+w closed the window, and Deno.serve keeps the process alive anyway
win.addEventListener("close", async (event) => {
if (!host) {
return;
}
event.preventDefault();
try {
await (await host).shutdown();
} catch (e) {
console.error((e as Error).message);
if (host) {
try {
await (await host).shutdown();
} catch (e) {
console.error((e as Error).message);
}
}
Deno.exit(0);
});
@@ -76,7 +97,7 @@ Deno.serve(async (req) => {
return new Response((e as Error).message, { status: 500 });
}
}
return serve_static(BUILD_DIR, req, url);
return serve_static(await client_dir, req, url);
});
// where the app keeps its worlds, the usual place for app data on each os
+103
View File
@@ -0,0 +1,103 @@
import { assert, assertEquals } from "@std/assert";
import { join } from "@std/path";
import { CLIENT_MANIFEST, client_manifest, sha256, update_client } from "$/desktop/client_updates.ts";
const PROTOCOL = 7;
// a build folder with these files and their manifest
async function make_build(dir: string, files: Record<string, string>, protocol = PROTOCOL) {
const hashes: Record<string, string> = {};
for (const [path, text] of Object.entries(files)) {
const bytes = new TextEncoder().encode(text);
Deno.mkdirSync(join(dir, path, ".."), { recursive: true });
Deno.writeFileSync(join(dir, path), bytes);
hashes[path] = await sha256(bytes);
}
const manifest = await client_manifest(hashes, protocol);
Deno.writeTextFileSync(join(dir, CLIENT_MANIFEST), JSON.stringify(manifest));
return manifest;
}
// the site as a folder, and what's been downloaded from it
function site(dir: string) {
const downloaded: string[] = [];
const fetch = (url: string | URL | Request) => {
const path = String(url).replace("https://site.test/", "");
downloaded.push(path);
try {
return Promise.resolve(new Response(Deno.readFileSync(join(dir, path))));
} catch {
return Promise.resolve(new Response("not found", { status: 404 }));
}
};
return { fetch: fetch as typeof globalThis.fetch, downloaded };
}
const FILES = { "client/main.js": "the game", "client/index.html": "<html>", "assets/sprites/gui.png": "pixels" };
function setup() {
const root = Deno.makeTempDirSync();
const dirs = { bundled: join(root, "bundled"), site: join(root, "site"), cache: join(root, "cache") };
return {
root,
dirs,
options: (fetch: typeof globalThis.fetch) => ({
source: "https://site.test",
bundled_dir: dirs.bundled,
cache_dir: dirs.cache,
protocol: PROTOCOL,
fetch,
}),
};
}
Deno.test("the app plays its own client when the site's is the same", async () => {
const { root, dirs, options } = setup();
await make_build(dirs.bundled, FILES);
await make_build(dirs.site, FILES);
const { fetch, downloaded } = site(dirs.site);
assertEquals(await update_client(options(fetch)), dirs.bundled);
assertEquals(downloaded, [CLIENT_MANIFEST]);
Deno.removeSync(root, { recursive: true });
});
Deno.test("a newer client on the site is downloaded, only the files that changed", async () => {
const { root, dirs, options } = setup();
await make_build(dirs.bundled, FILES);
const newer = await make_build(dirs.site, { ...FILES, "client/main.js": "the game, but better" });
const { fetch, downloaded } = site(dirs.site);
const played = await update_client(options(fetch));
assertEquals(played, join(dirs.cache, newer.build));
assertEquals(Deno.readTextFileSync(join(played, "client/main.js")), "the game, but better");
assertEquals(Deno.readTextFileSync(join(played, "assets/sprites/gui.png")), "pixels");
assertEquals(downloaded, [CLIENT_MANIFEST, "client/main.js"]);
// the next launch already has it, and offline it's still what's played
assertEquals(await update_client(options(fetch)), played);
const offline = (() => Promise.reject(new Error("offline"))) as typeof globalThis.fetch;
assertEquals(await update_client(options(offline)), played);
Deno.removeSync(root, { recursive: true });
});
Deno.test("a client for another protocol isn't used, the singleplayer server couldn't talk to it", async () => {
const { root, dirs, options } = setup();
await make_build(dirs.bundled, FILES);
await make_build(dirs.site, { ...FILES, "client/main.js": "a newer protocol" }, PROTOCOL + 1);
const { fetch, downloaded } = site(dirs.site);
assertEquals(await update_client(options(fetch)), dirs.bundled);
assertEquals(downloaded, [CLIENT_MANIFEST]);
Deno.removeSync(root, { recursive: true });
});
Deno.test("a download that doesn't match the manifest is thrown away", async () => {
const { root, dirs, options } = setup();
await make_build(dirs.bundled, FILES);
await make_build(dirs.site, { ...FILES, "client/main.js": "the game, but better" });
// changed after the manifest was made, like a half uploaded site
Deno.writeTextFileSync(join(dirs.site, "client/main.js"), "something else");
const { fetch } = site(dirs.site);
assertEquals(await update_client(options(fetch)), dirs.bundled);
assertEquals([...Deno.readDirSync(dirs.cache)], []);
Deno.removeSync(root, { recursive: true });
});