Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bun.lock
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"lockfileVersion": 1,
"configVersion": 0,
"workspaces": {
"": {
"name": "@cmux/ghostty-terminal",
Expand Down
86 changes: 58 additions & 28 deletions lib/ghostty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,39 +55,69 @@ export class Ghostty {

/**
* Load Ghostty WASM from URL or file path
* If no path is provided, attempts to load from common default locations
*/
static async load(wasmPath: string): Promise<Ghostty> {
let wasmBytes: ArrayBuffer;
static async load(wasmPath?: string): Promise<Ghostty> {
// Default WASM paths to try (in order)
const defaultPaths = [
// When running in Node/Bun (resolve to file path)
new URL('../ghostty-vt.wasm', import.meta.url).href.replace('file://', ''),
// When published as npm package (browser)
new URL('../ghostty-vt.wasm', import.meta.url).href,
// When used from CDN or local dev
'./ghostty-vt.wasm',
'/ghostty-vt.wasm',
];

const pathsToTry = wasmPath ? [wasmPath] : defaultPaths;
let lastError: Error | null = null;

for (const path of pathsToTry) {
try {
let wasmBytes: ArrayBuffer;

// Try loading as file first (for Node/Bun environments)
try {
const fs = await import('fs/promises');
const buffer = await fs.readFile(path);
wasmBytes = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
} catch (e) {
// Fall back to fetch (for browser environments)
const response = await fetch(path);
if (!response.ok) {
throw new Error(`Failed to fetch WASM: ${response.status} ${response.statusText}`);
}
wasmBytes = await response.arrayBuffer();
if (wasmBytes.byteLength === 0) {
throw new Error(`WASM file is empty (0 bytes). Check path: ${path}`);
}
}

// Try loading as file first (for Node/Bun environments)
try {
const fs = await import('fs/promises');
const buffer = await fs.readFile(wasmPath);
wasmBytes = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
} catch (e) {
// Fall back to fetch (for browser environments)
const response = await fetch(wasmPath);
if (!response.ok) {
throw new Error(`Failed to fetch WASM: ${response.status} ${response.statusText}`);
}
wasmBytes = await response.arrayBuffer();
if (wasmBytes.byteLength === 0) {
throw new Error(`WASM file is empty (0 bytes). Check path: ${wasmPath}`);
// Successfully loaded, instantiate and return
const wasmModule = await WebAssembly.instantiate(wasmBytes, {
env: {
log: (ptr: number, len: number) => {
const instance = (wasmModule as any).instance;
const bytes = new Uint8Array(instance.exports.memory.buffer, ptr, len);
const text = new TextDecoder().decode(bytes);
console.log('[ghostty-wasm]', text);
},
},
});

return new Ghostty(wasmModule.instance);
} catch (e) {
lastError = e instanceof Error ? e : new Error(String(e));
// Try next path
}
}

const wasmModule = await WebAssembly.instantiate(wasmBytes, {
env: {
log: (ptr: number, len: number) => {
const instance = (wasmModule as any).instance;
const bytes = new Uint8Array(instance.exports.memory.buffer, ptr, len);
const text = new TextDecoder().decode(bytes);
console.log('[ghostty-wasm]', text);
},
},
});

return new Ghostty(wasmModule.instance);
// All paths failed
throw new Error(
`Failed to load ghostty-vt.wasm. Tried paths: ${pathsToTry.join(', ')}. ` +
`Last error: ${lastError?.message}. ` +
`You can specify a custom path with: new Terminal({ wasmPath: './path/to/ghostty-vt.wasm' })`
);
}
}

Expand Down
4 changes: 2 additions & 2 deletions lib/input-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,8 @@ describe('InputHandler', () => {

beforeAll(async () => {
// Load WASM once for all tests (expensive operation)
const wasmPath = new URL('../ghostty-vt.wasm', import.meta.url).href;
ghostty = await Ghostty.load(wasmPath);
// wasmPath is now optional - auto-detected
ghostty = await Ghostty.load();
});

beforeEach(() => {
Expand Down
2 changes: 1 addition & 1 deletion lib/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export interface ITerminalOptions {
fontSize?: number; // Default: 15
fontFamily?: string; // Default: 'monospace'
allowTransparency?: boolean;
wasmPath?: string; // Default: '../ghostty-vt.wasm' (relative to examples/)
wasmPath?: string; // Optional: custom WASM path (auto-detected by default)
}

export interface ITheme {
Expand Down
6 changes: 4 additions & 2 deletions lib/terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ export class Terminal implements ITerminalCore {
public textarea?: HTMLTextAreaElement;

// Options
private options: Required<ITerminalOptions>;
private options: Required<Omit<ITerminalOptions, 'wasmPath'>> & {
wasmPath?: string;
};

// Components (created on open())
private ghostty?: Ghostty;
Expand Down Expand Up @@ -79,7 +81,7 @@ export class Terminal implements ITerminalCore {
fontSize: options.fontSize ?? 15,
fontFamily: options.fontFamily ?? 'monospace',
allowTransparency: options.allowTransparency ?? false,
wasmPath: options.wasmPath ?? '../ghostty-vt.wasm',
wasmPath: options.wasmPath, // Optional - Ghostty.load() handles defaults
};

this.cols = this.options.cols;
Expand Down
2 changes: 1 addition & 1 deletion scripts/build-wasm.sh
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ echo "✓ Found Zig $ZIG_VERSION"
GHOSTTY_DIR="/tmp/ghostty-for-wasm"
if [ ! -d "$GHOSTTY_DIR" ]; then
echo "📦 Cloning Ghostty..."
git clone --depth=1 https://github.com/ghostty-org/ghostty.git "$GHOSTTY_DIR"
git clone --depth=1 https://github.com/coder/ghostty.git "$GHOSTTY_DIR"
else
echo "📦 Updating Ghostty..."
cd "$GHOSTTY_DIR"
Expand Down