turborepo and better logging
This commit is contained in:
7 files changed
+188
-15
No files matched your search
@@ -54,7 +54,7 @@ npx t3
|
||||
|
||||
## Scripts
|
||||
|
||||
- `bun run dev` — Starts both the WebSocket server and Vite dev server in parallel with hot reload.
|
||||
- `bun run dev` — Starts contracts, server, and web dev tasks via Turborepo's parallel task runner.
|
||||
- `bun run dev:server` — Starts just the WebSocket server (uses tsx for TS execution).
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the renderer.
|
||||
- `bun run start` — Runs the production server (serves built renderer as static files).
|
||||
|
||||
+14
-10
@@ -4,12 +4,14 @@ import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { fixPath } from "./fixPath";
|
||||
import { createLogger } from "./logger";
|
||||
import { createServer } from "./wsServer";
|
||||
|
||||
fixPath();
|
||||
|
||||
const DEFAULT_PORT = 3773;
|
||||
const cwd = process.cwd();
|
||||
const logger = createLogger("server");
|
||||
|
||||
async function findAvailablePort(preferred: number): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -65,11 +67,12 @@ async function main() {
|
||||
const staticDir = devUrl ? undefined : resolveStaticDir();
|
||||
|
||||
if (!devUrl && !staticDir) {
|
||||
console.warn(
|
||||
"⚠ No built renderer found and no VITE_DEV_SERVER_URL set. The web UI will not be available.",
|
||||
);
|
||||
console.warn(
|
||||
" Run `bun run --cwd apps/renderer build` or set VITE_DEV_SERVER_URL for dev mode.",
|
||||
logger.warn(
|
||||
"renderer bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
|
||||
{
|
||||
hint:
|
||||
"Run `bun run --cwd apps/renderer build` or set VITE_DEV_SERVER_URL for dev mode.",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -77,8 +80,7 @@ async function main() {
|
||||
await server.start();
|
||||
|
||||
const url = `http://localhost:${port}`;
|
||||
console.log(`\n ✦ CodeThing running at ${url}`);
|
||||
console.log(` ✦ Project: ${cwd}\n`);
|
||||
logger.info("CodeThing running", { url, cwd });
|
||||
|
||||
// Open browser (dynamic import because `open` is ESM-only)
|
||||
try {
|
||||
@@ -86,12 +88,14 @@ async function main() {
|
||||
const target = devUrl ?? url;
|
||||
await open.default(target);
|
||||
} catch {
|
||||
console.log(` Open ${devUrl ?? url} in your browser to get started.\n`);
|
||||
logger.info("browser auto-open unavailable", {
|
||||
hint: `Open ${devUrl ?? url} in your browser.`,
|
||||
});
|
||||
}
|
||||
|
||||
// Graceful shutdown
|
||||
const shutdown = () => {
|
||||
console.log("\n Shutting down...\n");
|
||||
logger.info("shutting down");
|
||||
server.stop();
|
||||
process.exit(0);
|
||||
};
|
||||
@@ -101,6 +105,6 @@ async function main() {
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error("Failed to start CodeThing:", err);
|
||||
logger.error("failed to start CodeThing", { error: err });
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import util from "node:util";
|
||||
|
||||
type LogLevel = "info" | "warn" | "error" | "event";
|
||||
|
||||
type LogContext = Record<string, unknown>;
|
||||
|
||||
const ANSI = {
|
||||
reset: "\u001b[0m",
|
||||
dim: "\u001b[2m",
|
||||
cyan: "\u001b[36m",
|
||||
yellow: "\u001b[33m",
|
||||
red: "\u001b[31m",
|
||||
magenta: "\u001b[35m",
|
||||
} as const;
|
||||
|
||||
const LEVEL_LABEL: Record<LogLevel, string> = {
|
||||
info: "INFO",
|
||||
warn: "WARN",
|
||||
error: "ERROR",
|
||||
event: "EVENT",
|
||||
};
|
||||
|
||||
const LEVEL_COLOR: Record<LogLevel, string> = {
|
||||
info: ANSI.cyan,
|
||||
warn: ANSI.yellow,
|
||||
error: ANSI.red,
|
||||
event: ANSI.magenta,
|
||||
};
|
||||
|
||||
function useColors() {
|
||||
return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined;
|
||||
}
|
||||
|
||||
function colorize(value: string, color: string, enabled: boolean) {
|
||||
return enabled ? `${color}${value}${ANSI.reset}` : value;
|
||||
}
|
||||
|
||||
function timeStamp() {
|
||||
return new Date().toISOString().slice(11, 23);
|
||||
}
|
||||
|
||||
function formatValue(value: unknown) {
|
||||
if (typeof value === "string") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (
|
||||
typeof value === "number" ||
|
||||
typeof value === "boolean" ||
|
||||
value === null ||
|
||||
value === undefined
|
||||
) {
|
||||
return String(value);
|
||||
}
|
||||
return util.inspect(value, {
|
||||
depth: 4,
|
||||
breakLength: Infinity,
|
||||
compact: true,
|
||||
maxArrayLength: 25,
|
||||
maxStringLength: 320,
|
||||
});
|
||||
}
|
||||
|
||||
function formatContext(context: LogContext | undefined) {
|
||||
if (!context) return "";
|
||||
const entries = Object.entries(context).filter(([, value]) => value !== undefined);
|
||||
if (entries.length === 0) return "";
|
||||
return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
|
||||
}
|
||||
|
||||
function write(level: LogLevel, scope: string, message: string, context?: LogContext) {
|
||||
const colorEnabled = useColors();
|
||||
const ts = colorize(timeStamp(), ANSI.dim, colorEnabled);
|
||||
const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled);
|
||||
const contextText = formatContext(context);
|
||||
const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`;
|
||||
|
||||
if (level === "warn") {
|
||||
console.warn(line);
|
||||
return;
|
||||
}
|
||||
if (level === "error") {
|
||||
console.error(line);
|
||||
return;
|
||||
}
|
||||
console.log(line);
|
||||
}
|
||||
|
||||
export function createLogger(scope: string) {
|
||||
return {
|
||||
info(message: string, context?: LogContext) {
|
||||
write("info", scope, message, context);
|
||||
},
|
||||
warn(message: string, context?: LogContext) {
|
||||
write("warn", scope, message, context);
|
||||
},
|
||||
error(message: string, context?: LogContext) {
|
||||
write("error", scope, message, context);
|
||||
},
|
||||
event(message: string, context?: LogContext) {
|
||||
write("event", scope, message, context);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, afterEach } from "vitest";
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
|
||||
@@ -77,6 +77,7 @@ describe("WebSocket Server", () => {
|
||||
connections.length = 0;
|
||||
server?.stop();
|
||||
server = null;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("sends welcome message on connect", async () => {
|
||||
@@ -99,6 +100,37 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("logs outbound websocket push events in dev mode", async () => {
|
||||
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {
|
||||
// Keep test output clean while verifying websocket logs.
|
||||
});
|
||||
|
||||
server = createServer({
|
||||
port: 0,
|
||||
cwd: "/test/project",
|
||||
devUrl: "http://localhost:5173",
|
||||
});
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
expect(port).toBeGreaterThan(0);
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
expect(
|
||||
logSpy.mock.calls.some(([message]) => {
|
||||
if (typeof message !== "string") return false;
|
||||
return (
|
||||
message.includes("[ws]") &&
|
||||
message.includes("outgoing push") &&
|
||||
message.includes(`channel="${WS_CHANNELS.serverWelcome}"`)
|
||||
);
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("responds to server.getConfig", async () => {
|
||||
server = createServer({ port: 0, cwd: "/my/workspace" });
|
||||
await server.start();
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from "@acme/contracts";
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
@@ -36,12 +37,35 @@ export interface ServerOptions {
|
||||
cwd: string;
|
||||
staticDir?: string | undefined;
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
}
|
||||
|
||||
function parseBooleanEnv(value: string | undefined): boolean | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (["1", "true", "yes", "on"].includes(normalized)) return true;
|
||||
if (["0", "false", "no", "off"].includes(normalized)) return false;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function createServer(options: ServerOptions) {
|
||||
const { port, cwd, staticDir, devUrl } = options;
|
||||
const { port, cwd, staticDir, devUrl, logWebSocketEvents: explicitLogWsEvents } = options;
|
||||
const providerManager = new ProviderManager();
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
const logWebSocketEvents =
|
||||
explicitLogWsEvents ??
|
||||
parseBooleanEnv(process.env.CODETHING_LOG_WS_EVENTS) ??
|
||||
Boolean(devUrl);
|
||||
|
||||
function logOutgoingPush(push: WsPush, recipients: number) {
|
||||
if (!logWebSocketEvents) return;
|
||||
logger.event("outgoing push", {
|
||||
channel: push.channel,
|
||||
recipients,
|
||||
payload: push.data,
|
||||
});
|
||||
}
|
||||
|
||||
// Forward provider events to all connected WebSocket clients
|
||||
providerManager.on("event", (event) => {
|
||||
@@ -51,11 +75,14 @@ export function createServer(options: ServerOptions) {
|
||||
data: event,
|
||||
};
|
||||
const message = JSON.stringify(push);
|
||||
let recipients = 0;
|
||||
for (const client of clients) {
|
||||
if (client.readyState === client.OPEN) {
|
||||
client.send(message);
|
||||
recipients += 1;
|
||||
}
|
||||
}
|
||||
logOutgoingPush(push, recipients);
|
||||
});
|
||||
|
||||
// HTTP server — serves static files or redirects to Vite dev server
|
||||
@@ -129,6 +156,7 @@ export function createServer(options: ServerOptions) {
|
||||
channel: WS_CHANNELS.serverWelcome,
|
||||
data: { cwd, projectName },
|
||||
};
|
||||
logOutgoingPush(welcome, 1);
|
||||
ws.send(JSON.stringify(welcome));
|
||||
|
||||
ws.on("message", (raw) => {
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
"packages/*"
|
||||
],
|
||||
"scripts": {
|
||||
"dev": "bun run build:contracts && VITE_WS_URL=ws://localhost:3773 turbo run dev --filter=@acme/renderer --filter=t3 --parallel",
|
||||
"dev": "CODETHING_LOG_WS_EVENTS=1 VITE_WS_URL=ws://localhost:3773 turbo run dev --ui=tui --filter=@acme/contracts --filter=@acme/renderer --filter=t3 --parallel",
|
||||
"dev:server": "bun run build:contracts && bun run --cwd apps/server dev",
|
||||
"dev:web": "VITE_WS_URL=ws://localhost:3773 bun run --cwd apps/renderer dev",
|
||||
"start": "node apps/server/dist/index.js",
|
||||
|
||||
+7
-1
@@ -1,12 +1,18 @@
|
||||
{
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"globalEnv": ["PORT", "VITE_WS_URL", "VITE_DEV_SERVER_URL"],
|
||||
"globalEnv": [
|
||||
"PORT",
|
||||
"VITE_WS_URL",
|
||||
"VITE_DEV_SERVER_URL",
|
||||
"CODETHING_LOG_WS_EVENTS"
|
||||
],
|
||||
"tasks": {
|
||||
"build": {
|
||||
"dependsOn": ["^build"],
|
||||
"outputs": ["dist/**"]
|
||||
},
|
||||
"dev": {
|
||||
"dependsOn": ["@acme/contracts#build"],
|
||||
"cache": false,
|
||||
"persistent": true
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user