VibeGame / src /lib /services /console-sync.ts
dylanebert
examples prompts, stop button
7ad6991
import { consoleStore } from "../stores/console";
import { agentService } from "./agent";
type ConsoleMethod = "log" | "warn" | "error" | "info";
export class ConsoleSyncService {
private isSetup = false;
private originalConsole: Record<ConsoleMethod, (...args: unknown[]) => void> =
{} as Record<ConsoleMethod, (...args: unknown[]) => void>;
setup(): void {
if (this.isSetup) return;
this.originalConsole = {
log: console.log.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console),
info: console.info.bind(console),
};
const interceptConsole = (method: ConsoleMethod) => {
const original = this.originalConsole[method];
console[method] = (...args: unknown[]) => {
original(...args);
const firstArg = args[0];
if (typeof firstArg === "string") {
if (
firstArg.includes("[vite]") ||
firstArg.includes("[VibeGame] Console forwarding") ||
firstArg.includes("[DEBUG]") ||
firstArg.includes("hot updated:") ||
firstArg.includes(
"using deprecated parameters for the initialization function",
)
) {
return;
}
}
const message = args
.map((arg) => {
if (arg instanceof Error) {
return arg.message;
} else if (typeof arg === "object") {
try {
return JSON.stringify(arg, null, 2);
} catch {
return String(arg);
}
}
return String(arg);
})
.join(" ");
const messageId = `${Date.now()}-${Math.random()}`;
consoleStore.addMessage(method === "log" ? "info" : method, message);
agentService.sendRawMessage({
type: "console_sync",
payload: {
id: messageId,
type: method === "log" ? "info" : method,
message: message,
timestamp: Date.now(),
},
timestamp: Date.now(),
});
};
};
(["log", "warn", "error", "info"] as ConsoleMethod[]).forEach(
interceptConsole,
);
this.isSetup = true;
}
teardown(): void {
if (!this.isSetup) return;
console.log = this.originalConsole.log;
console.warn = this.originalConsole.warn;
console.error = this.originalConsole.error;
console.info = this.originalConsole.info;
this.originalConsole = {} as Record<
ConsoleMethod,
(...args: unknown[]) => void
>;
this.isSetup = false;
}
}
export const consoleSyncService = new ConsoleSyncService();