Skip to content

Commit 8cc7135

Browse files
committed
turborepo and better logging
1 parent f3d92c9 commit 8cc7135

7 files changed

Lines changed: 188 additions & 15 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ npx t3
5454

5555
## Scripts
5656

57-
- `bun run dev` — Starts both the WebSocket server and Vite dev server in parallel with hot reload.
57+
- `bun run dev` — Starts contracts, server, and web dev tasks via Turborepo's parallel task runner.
5858
- `bun run dev:server` — Starts just the WebSocket server (uses tsx for TS execution).
5959
- `bun run dev:web` — Starts just the Vite dev server for the renderer.
6060
- `bun run start` — Runs the production server (serves built renderer as static files).

‎apps/server/src/index.ts‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@ import path from "node:path";
44
import { fileURLToPath } from "node:url";
55

66
import { fixPath } from "./fixPath";
7+
import { createLogger } from "./logger";
78
import { createServer } from "./wsServer";
89

910
fixPath();
1011

1112
const DEFAULT_PORT = 3773;
1213
const cwd = process.cwd();
14+
const logger = createLogger("server");
1315

1416
async function findAvailablePort(preferred: number): Promise<number> {
1517
return new Promise((resolve, reject) => {
@@ -65,33 +67,35 @@ async function main() {
6567
const staticDir = devUrl ? undefined : resolveStaticDir();
6668

6769
if (!devUrl && !staticDir) {
68-
console.warn(
69-
"⚠ No built renderer found and no VITE_DEV_SERVER_URL set. The web UI will not be available.",
70-
);
71-
console.warn(
72-
" Run `bun run --cwd apps/renderer build` or set VITE_DEV_SERVER_URL for dev mode.",
70+
logger.warn(
71+
"renderer bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
72+
{
73+
hint:
74+
"Run `bun run --cwd apps/renderer build` or set VITE_DEV_SERVER_URL for dev mode.",
75+
},
7376
);
7477
}
7578

7679
const server = createServer({ port, cwd, staticDir, devUrl });
7780
await server.start();
7881

7982
const url = `http://localhost:${port}`;
80-
console.log(`\n ✦ CodeThing running at ${url}`);
81-
console.log(` ✦ Project: ${cwd}\n`);
83+
logger.info("CodeThing running", { url, cwd });
8284

8385
// Open browser (dynamic import because `open` is ESM-only)
8486
try {
8587
const open = await import("open");
8688
const target = devUrl ?? url;
8789
await open.default(target);
8890
} catch {
89-
console.log(` Open ${devUrl ?? url} in your browser to get started.\n`);
91+
logger.info("browser auto-open unavailable", {
92+
hint: `Open ${devUrl ?? url} in your browser.`,
93+
});
9094
}
9195

9296
// Graceful shutdown
9397
const shutdown = () => {
94-
console.log("\n Shutting down...\n");
98+
logger.info("shutting down");
9599
server.stop();
96100
process.exit(0);
97101
};
@@ -101,6 +105,6 @@ async function main() {
101105
}
102106

103107
main().catch((err) => {
104-
console.error("Failed to start CodeThing:", err);
108+
logger.error("failed to start CodeThing", { error: err });
105109
process.exit(1);
106110
});

‎apps/server/src/logger.ts‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import util from "node:util";
2+
3+
type LogLevel = "info" | "warn" | "error" | "event";
4+
5+
type LogContext = Record<string, unknown>;
6+
7+
const ANSI = {
8+
reset: "\u001b[0m",
9+
dim: "\u001b[2m",
10+
cyan: "\u001b[36m",
11+
yellow: "\u001b[33m",
12+
red: "\u001b[31m",
13+
magenta: "\u001b[35m",
14+
} as const;
15+
16+
const LEVEL_LABEL: Record<LogLevel, string> = {
17+
info: "INFO",
18+
warn: "WARN",
19+
error: "ERROR",
20+
event: "EVENT",
21+
};
22+
23+
const LEVEL_COLOR: Record<LogLevel, string> = {
24+
info: ANSI.cyan,
25+
warn: ANSI.yellow,
26+
error: ANSI.red,
27+
event: ANSI.magenta,
28+
};
29+
30+
function useColors() {
31+
return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined;
32+
}
33+
34+
function colorize(value: string, color: string, enabled: boolean) {
35+
return enabled ? `${color}${value}${ANSI.reset}` : value;
36+
}
37+
38+
function timeStamp() {
39+
return new Date().toISOString().slice(11, 23);
40+
}
41+
42+
function formatValue(value: unknown) {
43+
if (typeof value === "string") {
44+
return JSON.stringify(value);
45+
}
46+
if (
47+
typeof value === "number" ||
48+
typeof value === "boolean" ||
49+
value === null ||
50+
value === undefined
51+
) {
52+
return String(value);
53+
}
54+
return util.inspect(value, {
55+
depth: 4,
56+
breakLength: Infinity,
57+
compact: true,
58+
maxArrayLength: 25,
59+
maxStringLength: 320,
60+
});
61+
}
62+
63+
function formatContext(context: LogContext | undefined) {
64+
if (!context) return "";
65+
const entries = Object.entries(context).filter(([, value]) => value !== undefined);
66+
if (entries.length === 0) return "";
67+
return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
68+
}
69+
70+
function write(level: LogLevel, scope: string, message: string, context?: LogContext) {
71+
const colorEnabled = useColors();
72+
const ts = colorize(timeStamp(), ANSI.dim, colorEnabled);
73+
const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled);
74+
const contextText = formatContext(context);
75+
const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`;
76+
77+
if (level === "warn") {
78+
console.warn(line);
79+
return;
80+
}
81+
if (level === "error") {
82+
console.error(line);
83+
return;
84+
}
85+
console.log(line);
86+
}
87+
88+
export function createLogger(scope: string) {
89+
return {
90+
info(message: string, context?: LogContext) {
91+
write("info", scope, message, context);
92+
},
93+
warn(message: string, context?: LogContext) {
94+
write("warn", scope, message, context);
95+
},
96+
error(message: string, context?: LogContext) {
97+
write("error", scope, message, context);
98+
},
99+
event(message: string, context?: LogContext) {
100+
write("event", scope, message, context);
101+
},
102+
};
103+
}

‎apps/server/src/wsServer.test.ts‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, expect, it, afterEach } from "vitest";
1+
import { describe, expect, it, afterEach, vi } from "vitest";
22
import { createServer } from "./wsServer";
33
import WebSocket from "ws";
44

@@ -77,6 +77,7 @@ describe("WebSocket Server", () => {
7777
connections.length = 0;
7878
server?.stop();
7979
server = null;
80+
vi.restoreAllMocks();
8081
});
8182

8283
it("sends welcome message on connect", async () => {
@@ -99,6 +100,37 @@ describe("WebSocket Server", () => {
99100
});
100101
});
101102

103+
it("logs outbound websocket push events in dev mode", async () => {
104+
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {
105+
// Keep test output clean while verifying websocket logs.
106+
});
107+
108+
server = createServer({
109+
port: 0,
110+
cwd: "/test/project",
111+
devUrl: "http://localhost:5173",
112+
});
113+
await server.start();
114+
const addr = server.httpServer.address();
115+
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
116+
expect(port).toBeGreaterThan(0);
117+
118+
const ws = await connectWs(port);
119+
connections.push(ws);
120+
await waitForMessage(ws);
121+
122+
expect(
123+
logSpy.mock.calls.some(([message]) => {
124+
if (typeof message !== "string") return false;
125+
return (
126+
message.includes("[ws]") &&
127+
message.includes("outgoing push") &&
128+
message.includes(`channel="${WS_CHANNELS.serverWelcome}"`)
129+
);
130+
}),
131+
).toBe(true);
132+
});
133+
102134
it("responds to server.getConfig", async () => {
103135
server = createServer({ port: 0, cwd: "/my/workspace" });
104136
await server.start();

‎apps/server/src/wsServer.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
} from "@acme/contracts";
1515
import { WebSocketServer, type WebSocket } from "ws";
1616

17+
import { createLogger } from "./logger";
1718
import { ProviderManager } from "./providerManager";
1819

1920
const MIME_TYPES: Record<string, string> = {
@@ -36,12 +37,35 @@ export interface ServerOptions {
3637
cwd: string;
3738
staticDir?: string | undefined;
3839
devUrl?: string | undefined;
40+
logWebSocketEvents?: boolean | undefined;
41+
}
42+
43+
function parseBooleanEnv(value: string | undefined): boolean | undefined {
44+
if (value === undefined) return undefined;
45+
const normalized = value.trim().toLowerCase();
46+
if (["1", "true", "yes", "on"].includes(normalized)) return true;
47+
if (["0", "false", "no", "off"].includes(normalized)) return false;
48+
return undefined;
3949
}
4050

4151
export function createServer(options: ServerOptions) {
42-
const { port, cwd, staticDir, devUrl } = options;
52+
const { port, cwd, staticDir, devUrl, logWebSocketEvents: explicitLogWsEvents } = options;
4353
const providerManager = new ProviderManager();
4454
const clients = new Set<WebSocket>();
55+
const logger = createLogger("ws");
56+
const logWebSocketEvents =
57+
explicitLogWsEvents ??
58+
parseBooleanEnv(process.env.CODETHING_LOG_WS_EVENTS) ??
59+
Boolean(devUrl);
60+
61+
function logOutgoingPush(push: WsPush, recipients: number) {
62+
if (!logWebSocketEvents) return;
63+
logger.event("outgoing push", {
64+
channel: push.channel,
65+
recipients,
66+
payload: push.data,
67+
});
68+
}
4569

4670
// Forward provider events to all connected WebSocket clients
4771
providerManager.on("event", (event) => {
@@ -51,11 +75,14 @@ export function createServer(options: ServerOptions) {
5175
data: event,
5276
};
5377
const message = JSON.stringify(push);
78+
let recipients = 0;
5479
for (const client of clients) {
5580
if (client.readyState === client.OPEN) {
5681
client.send(message);
82+
recipients += 1;
5783
}
5884
}
85+
logOutgoingPush(push, recipients);
5986
});
6087

6188
// HTTP server — serves static files or redirects to Vite dev server
@@ -129,6 +156,7 @@ export function createServer(options: ServerOptions) {
129156
channel: WS_CHANNELS.serverWelcome,
130157
data: { cwd, projectName },
131158
};
159+
logOutgoingPush(welcome, 1);
132160
ws.send(JSON.stringify(welcome));
133161

134162
ws.on("message", (raw) => {

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
"packages/*"
77
],
88
"scripts": {
9-
"dev": "bun run build:contracts && VITE_WS_URL=ws://localhost:3773 turbo run dev --filter=@acme/renderer --filter=t3 --parallel",
9+
"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",
1010
"dev:server": "bun run build:contracts && bun run --cwd apps/server dev",
1111
"dev:web": "VITE_WS_URL=ws://localhost:3773 bun run --cwd apps/renderer dev",
1212
"start": "node apps/server/dist/index.js",

‎turbo.json‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
{
22
"$schema": "https://turbo.build/schema.json",
3-
"globalEnv": ["PORT", "VITE_WS_URL", "VITE_DEV_SERVER_URL"],
3+
"globalEnv": [
4+
"PORT",
5+
"VITE_WS_URL",
6+
"VITE_DEV_SERVER_URL",
7+
"CODETHING_LOG_WS_EVENTS"
8+
],
49
"tasks": {
510
"build": {
611
"dependsOn": ["^build"],
712
"outputs": ["dist/**"]
813
},
914
"dev": {
15+
"dependsOn": ["@acme/contracts#build"],
1016
"cache": false,
1117
"persistent": true
1218
},

0 commit comments

Comments
 (0)