Skip to content
Merged
Prev Previous commit
Next Next commit
refactor(web): deduplicate WASM engine, IndexedDB helper, and DOM el(…
…) across web/src
  • Loading branch information
kyya committed Nov 28, 2026
commit 127b8ca97dee7b0ff8abde8d2e8801c2d43964b0
175 changes: 41 additions & 134 deletions web/src/catengine.ts
Original file line number Diff line number Diff line change
@@ -1,134 +1,41 @@
// The tailcat engine's page half (tailcat.ts, docs/WEB-006-tailcat.md): the
// code that runs only once a tailcat host needs it, a chunk of its own.
// It loads the engine through the loader (loader.ts): Go's wasm_exec.js
// (tailcat/exec), then the gzipped module (tailcat/engine), which the
// loader's cache keeps; and it carries HTTP and WebSockets to a host over
// the engine's tailcat client.
import { failure, t } from "./i18n";
import { loader } from "./loader";
import type { SocketLike, Transport } from "./rex";
import { EngineCat, NoCatEngine } from "./tailcat";

/** Go's wasm_exec.js, which tailcat/exec defines. */
declare class Go {
importObject: WebAssembly.Imports;
run(instance: WebAssembly.Instance): Promise<void>;
}

/**
* Downloads the engine, reporting the compressed bytes as they come,
* unpacks it with DecompressionStream and starts Go's runtime, which sets
* gorexTailcat. A module that arrives unpacked (a server that decoded it)
* is taken as it is. A build without Go has no engine (NoCatEngine).
*/
export async function loadEngine(progress: (received: number, total: number) => void, starting: () => void): Promise<void> {
await loader.init();
const a = loader.asset("tailcat/engine");
if (!a || !loader.asset("tailcat/exec")) throw new NoCatEngine();
await loader.script("tailcat/exec");
let packed: Uint8Array = await loader.load("tailcat/engine", { progress: (received, total) => progress(received, total ?? a.bytes) });
loader.release("tailcat/engine");
starting();
let module: ArrayBuffer;
if (packed[0] === 0x1f && packed[1] === 0x8b) {
const stream = new Blob([packed as BlobPart]).stream().pipeThrough(new DecompressionStream("gzip"));
module = await new Response(stream).arrayBuffer();
} else if (packed[0] === 0 && packed[1] === 0x61 && packed[2] === 0x73 && packed[3] === 0x6d) {
module = packed.buffer as ArrayBuffer;
} else {
throw failure(() => t("tsNotEngine"));
}
packed = new Uint8Array(0);
const go = new Go();
const { instance } = await WebAssembly.instantiate(module, go.importObject);
go.run(instance).then(() => console.warn("tailcat: the engine exited"));
if (typeof (globalThis as any).gorexTailcat !== "function") throw failure(() => t("tsEngineNotStarted"));
}

/** A WebSocket over the engine, as SocketLike. Its events come after the engine's call returns. */
export class TailcatSocket implements SocketLike {
binaryType: BinaryType = "blob";
protocol = "";
onopen: ((e: Event) => any) | null = null;
onmessage: ((m: MessageEvent) => any) | null = null;
onclose: ((e: CloseEvent) => any) | null = null;
private h?: ReturnType<EngineCat["socket"]>;

constructor(node: EngineCat | undefined, address: string, path: string, protocol: string) {
if (!node) {
queueMicrotask(() => this.onclose?.(new CloseEvent("close", { code: 1006, reason: t("tcIsOff") })));
return;
}
this.h = node.socket(address, path, protocol, (kind, a, b) => queueMicrotask(() => this.event(kind, a, b)));
}

private event(kind: string, a: any, b: any) {
if (kind === "open") {
this.protocol = a ?? "";
this.onopen?.(new Event("open"));
} else if (kind === "message") {
let data: any = a;
if (typeof a !== "string") {
const u = a as Uint8Array;
data = this.binaryType === "arraybuffer" ? u.buffer.slice(u.byteOffset, u.byteOffset + u.byteLength) : new Blob([u as BlobPart]);
}
this.onmessage?.(new MessageEvent("message", { data }));
} else if (kind === "close") {
this.onclose?.(new CloseEvent("close", { code: a, reason: b ?? "", wasClean: a !== 1006 }));
}
}

send(d: string | ArrayBufferLike | ArrayBufferView) {
if (typeof d === "string") this.h?.send(d);
else if (ArrayBuffer.isView(d)) this.h?.send(new Uint8Array(d.buffer, d.byteOffset, d.byteLength));
else this.h?.send(new Uint8Array(d));
}

close(code = 1000, reason = "") {
this.h?.close(code, reason);
}
}

