/** * Native canvas rendering engine for @termless/ghostty — Visual Eyes without * the browser. * * Drives ghostty-web's CanvasRenderer with `@napi-rs/canvas` (Skia, native) * as the backing canvas. No headless Chromium, no Playwright dependency, no * `node:http` server, no SVG round-trip. The renderer sees real Ghostty cell * metrics and paints real glyphs; we encode the resulting Skia surface to PNG * in-process. * * Replaces the legacy `screenshotCanvasPng()` from `vendor/termless/src/canvas-render.ts`. * The legacy export stays callable until the wider migration is complete — * this file is the new path. Callsite migration happens in a later phase. * * Two public entry points: * * - {@link renderAnsiPng} — raw bytes path. Preferred when ANSI is already * on hand (e.g. a recorded PTY snapshot, an MCP-tool capture, the canonical * test fixture). Skips the cells-roundtrip; ghostty-web parses the bytes * directly with the same VT engine real Ghostty uses. * * - {@link renderTerminalPng} — terminal snapshot path. Wraps * {@link cellsToAnsi} + {@link renderAnsiPng}. Useful when the source state * lives in an existing Terminal (xterm.js, vterm, etc.) and you * want a visual of that state through Ghostty's renderer. * * DOM shims are applied lazily on the first call (module-scoped, idempotent) * so importing this file is side-effect free for other tests. * * @see https://github.com/Brooooooklyn/canvas — @napi-rs/canvas (Skia bindings) * @see https://github.com/mitchellh/ghostty — Ghostty (renderer source) */ import { Blob } from "node:buffer" import { readFile } from "node:fs/promises" import { existsSync } from "node:fs" import { join } from "node:path" import { resolveGhosttyWebWasm } from "./load-native.ts" import { createCanvas, GlobalFonts, type Canvas } from "@napi-rs/canvas" import type { Terminal } from "../../../src/terminal/types.ts" import { BUNDLED_FONTS, bundledFontsDir, BUNDLED_PRIMARY_FAMILY, BUNDLED_SYMBOL_FAMILY, BUNDLED_EMOJI_FAMILY, } from "../../../src/render/fonts.ts" import { cellsToAnsi } from "../../../src/terminal/cells-to-ansi.ts" import type { CanvasTheme, RenderOptions, RenderMeta } from "../../../src/render/canvas-types.ts" export type { CanvasTheme, RenderOptions, RenderMeta } from "../../../src/render/canvas-types.ts" // ── Tokyo Night Storm default theme ── const DEFAULT_THEME: Required = { background: "#1a1b26", foreground: "#c0caf5", cursor: "#c0caf5", cursorAccent: "#1a1b26", selectionBackground: "#33467c", selectionForeground: "#c0caf5", black: "#15161e", red: "#f7768e", green: "#9ece6a", yellow: "#e0af68", blue: "#7aa2f7", magenta: "#bb9af7", cyan: "#7dcfff", white: "#a9b1d6", brightBlack: "#414868", brightRed: "#f7768e", brightGreen: "#9ece6a", brightYellow: "#e0af68", brightBlue: "#7aa2f7", brightMagenta: "#bb9af7", brightCyan: "#7dcfff", brightWhite: "#c0caf5", } // 64 MiPixels = 256 MiB for one raw RGBA surface. This still permits an 8K // frame with headroom while bounding Skia's additional backing-store cost. const MAX_CANVAS_PIXELS = 64 * 1024 * 1024 // ── DOM shim (lazy, idempotent) ── let domShimApplied = false /** * Apply just-enough browser globals so ghostty-web's CanvasRenderer thinks it * has a DOM. Idempotent — safe to call repeatedly. Module-scoped, applied * lazily on the first render so importing this file is side-effect-free. * * What ghostty-web's CanvasRenderer actually touches (verified empirically * in `tmp-spike/native-canvas-render.ts`): * - `canvas.style.{width,height} = "Npx"` — settable, never read. * - `canvas.width / canvas.height` — already on Canvas, no shim needed. * - `document.createElement("canvas")` — inside `measureFont`; gets a 1×1 * throwaway and immediately calls `getContext`. * - `window.devicePixelRatio` — read for default DPR resolution. * * Other DOM features (addEventListener, getBoundingClientRect, parentNode, * etc.) live in Terminal/SelectionManager which we don't instantiate — they * never touch CanvasRenderer alone. */ function ensureDomShim(dpr: number): void { if (domShimApplied) { // Update DPR if needed — last writer wins. ghostty-web reads this lazily. const w = (globalThis as unknown as { window?: { devicePixelRatio?: number } }).window if (w) w.devicePixelRatio = dpr ;(globalThis as unknown as { devicePixelRatio?: number }).devicePixelRatio = dpr return } // 1. canvas.style proxy — writes only, never reads. const protoSample = createCanvas(1, 1) const napiCanvasProto = Object.getPrototypeOf(protoSample) as object if (!("style" in napiCanvasProto)) { Object.defineProperty(napiCanvasProto, "style", { configurable: true, get(this: { __style?: Record }) { if (!this.__style) this.__style = {} return this.__style }, }) } // 2. document.createElement('canvas') — used inside ghostty-web's measureFont. const g = globalThis as unknown as { document?: { createElement: (tag: string) => unknown } window?: { devicePixelRatio?: number } devicePixelRatio?: number } if (!g.document) { g.document = { createElement(tag: string) { if (tag === "canvas") { // (1,1) NOT (0,0) — @napi-rs/canvas rejects 0×0. return createCanvas(1, 1) } throw new Error(`document.createElement: unsupported tag '${tag}' (termless DOM shim)`) }, } } // 3. window.devicePixelRatio. if (!g.window) { g.window = { devicePixelRatio: dpr } } else { g.window.devicePixelRatio = dpr } if (g.devicePixelRatio == null) g.devicePixelRatio = dpr domShimApplied = true } // ── ghostty-web ESM loader ── interface GhosttyWebModule { Ghostty: { load: (wasmPath?: string) => Promise<{ createTerminal: (cols: number, rows: number) => GhosttyTerminalHandle }> } CanvasRenderer: new (canvas: unknown, opts: unknown) => GhosttyCanvasRenderer } interface GhosttyTerminalHandle { write: (data: string | Uint8Array) => void update: () => void } interface GhosttyCanvasRenderer { remeasureFont(): void resize(cols: number, rows: number): void setCursorBlink(b: boolean): void setCursorVisible?: (v: boolean) => void render(buf: unknown, forceAll?: boolean): void metrics: { width: number; height: number; baseline: number } charWidth: number charHeight: number } let ghosttyModuleCache: { mod: GhosttyWebModule; wasmPath: string } | null = null async function loadGhosttyWeb(): Promise<{ mod: GhosttyWebModule; wasmPath: string }> { if (ghosttyModuleCache) return ghosttyModuleCache try { // Resolve via the wasm subpath (always exported) and walk up to package root. const wasmPath = resolveGhosttyWebWasm() const pkgRoot = wasmPath.slice(0, wasmPath.length - "/ghostty-vt.wasm".length) const pkgJsonPath = `${pkgRoot}/package.json` const pkgJson = JSON.parse((await readFile(pkgJsonPath)).toString()) as { exports?: { ["."]?: { import?: string } } module?: string main?: string } const esmRel: string = pkgJson.exports?.["."]?.import ?? pkgJson.module ?? pkgJson.main ?? "" if (!esmRel) throw new Error("ghostty-web: no ESM export entry resolvable from package.json") const jsPath = `${pkgRoot}/${esmRel.replace(/^\.\//, "")}` const mod = (await import(jsPath)) as GhosttyWebModule ghosttyModuleCache = { mod, wasmPath } return ghosttyModuleCache } catch (cause) { throw new Error("renderAnsiPng() requires the ghostty-web package. Install it:\n bun add ghostty-web", { cause }) } } /** * Load the ghostty-web WASM in a way that works under both Bun and Node * (vitest's default pool). ghostty-web's `Ghostty.load(path)` calls a * try-chain of Bun.file → vite-browser-external readFile (no-op shim under * node) → fetch(path). On Node, the first two fail and fetch can't handle a * raw filesystem path ("Failed to parse URL"); even a `file://` URL trips * node's fetch implementation. Pre-reading the bytes via fs and stubbing * globalThis.fetch for the duration of load() keeps the engine's contract * (works regardless of runtime) without forking ghostty-web. * * Bun gets the fast path: `Ghostty.load(wasmPath)` hits Bun.file directly. */ async function loadGhosttyInstance( mod: GhosttyWebModule, wasmPath: string, ): Promise>> { const hasBun = typeof (globalThis as { Bun?: unknown }).Bun !== "undefined" if (hasBun) { return mod.Ghostty.load(wasmPath) } // Node path: pre-read bytes, stub fetch for the wasmPath, call load. const bytes = await readFile(wasmPath) const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch ;(globalThis as { fetch?: typeof fetch }).fetch = (async (input: unknown) => { if (input === wasmPath) { return new Response( new Blob([bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer]), { status: 200 }, ) } if (!originalFetch) throw new Error("global fetch not available") return originalFetch(input as RequestInfo) }) as typeof fetch try { return await mod.Ghostty.load(wasmPath) } finally { ;(globalThis as { fetch?: typeof fetch }).fetch = originalFetch } } // ── Font registration ── const registeredFontPaths = new Set() const BUNDLED_FONT_NAME = "TermlessCanvasFont" function registerFontIfNeeded(fontPath: string): void { if (registeredFontPaths.has(fontPath)) return if (!existsSync(fontPath)) { throw new Error(`renderAnsiPng(): fontPath does not exist: ${fontPath}`) } GlobalFonts.registerFromPath(fontPath, BUNDLED_FONT_NAME) registeredFontPaths.add(fontPath) } // ── Bundled fallback fonts ── // // `@napi-rs/canvas`'s built-in `monospace` alias resolves, per platform, to // whatever Skia's font manager picks — and that face has unstable cell metrics // (on a stock napi-canvas install the advance for "monospace" at 16px measures // ~13px, aspect ~0.81, far wider than a real terminal font's ~0.6). Rendering // against it produces a uniform "letter-spacing" stretch: glyphs are painted at // their natural advance inside cells that are ~35% too wide. Worse, the alias is // not guaranteed to exist at all on minimal Linux CI runners, where it can fall // through to a sans-serif (proportional) face — different metrics on every OS. // // So instead of trusting `monospace`, termless bundles its own fonts and // registers them process-wide. This makes the canvas geometry **deterministic // and identical on every platform and every render path** (Terminal.screenshot, // renderTerminalPng, the frame tracer) — which is the contract a visual- // regression tool must keep. // // Three faces, each earning its place: // - JetBrains Mono — the primary monospace face. OFL-licensed, true fixed // pitch, broad Latin + box-drawing + geometric-shape coverage. // - Noto Sans Symbols2 — fallback for terminal symbol glyphs JetBrains Mono // lacks (hourglass U+29D7, rarer geometric shapes, arrows). // - Noto Emoji (monochrome) — fallback for emoji (📁 📋 📄 and friends). // Monochrome, not color: a terminal-faithful look, and it composes with the // truecolor SGR fg the renderer already applies. // // All three are appended to *every* render's `fontFamily` chain so per-glyph // fallback Just Works regardless of what primary face the caller requested. // The bundled font assets, family names, and directory resolver are owned by // `@termless/core` (`src/render/fonts.ts`) — the foundational package. Both // the canvas renderer here and core's `@resvg/resvg-js` SVG→raster path // (gif.ts / apng.ts / png.ts) consume the same single bundled copy. /** * The fallback chain appended to every render. Order matters: symbols then * emoji, both after whatever the caller's primary face is. */ const BUNDLED_FALLBACK_CHAIN = `${BUNDLED_SYMBOL_FAMILY}, ${BUNDLED_EMOJI_FAMILY}` let bundledFontsRegistered = false /** * Register the bundled fallback fonts process-wide. Idempotent — the first * call registers, later calls are no-ops. A missing bold, symbol or emoji * face is skipped with a warning: a render with a partial chain still beats a * hard failure (Skia synthesizes bold). A missing Regular primary face throws: * it sets the cell geometry, and without it the cell measures zero wide and * the render fails later on a canvas of width 0, far from why. */ function ensureBundledFonts(): void { if (bundledFontsRegistered) return const dir = bundledFontsDir() for (const { file, family, weight } of BUNDLED_FONTS) { const path = join(dir, file) if (!existsSync(path) && family === BUNDLED_PRIMARY_FAMILY && weight === 400) { throw new Error( `[termless/ghostty] the bundled primary font ${path} is missing; @termless/core ships assets/fonts, so install it beside @termless/ghostty`, ) } } bundledFontsRegistered = true for (const { file, family } of BUNDLED_FONTS) { const path = join(dir, file) if (!existsSync(path)) { // eslint-disable-next-line no-console console.warn(`[termless/ghostty] bundled font missing, skipping: ${path}`) continue } GlobalFonts.registerFromPath(path, family) } } /** * Build the final `font-family` CSS list for a render. * * - The bundled monospace face (`TermlessMono`) is the default primary when * the caller passes neither `fontPath` nor an explicit `fontFamily` — this * is what makes the geometry deterministic instead of leaning on the * platform `monospace` alias. * - A caller-supplied `fontPath` is registered and still takes precedence. * - The bundled symbol + emoji faces are always appended last so per-glyph * fallback covers coverage gaps in whatever the primary face is. */ function buildFontFamily(opts: Pick): string { const parts: string[] = [] if (opts.fontPath) { registerFontIfNeeded(opts.fontPath) parts.push(BUNDLED_FONT_NAME) } if (opts.fontFamily) { parts.push(opts.fontFamily) } // The bundled monospace face is the default primary — used when the caller // gave no font of their own. Appending it unconditionally is also harmless: // it just acts as one more fallback when a caller font is present. parts.push(BUNDLED_PRIMARY_FAMILY) parts.push(BUNDLED_FALLBACK_CHAIN) return parts.join(", ") } // ── Cursor style mapping ── function mapCursorStyle(s: RenderOptions["cursorStyle"]): "block" | "underline" | "bar" { if (s === "beam") return "bar" return s ?? "block" } // ── Resample (Skia in-process) ── function resampleCanvas(src: Canvas, targetWidth: number, targetHeight: number): Canvas { if (src.width === targetWidth && src.height === targetHeight) return src const resized = createCanvas(targetWidth, targetHeight) const ctx = resized.getContext("2d") ctx.imageSmoothingEnabled = true ctx.imageSmoothingQuality = "high" // Type quirk: @napi-rs/canvas's drawImage accepts a Canvas but its DOM-style // signature requires CanvasImageSource. Cast through unknown. ctx.drawImage(src as unknown as never, 0, 0, targetWidth, targetHeight) return resized } // ── Public API ── const DECAWM_OFF_PREAMBLE = "\x1b[H\x1b[2J\x1b[?7l\x1b[?25l" function toUtf8String(bytes: string | Uint8Array): string { if (typeof bytes === "string") return bytes return new TextDecoder().decode(bytes) } function assertCanvasPixelCeiling(width: number, height: number, surface: "render" | "target"): void { if (!Number.isSafeInteger(width) || width <= 0 || !Number.isSafeInteger(height) || height <= 0) { throw new RangeError( `Termless canvas ${surface} dimensions must be positive safe integers; received ${width}x${height}`, ) } const pixels = width * height if (!Number.isSafeInteger(pixels) || pixels > MAX_CANVAS_PIXELS) { throw new RangeError( `Termless canvas ${surface} ${width}x${height} (${pixels} pixels) exceeds the ${MAX_CANVAS_PIXELS}-pixel ceiling`, ) } } /** * The baseline that centers the font's ascent + descent box in the cell, the way * a real terminal places text. ghostty-web measures only "M" (cap height, no * descent) and puts the baseline one pixel under the cap top, so capitals hugged * the cell's top edge with most of the free space beneath them (operator, * 2026-09-25, on a pane screenshot). */ function centeredBaseline(canvas: Canvas, font: string, cellHeight: number): number { const ctx = canvas.getContext("2d") ctx.font = font const metrics = ctx.measureText("M") const ascent = metrics.fontBoundingBoxAscent const descent = metrics.fontBoundingBoxDescent if (!Number.isFinite(ascent) || !Number.isFinite(descent)) { throw new Error(`termless: the canvas reports no font ascent/descent for ${font}; cannot place the baseline`) } const baseline = Math.round(ascent + (cellHeight - ascent - descent) / 2) return Math.min(Math.max(baseline, 1), cellHeight - 1) } /** * Render raw ANSI bytes to a PNG via ghostty-web's CanvasRenderer + native * Skia canvas. This is the preferred entry point when the ANSI source is * already on hand — bypasses the cells round-trip entirely. * * Prepends a deterministic preamble (`\x1b[H \x1b[2J \x1b[?7l \x1b[?25l`) * unless the input already starts with it. The preamble is what stops * ghostty-web from dropping the top N rows when every row fills the right * margin (DECAWM pending-wrap behavior). * * @example * ```ts * const png = await renderAnsiPng("\x1b[31mhello\x1b[0m", { * cols: 80, rows: 24, * fontPath: "/Users/me/Library/Fonts/FiraMonoNerdFontMono-Bold.otf", * }) * await Bun.write("./out.png", png) * ``` */ export async function renderAnsiPng( ansi: string | Uint8Array, opts: RenderOptions & { returnMeta: true }, ): Promise<{ png: Uint8Array; meta: RenderMeta }> export async function renderAnsiPng(ansi: string | Uint8Array, opts?: RenderOptions): Promise export async function renderAnsiPng( ansi: string | Uint8Array, opts: RenderOptions = {}, ): Promise { const cols = opts.cols ?? 100 const rows = opts.rows ?? 40 const fontSize = opts.fontSize ?? 16 const dpr = opts.dpr ?? 2 const theme: Required = { ...DEFAULT_THEME, ...opts.theme } const cursorStyle = mapCursorStyle(opts.cursorStyle) const cursorBlink = opts.cursorBlink ?? false if (opts.targetWidth != null && opts.targetHeight != null) { assertCanvasPixelCeiling(opts.targetWidth, opts.targetHeight, "target") } // Reject absurd terminal geometry before either the WASM cell grid or Skia // can allocate. The exact post-font-measurement dimensions are checked again // immediately before CanvasRenderer.resize(). const estimatedCellWidth = opts.cellWidth ?? Math.ceil(fontSize * 0.6) const estimatedCellHeight = opts.cellHeight ?? Math.ceil(fontSize * 1.25) const estimatedWidth = Math.ceil(cols * estimatedCellWidth * dpr) const estimatedHeight = Math.ceil(rows * estimatedCellHeight * dpr) assertCanvasPixelCeiling(estimatedWidth, estimatedHeight, "render") // 1. DOM shim (idempotent). ensureDomShim(dpr) // 2. Font registration (idempotent). The bundled monospace + symbol + emoji // faces are registered process-wide and woven into the font-family chain // so geometry is deterministic and emoji/symbols never fall to tofu — // regardless of platform or whether the caller supplied a font. ensureBundledFonts() const fontFamily = buildFontFamily(opts) // 3. Load ghostty-web ESM bundle + WASM. const { mod, wasmPath } = await loadGhosttyWeb() const ghostty = await loadGhosttyInstance(mod, wasmPath) // 4. Create the WASM terminal. const terminal = ghostty.createTerminal(cols, rows) // 5. CanvasRenderer needs a positive bootstrap canvas to measure fonts. Keep // it at 1×1 so the only target-sized allocation happens after the exact // measured geometry passes the ceiling below. let canvas = createCanvas(1, 1) as Canvas // 6. Instantiate CanvasRenderer with our shim'd canvas. const renderer = new mod.CanvasRenderer(canvas, { fontSize, fontFamily, cursorStyle, cursorBlink, devicePixelRatio: dpr, theme, }) // 7. Measure + resize. The metrics override (cellWidth / cellHeight) lands // AFTER remeasureFont and BEFORE resize, mirroring the legacy path. renderer.remeasureFont() if (opts.cellWidth != null) renderer.metrics.width = opts.cellWidth if (opts.cellHeight != null) renderer.metrics.height = opts.cellHeight renderer.metrics.baseline = centeredBaseline(canvas, `${fontSize}px ${fontFamily}`, renderer.metrics.height) const renderWidth = Math.ceil(cols * renderer.metrics.width * dpr) const renderHeight = Math.ceil(rows * renderer.metrics.height * dpr) assertCanvasPixelCeiling(renderWidth, renderHeight, "render") renderer.resize(cols, rows) renderer.setCursorBlink(cursorBlink) if (opts.hideCursor && typeof renderer.setCursorVisible === "function") { renderer.setCursorVisible(false) } // 8. Feed bytes. Prepend the DECAWM-off preamble unless the caller already // included it (idempotent — the preamble is purely state-setting). const ansiStr = toUtf8String(ansi) const bytes = ansiStr.startsWith(DECAWM_OFF_PREAMBLE) ? ansiStr : DECAWM_OFF_PREAMBLE + ansiStr terminal.write(bytes) terminal.update() // 9. Paint. renderer.render(terminal, true) // 10. Optional in-process resample. if (opts.targetWidth != null && opts.targetHeight != null) { canvas = resampleCanvas(canvas, opts.targetWidth, opts.targetHeight) } // 11. Encode PNG via the async encoder (off the main loop). const png = await canvas.encode("png") const out = png instanceof Uint8Array ? png : new Uint8Array(png) if (opts.returnMeta) { const meta: RenderMeta = { width: canvas.width, height: canvas.height, cols, rows, cellWidth: renderer.metrics.width, cellHeight: renderer.metrics.height, dpr, } return { png: out, meta } } return out } /** * Render an in-memory Terminal to a PNG via ghostty-web. Wraps * {@link cellsToAnsi} + {@link renderAnsiPng}. * * Useful when the source state lives in a terminal backed by a different * VT parser (xterm.js, vterm, libvterm, etc.) and you want a visual that * goes through Ghostty's renderer. The trade-off is a cells round-trip: * parser disagreements between the source backend and ghostty-web get * baked into the cells before they reach the renderer. * * For maximum fidelity, capture the raw bytes you fed to the source * terminal and pass them to {@link renderAnsiPng} directly. */ export async function renderTerminalPng( // oxlint-disable-next-line typescript/no-deprecated -- renderTerminalPng takes the Terminal read contract until unterm phase A4 moves it to Emulator terminal: Terminal, opts: RenderOptions & { returnMeta: true }, ): Promise<{ png: Uint8Array; meta: RenderMeta }> // oxlint-disable-next-line typescript/no-deprecated -- renderTerminalPng takes the Terminal read contract until unterm phase A4 moves it to Emulator export async function renderTerminalPng(terminal: Terminal, opts?: RenderOptions): Promise export async function renderTerminalPng( // oxlint-disable-next-line typescript/no-deprecated -- renderTerminalPng takes the Terminal read contract until unterm phase A4 moves it to Emulator terminal: Terminal, opts: RenderOptions = {}, ): Promise { const cols = opts.cols ?? inferCols(terminal) ?? 100 const rows = opts.rows ?? inferRows(terminal) ?? 40 const ansi = cellsToAnsi(terminal, { cols, rows }) if (opts.returnMeta) { return renderAnsiPng(ansi, { ...opts, cols, rows, returnMeta: true }) } return renderAnsiPng(ansi, { ...opts, cols, rows }) } // ── Inference helpers ── // oxlint-disable-next-line typescript/no-deprecated -- renderTerminalPng takes the Terminal read contract until unterm phase A4 moves it to Emulator function inferCols(terminal: Terminal): number | null { try { const lines = terminal.getRows() if (lines.length === 0) return null return lines[lines.length - 1]?.length || null } catch { return null } } // oxlint-disable-next-line typescript/no-deprecated -- renderTerminalPng takes the Terminal read contract until unterm phase A4 moves it to Emulator function inferRows(terminal: Terminal): number | null { let lineCount: number try { lineCount = terminal.getRows().length if (lineCount === 0) return null } catch { return null } try { const scrollback = terminal.getScrollback() const viewportRows = scrollback.screenRows if (!Number.isSafeInteger(viewportRows) || viewportRows <= 0) return lineCount return Math.min(lineCount, viewportRows) } catch { return lineCount } } // ── Internal exports for testing ── /** @internal — reset the DOM-shim sentinel so tests can verify the lazy path. */ export function _resetDomShimForTesting(): void { domShimApplied = false }