@townco/core 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@townco/core",
3
+ "type": "module",
4
+ "version": "0.0.2",
5
+ "description": "core",
6
+ "license": "UNLICENSED",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "repository": "github:townco/town",
10
+ "exports": {
11
+ ".": {
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "devDependencies": {
17
+ "typescript": "^5.9.3",
18
+ "@townco/tsconfig": "0.1.21"
19
+ },
20
+ "scripts": {
21
+ "build": "tsc",
22
+ "check": "tsc --noEmit"
23
+ }
24
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./logger.js";
package/src/logger.ts ADDED
@@ -0,0 +1,253 @@
1
+ /**
2
+ * Browser-compatible logger
3
+ * Outputs structured JSON logs to console with color-coding
4
+ * Also captures logs to a global store for in-app viewing
5
+ * In Node.js environment with logsDir option, also writes to .logs/ directory
6
+ */
7
+
8
+ export type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
9
+
10
+ // Check if running in Node.js
11
+ const isNode = typeof process !== "undefined" && process.versions?.node;
12
+
13
+ // Global logs directory configuration (set once at app startup for TUI)
14
+ let globalLogsDir: string | undefined;
15
+
16
+ export interface LogEntry {
17
+ id: string;
18
+ timestamp: string;
19
+ level: LogLevel;
20
+ service: string;
21
+ message: string;
22
+ metadata?: Record<string, unknown>;
23
+ }
24
+
25
+ // Global log store
26
+ const globalLogStore: LogEntry[] = [];
27
+ let logIdCounter = 0;
28
+
29
+ /**
30
+ * Get all captured logs
31
+ */
32
+ export function getCapturedLogs(): LogEntry[] {
33
+ return [...globalLogStore];
34
+ }
35
+
36
+ /**
37
+ * Clear all captured logs
38
+ */
39
+ export function clearCapturedLogs(): void {
40
+ globalLogStore.length = 0;
41
+ }
42
+
43
+ /**
44
+ * Subscribe to log updates
45
+ */
46
+ type LogSubscriber = (entry: LogEntry) => void;
47
+ const logSubscribers: Set<LogSubscriber> = new Set();
48
+
49
+ export function subscribeToLogs(callback: LogSubscriber): () => void {
50
+ logSubscribers.add(callback);
51
+ return () => logSubscribers.delete(callback);
52
+ }
53
+
54
+ function notifyLogSubscribers(entry: LogEntry): void {
55
+ for (const callback of logSubscribers) {
56
+ callback(entry);
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Configure global logs directory for file writing
62
+ * Must be called before creating any loggers (typically at TUI startup)
63
+ */
64
+ export function configureLogsDir(logsDir: string): void {
65
+ globalLogsDir = logsDir;
66
+ }
67
+
68
+ const LOG_LEVELS: Record<LogLevel, number> = {
69
+ trace: 0,
70
+ debug: 1,
71
+ info: 2,
72
+ warn: 3,
73
+ error: 4,
74
+ fatal: 5,
75
+ };
76
+
77
+ const _LOG_COLORS: Record<LogLevel, string> = {
78
+ trace: "#6B7280", // gray
79
+ debug: "#3B82F6", // blue
80
+ info: "#10B981", // green
81
+ warn: "#F59E0B", // orange
82
+ error: "#EF4444", // red
83
+ fatal: "#DC2626", // dark red
84
+ };
85
+
86
+ const _LOG_STYLES: Record<LogLevel, string> = {
87
+ trace: "color: #6B7280",
88
+ debug: "color: #3B82F6; font-weight: bold",
89
+ info: "color: #10B981; font-weight: bold",
90
+ warn: "color: #F59E0B; font-weight: bold",
91
+ error: "color: #EF4444; font-weight: bold",
92
+ fatal: "color: #DC2626; font-weight: bold; background: #FEE2E2",
93
+ };
94
+
95
+ export class Logger {
96
+ private service: string;
97
+ private minLevel: LogLevel;
98
+ private logFilePath?: string;
99
+ private logsDir?: string;
100
+ private writeQueue: string[] = [];
101
+ private isWriting = false;
102
+
103
+ constructor(service: string, minLevel: LogLevel = "debug") {
104
+ this.service = service;
105
+ this.minLevel = minLevel;
106
+
107
+ // In production, suppress trace and debug logs
108
+ if (
109
+ typeof process !== "undefined" &&
110
+ process.env?.NODE_ENV === "production"
111
+ ) {
112
+ this.minLevel = "info";
113
+ }
114
+
115
+ // Note: File logging setup is done lazily in log() method
116
+ // This allows loggers created before configureLogsDir() to still write to files
117
+ }
118
+
119
+ private setupFileLogging(): void {
120
+ if (!isNode || !globalLogsDir) return;
121
+
122
+ try {
123
+ // Dynamic import for Node.js modules
124
+ const path = require("node:path");
125
+ const fs = require("node:fs");
126
+
127
+ this.logsDir = globalLogsDir;
128
+ this.logFilePath = path.join(this.logsDir, `${this.service}.log`);
129
+
130
+ // Create logs directory if it doesn't exist
131
+ if (!fs.existsSync(this.logsDir)) {
132
+ fs.mkdirSync(this.logsDir, { recursive: true });
133
+ }
134
+ } catch (_error) {
135
+ // Silently fail if we can't set up file logging
136
+ }
137
+ }
138
+
139
+ private async writeToFile(content: string): Promise<void> {
140
+ if (!this.logFilePath || !isNode) return;
141
+
142
+ this.writeQueue.push(content);
143
+
144
+ if (this.isWriting) {
145
+ return;
146
+ }
147
+
148
+ this.isWriting = true;
149
+
150
+ while (this.writeQueue.length > 0) {
151
+ const batch = this.writeQueue.splice(0, this.writeQueue.length);
152
+ const data = `${batch.join("\n")}\n`;
153
+
154
+ try {
155
+ // Dynamic import for Node.js modules
156
+ const fs = require("node:fs");
157
+ await fs.promises.appendFile(this.logFilePath, data, "utf-8");
158
+ } catch (_error) {
159
+ // Silently fail
160
+ }
161
+ }
162
+
163
+ this.isWriting = false;
164
+ }
165
+
166
+ private shouldLog(level: LogLevel): boolean {
167
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.minLevel];
168
+ }
169
+
170
+ private log(
171
+ level: LogLevel,
172
+ message: string,
173
+ metadata?: Record<string, unknown>,
174
+ ): void {
175
+ if (!this.shouldLog(level)) {
176
+ return;
177
+ }
178
+
179
+ const entry: LogEntry = {
180
+ id: `log_${++logIdCounter}`,
181
+ timestamp: new Date().toISOString(),
182
+ level,
183
+ service: this.service,
184
+ message,
185
+ ...(metadata && { metadata }),
186
+ };
187
+
188
+ // Store in global log store
189
+ globalLogStore.push(entry);
190
+
191
+ // Notify subscribers
192
+ notifyLogSubscribers(entry);
193
+
194
+ // Write to file in Node.js (for logs tab to read)
195
+ // Lazily set up file logging if globalLogsDir was configured after this logger was created
196
+ if (isNode && !this.logFilePath && globalLogsDir) {
197
+ this.setupFileLogging();
198
+ }
199
+
200
+ if (isNode && this.logFilePath) {
201
+ // Write as JSON without the id field (to match expected format)
202
+ const fileEntry = {
203
+ timestamp: entry.timestamp,
204
+ level: entry.level,
205
+ service: entry.service,
206
+ message: entry.message,
207
+ ...(entry.metadata && { metadata: entry.metadata }),
208
+ };
209
+ this.writeToFile(JSON.stringify(fileEntry)).catch(() => {
210
+ // Silently fail
211
+ });
212
+ }
213
+
214
+ // No console output - logs are only captured and displayed in UI
215
+ // This prevents logs from polluting stdout/stderr in TUI mode
216
+ }
217
+
218
+ trace(message: string, metadata?: Record<string, unknown>): void {
219
+ this.log("trace", message, metadata);
220
+ }
221
+
222
+ debug(message: string, metadata?: Record<string, unknown>): void {
223
+ this.log("debug", message, metadata);
224
+ }
225
+
226
+ info(message: string, metadata?: Record<string, unknown>): void {
227
+ this.log("info", message, metadata);
228
+ }
229
+
230
+ warn(message: string, metadata?: Record<string, unknown>): void {
231
+ this.log("warn", message, metadata);
232
+ }
233
+
234
+ error(message: string, metadata?: Record<string, unknown>): void {
235
+ this.log("error", message, metadata);
236
+ }
237
+
238
+ fatal(message: string, metadata?: Record<string, unknown>): void {
239
+ this.log("fatal", message, metadata);
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Create a logger instance for a service
245
+ * @param service - Service name (e.g., "gui", "http-agent", "tui")
246
+ * @param minLevel - Minimum log level to display (default: "debug")
247
+ */
248
+ export function createLogger(
249
+ service: string,
250
+ minLevel: LogLevel = "debug",
251
+ ): Logger {
252
+ return new Logger(service, minLevel);
253
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "@townco/tsconfig",
3
+ "compilerOptions": { "outDir": "./dist", "rootDir": "./src" },
4
+ "include": ["src/**/*"],
5
+ "exclude": ["node_modules", "dist", ".sst"]
6
+ }