/** Statuses whose Response has no body. */
const nullBody = new Set([101, 103, 204, 205, 304]);

/** HTTP and WebSockets to a host's tailcat address through the engine. */
export function tailcatTransport(node: () => EngineCat | undefined, address: string): Transport {
return {
kind: "tailcat",
socket: (path, protocol) => new TailcatSocket(node(), address, path, protocol),
async fetch(path, init = {}) {
const n = node();
if (!n) throw new TypeError(t("tcIsOff"));
const signal = init.signal;
if (signal?.aborted) throw new DOMException("The request was aborted.", "AbortError");
const headers: Record<string, string> = {};
new Headers(init.headers).forEach((v, k) => (headers[k] = v));
const body = init.body == null ? null : new Uint8Array(await new Response(init.body).arrayBuffer());
const r = await n.request(address, init.method ?? "GET", path, JSON.stringify(headers), body, 30_000);
const reader = r.body;
signal?.addEventListener("abort", () => reader.cancel(), { once: true });
const stream = new ReadableStream<Uint8Array>({
async pull(c) {
for (;;) {
const v = await reader.read();
if (v === null) return c.close();
if (v.length) return c.enqueue(v);
}
},
cancel: () => reader.cancel(),
});
const h = new Headers();
try {
for (const [k, v] of JSON.parse(r.headers) ?? []) h.append(k, v);
} catch {}
const status = r.status >= 200 && r.status <= 599 ? r.status : 502;
if (nullBody.has(status)) reader.cancel();
try {
return new Response(nullBody.has(status) ? null : stream, { status, statusText: r.statusText, headers: h });
} catch {
return new Response(nullBody.has(status) ? null : stream, { status, headers: h });
}
},
};
}
// The tailcat engine's page half (tailcat.ts, docs/WEB-006-tailcat.md): the
// code that runs only once a tailcat host needs it, a chunk of its own.
import { t } from "./i18n";
import type { Transport } from "./rex";
import { EngineCat, NoCatEngine } from "./tailcat";
import { loadWasmEngine, WasmSocket, wasmTransport } from "./wasmengine";

export function loadEngine(progress: (received: number, total: number) => void, starting: () => void): Promise<void> {
return loadWasmEngine(
{
engineAsset: "tailcat/engine",
execAsset: "tailcat/exec",
globalFactory: "gorexTailcat",
logName: "tailcat",
missingError: () => new NoCatEngine(),
},
progress,
starting,
);
}

/** A WebSocket over the tailcat engine, as SocketLike. */
export class TailcatSocket extends WasmSocket {
constructor(node: EngineCat | undefined, address: string, path: string, protocol: string) {
super(
node ? (onEvent) => node.socket(address, path, protocol, onEvent) : undefined,
() => t("tcIsOff"),
);
}
}

/** HTTP and WebSockets to a host's tailcat address through the engine. */
export function tailcatTransport(node: () => EngineCat | undefined, address: string): Transport {
return wasmTransport({
kind: "tailcat",
node,
offReason: () => t("tcIsOff"),
openSocket: (n, path, protocol, onEvent) => n.socket(address, path, protocol, onEvent),
request: (n, method, path, headers, body, timeoutMs) => n.request(address, method, path, headers, body, timeoutMs),
});
}
85 changes: 36 additions & 49 deletions web/src/catstore.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,36 @@
// The web client's tailcat device key (docs/WEB-006-tailcat.md): kept in
// IndexedDB so a reload does not pair again, in memory when the user
// chose this-tab-only. The key is a secret: the page keeps it here and
// shows only its public half.

const dbName = "gorex-tailcat";
const storeName = "key";
const id = "device";

function openDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const idb = typeof indexedDB !== "undefined" ? indexedDB : undefined;
if (!idb) return reject(new Error("indexedDB unavailable"));
const req = idb.open(dbName, 1);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains(storeName)) db.createObjectStore(storeName);
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error("indexedDB open failed"));
});
}

async function withStore<T>(mode: IDBTransactionMode, f: (s: IDBObjectStore) => IDBRequest<T>): Promise<T | undefined> {
try {
const db = await openDB();
try {
return await new Promise<T | undefined>((resolve, reject) => {
const tx = db.transaction(storeName, mode);
const req = f(tx.objectStore(storeName));
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error("indexedDB request failed"));
});
} finally {
db.close();
}
} catch {
return undefined;
}
}

/** The device private key's text, kept across reloads; undefined without storage. */
export const loadKey = () => withStore("readonly", (s) => s.get(id) as IDBRequest<string>);

/** Keeps the device private key's text across reloads. */
export const saveKey = (key: string) => withStore("readwrite", (s) => s.put(key, id));

/** Forgets the device key (this tab only chosen, or reset). */
export const clearKey = () => withStore("readwrite", (s) => s.delete(id));
// The web client's tailcat device key (docs/WEB-006-tailcat.md): kept in
// IndexedDB so a reload does not pair again, in memory when the user
// chose this-tab-only. The key is a secret: the page keeps it here and
// shows only its public half.
import { openDB } from "./idb";

const dbName = "gorex-tailcat";
const storeName = "key";
const id = "device";

async function withStore<T>(mode: IDBTransactionMode, f: (s: IDBObjectStore) => IDBRequest<T>): Promise<T | undefined> {
try {
const db = await openDB(dbName, storeName);
try {
return await new Promise<T | undefined>((resolve, reject) => {
const tx = db.transaction(storeName, mode);
const req = f(tx.objectStore(storeName));
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error("indexedDB request failed"));
});
} finally {
db.close();
}
} catch {
return undefined;
}
}

/** The device private key's text, kept across reloads; undefined without storage. */
export const loadKey = () => withStore("readonly", (s) => s.get(id) as IDBRequest<string>);

/** Keeps the device private key's text across reloads. */
export const saveKey = (key: string) => withStore("readwrite", (s) => s.put(key, id));

/** Forgets the device key (this tab only chosen, or reset). */
export const clearKey = () => withStore("readwrite", (s) => s.delete(id));
7 changes: 1 addition & 6 deletions web/src/corner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@
// the sidebar's footer and Settings' Appearance page hold once a host exists.
// The language is the same setting as Settings › Appearance › Language
// (setLanguage), so the two always show the same choice.
import { el } from "./dom";
import { icon } from "./hosts";
import { Language, language, languages, localize, setLanguage, t, tIn } from "./i18n";
import { prefs } from "./prefs";
import { setTooltip } from "./tooltip";

function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls: string): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
e.className = cls;
return e;
}

/** Fills mount with the language menu and the Settings button. */
export function mountCorner(mount: HTMLElement, openSettings: () => void) {
const button = el("button", "corner-button corner-lang");
Expand Down
7 changes: 7 additions & 0 deletions web/src/dom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** Creates an HTML element with an optional className and textContent. */
export function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string, text?: string): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined) e.textContent = text;
return e;
}
8 changes: 1 addition & 7 deletions web/src/guide.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,13 @@
// follow the node (tailnet.ts): what happens, the engine's download, the
// sign-in in a tab of its own, and the hosts found, with what to do when
// none are. Escape or Close hides it; a sign-in on its way goes on.
import { el } from "./dom";
import { allowCommand, commandBox, Host, icon } from "./hosts";
import { formatList, onLanguageChange, PlainKey, t } from "./i18n";
import { ProgressView } from "./progress";
import { Tailnet, TailnetHost } from "./tailnet";
import { setTooltip } from "./tooltip";

function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string, text?: string): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined) e.textContent = text;
return e;
}

function button(label: string, cls = "host-add", glyph?: string): HTMLButtonElement {
const b = el("button", cls);
b.type = "button";
Expand Down
8 changes: 1 addition & 7 deletions web/src/hosts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// user adds each one, and each one must trust this page's origin. Hosts
// found on the tailnet by built-in Tailscale (tailnet.ts) are listed in a
// group of their own, and not kept.
import { el } from "./dom";
import { localize, PlainKey, t } from "./i18n";
import type { LinkState } from "./settings";
import { joinHostURL, SharedGroup, withToken } from "./share";
Expand Down Expand Up @@ -240,13 +241,6 @@ export async function diagnose(url: string, token?: string): Promise<Problem> {
return untrusted(() => t("problemUntrustedText", { url }));
}

function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string, text?: string): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined) e.textContent = text;
return e;
}

/** A lucide icon of the repo, drawn in the text's colour; "tailscale" is Tailscale's own mark. */
export function icon(name: string): HTMLElement {
if (name === "tailscale") return tailscaleMark();
Expand Down
14 changes: 14 additions & 0 deletions web/src/idb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/** Opens (or creates) a version-1 IndexedDB database with a single object store. */
export function openDB(dbName: string, storeName: string): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const idb = typeof indexedDB !== "undefined" ? indexedDB : undefined;
if (!idb) return reject(new Error("indexedDB unavailable"));
const req = idb.open(dbName, 1);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains(storeName)) db.createObjectStore(storeName);
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error("indexedDB open failed"));
});
}
8 changes: 1 addition & 7 deletions web/src/pane.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// One pane of a window: a block's terminal, its stream fed to
// libghostty-vt, drawn on its own canvas, the keys typed written back.
import { el } from "./dom";
import { FindBar } from "./find";
import { glassRedrawn } from "./glass";
import { Ghostty } from "./ghostty";
Expand Down Expand Up @@ -52,13 +53,6 @@ const maxWrite = 128 << 10;

export { describe };

function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls: string, text?: string): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
e.className = cls;
if (text !== undefined) e.textContent = text;
return e;
}

/** The header's buttons, as the desktop's (view.go paneActions), with its lucide icons: split right, split down, zoom and close. */
const actions: [name: string, label: PlainKey][] = [
["split-right", "cmdSplitRight"],
Expand Down
8 changes: 1 addition & 7 deletions web/src/pointer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
// Ctrl (Cmd on the Mac) over a link underlines it, and a click opens it,
// as on the desktop (links.ts): a URL in a new tab, a host's file with
// files.ts.
import { el } from "./dom";
import { Mods } from "./ghostty";
import { icon } from "./hosts";
import { localize, Msg, t } from "./i18n";
Expand Down Expand Up @@ -50,13 +51,6 @@ const autoscrollMs = 15;
/** A handle's knob, in CSS pixels, as iOS's SelectionHandle. */
const knob = 10;

function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls: string, text?: string): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
e.className = cls;
if (text !== undefined) e.textContent = text;
return e;
}

/** A key event's or pointer event's modifiers, as Ghostty's Mods. */
function modsOf(e: { shiftKey: boolean; ctrlKey: boolean; altKey: boolean; metaKey: boolean }): number {
return (e.shiftKey ? Mods.shift : 0) | (e.ctrlKey ? Mods.ctrl : 0) | (e.altKey ? Mods.alt : 0) | (e.metaKey ? Mods.super : 0);
Expand Down
Loading