@compilr-dev/logger 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,108 @@
1
+ Functional Source License, Version 1.1, MIT Future License
2
+
3
+ Abbreviation: FSL-1.1-MIT
4
+
5
+ Notice
6
+
7
+ Copyright 2026 Carmelo Scozzola
8
+
9
+ Terms and Conditions
10
+
11
+ Licensor ("We")
12
+
13
+ The party offering the Software under these Terms and Conditions.
14
+
15
+ The Software
16
+
17
+ The "Software" is each version of the software that we make available under
18
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
19
+ Conditions with the Software.
20
+
21
+ License Grant
22
+
23
+ Subject to your compliance with this License Grant and the Patents,
24
+ Redistribution and Trademark clauses below, we hereby grant you the right to
25
+ use, copy, modify, create derivative works, publicly perform, publicly display
26
+ and redistribute the Software for any Permitted Purpose identified below.
27
+
28
+ Permitted Purpose
29
+
30
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
31
+ means making the Software available to others in a commercial product or
32
+ service that:
33
+
34
+ 1. substitutes for the Software;
35
+
36
+ 2. substitutes for any other product or service we offer using the Software
37
+ that exists as of the date we make the Software available; or
38
+
39
+ 3. offers the same or substantially similar functionality as the Software.
40
+
41
+ Permitted Purposes specifically include using the Software:
42
+
43
+ 1. for your internal use and access;
44
+
45
+ 2. for non-commercial education;
46
+
47
+ 3. for non-commercial research; and
48
+
49
+ 4. in connection with professional services that you provide to a licensee
50
+ using the Software in accordance with these Terms and Conditions.
51
+
52
+ Patents
53
+
54
+ To the extent your use for a Permitted Purpose would necessarily infringe our
55
+ patents, the license grant above includes a license under our patents. If you
56
+ make a claim against any party that the Software infringes or contributes to
57
+ the infringement of any patent, then your patent license to the Software ends
58
+ immediately.
59
+
60
+ Redistribution
61
+
62
+ The Terms and Conditions apply to all copies, modifications and derivatives of
63
+ the Software.
64
+
65
+ If you redistribute any copies, modifications or derivatives of the Software,
66
+ you must include a copy of or a link to these Terms and Conditions and not
67
+ remove any copyright notices provided in or with the Software.
68
+
69
+ Disclaimer
70
+
71
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
72
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
73
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
74
+
75
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
76
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
77
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
78
+
79
+ Trademarks
80
+
81
+ Except for displaying the License Details and identifying us as the origin of
82
+ the Software, you have no right under these Terms and Conditions to use our
83
+ trademarks, trade names, service marks or product names.
84
+
85
+ Grant of Future License
86
+
87
+ We hereby irrevocably grant you an additional license to use the Software under
88
+ the MIT license that is effective on the second anniversary of the date we make
89
+ the Software available. On or after that date, you may use the Software under
90
+ the MIT license, in which case the following will apply:
91
+
92
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
93
+ this software and associated documentation files (the "Software"), to deal in
94
+ the Software without restriction, including without limitation the rights to
95
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
96
+ of the Software, and to permit persons to whom the Software is furnished to do
97
+ so, subject to the following conditions:
98
+
99
+ The above copyright notice and this permission notice shall be included in all
100
+ copies or substantial portions of the Software.
101
+
102
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
103
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
104
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
105
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
106
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
107
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
108
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # @compilr-dev/logger
2
+
3
+ ```
4
+ \|/
5
+ ╭══════════╮ ___ ___ _ __ ___ _ __ (_) |_ __
6
+ ║' ▐▌ ▐▌ │ / __|/ _ \| '_ ` _ \| '_ \| | | '__|
7
+ ║ │ | (__| (_) | | | | | | |_) | | | |
8
+ ╰─═──────═─╯ \___|\___/|_| |_| |_| .__/|_|_|_|
9
+ \________\ | | .dev
10
+ |_| logger
11
+ ```
12
+
13
+ > Structured logging for the compilr-dev ecosystem
14
+
15
+ [![npm version](https://img.shields.io/npm/v/@compilr-dev/logger.svg)](https://www.npmjs.com/package/@compilr-dev/logger)
16
+ [![License: FSL-1.1-MIT](https://img.shields.io/badge/License-FSL--1.1--MIT-blue.svg)](https://fsl.software/)
17
+
18
+ > [!WARNING]
19
+ > This package is in beta. APIs may change between minor versions.
20
+
21
+ ## Overview
22
+
23
+ A single, shared logging package used across the entire compilr-dev ecosystem — CLI, Desktop, SDK, agents, and factory. Built on [pino](https://github.com/pinojs/pino), the fastest Node.js logger.
24
+
25
+ - **JSON structured output** — cloud-native, parseable by GCP/AWS/Azure log aggregators
26
+ - **Automatic redaction** — API keys, tokens, passwords, and 30+ sensitive field patterns masked at serialization time
27
+ - **File rotation** — 10MB x 5 files via pino-roll, daily rotation
28
+ - **Pretty-print for development** — colored, human-readable output via pino-pretty
29
+ - **Electron renderer support** — IPC-based logger bridge for renderer process
30
+ - **Zero-overhead level gating** — disabled levels cost ~5ns per call
31
+ - **Child loggers** — carry context (conversationId, agentId, component) through call chains
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ npm install @compilr-dev/logger
37
+ ```
38
+
39
+ ## Quick Start
40
+
41
+ ```typescript
42
+ import { createLogger } from '@compilr-dev/logger';
43
+
44
+ // Create a logger for your package
45
+ const log = createLogger({
46
+ package: 'desktop',
47
+ component: 'ipc',
48
+ filePath: '~/.compilr-dev/logs/desktop.log',
49
+ });
50
+
51
+ // Structured logging — data in object, message in string
52
+ log.info({ handler: 'files:write', durationMs: 12 }, 'Handler completed');
53
+
54
+ // Error logging — pino serializes Error objects automatically
55
+ try {
56
+ await riskyOperation();
57
+ } catch (err) {
58
+ log.error({ err }, 'Operation failed');
59
+ }
60
+
61
+ // Child loggers carry context
62
+ const agentLog = log.child({ agentId: 'researcher', conversationId: 'conv-123' });
63
+ agentLog.debug('Starting tool execution');
64
+ ```
65
+
66
+ ## Log Levels
67
+
68
+ | Level | Value | Usage |
69
+ |-------|-------|-------|
70
+ | `trace` | 10 | Verbose diagnostics. Token counts, raw timing. |
71
+ | `debug` | 20 | Tool calls, IPC messages, state transitions. |
72
+ | `info` | 30 | Normal operations. **Default level.** |
73
+ | `warn` | 40 | Unexpected but recoverable. Retries, fallbacks. |
74
+ | `error` | 50 | Operation failed. Stack traces attached. |
75
+ | `fatal` | 60 | App cannot continue. |
76
+
77
+ Default level by environment:
78
+ - `NODE_ENV=development` → `debug`
79
+ - Production → `info`
80
+ - `LOG_LEVEL=trace` → override via environment variable
81
+
82
+ ## API
83
+
84
+ ### `createLogger(options?)`
85
+
86
+ Create a configured logger instance.
87
+
88
+ ```typescript
89
+ interface LoggerOptions {
90
+ package?: string; // Added to every log entry (e.g., "desktop", "cli")
91
+ component?: string; // Added to every log entry (e.g., "ipc", "agent-manager")
92
+ level?: LogLevel; // Minimum level (default: from LOG_LEVEL env or 'info')
93
+ filePath?: string; // Write to file with rotation
94
+ pretty?: boolean; // Pretty-print to stdout (default: true in development)
95
+ redact?: string[]; // Additional redaction paths (merged with defaults)
96
+ silent?: boolean; // Disable stdout/stderr output
97
+ }
98
+ ```
99
+
100
+ ### `createSilentLogger()`
101
+
102
+ Create a no-op logger. Used as fallback in libraries when no logger is provided.
103
+
104
+ ### `createRendererLogger(options?)`
105
+
106
+ IPC-based logger for Electron renderer process. Import from `@compilr-dev/logger/renderer`.
107
+
108
+ ```typescript
109
+ import { createRendererLogger } from '@compilr-dev/logger/renderer';
110
+ const log = createRendererLogger({ component: 'chat' });
111
+ log.info('Message sent');
112
+ ```
113
+
114
+ ### `scrubSecrets(text)`
115
+
116
+ Scrub accidentally-logged secrets from text. Used when exporting logs for support.
117
+
118
+ ## Redaction
119
+
120
+ These fields are automatically replaced with `"[REDACTED]"` in all output:
121
+
122
+ - `apiKey`, `token`, `password`, `secret`, `authorization`, `credentials`
123
+ - Nested: `*.apiKey`, `*.token`, `*.password`, etc.
124
+ - Headers: `headers.authorization`, `headers.cookie`
125
+ - Environment: `env.ANTHROPIC_API_KEY`, `env.OPENAI_API_KEY`, `env.GITHUB_TOKEN`
126
+
127
+ ## For Libraries (Dependency Injection)
128
+
129
+ Libraries (SDK, agents) should never import the default logger singleton. Accept a logger via config:
130
+
131
+ ```typescript
132
+ import type { Logger } from '@compilr-dev/logger';
133
+
134
+ interface MyConfig {
135
+ logger?: Logger;
136
+ }
137
+
138
+ function doWork(config: MyConfig) {
139
+ const log = config.logger ?? createSilentLogger();
140
+ log.info('Working...');
141
+ }
142
+ ```
143
+
144
+ ## License
145
+
146
+ [FSL-1.1-MIT](https://fsl.software/) — Functional Source License, converts to MIT after 2 years per version.
147
+
148
+ Copyright (c) Carmelo Scozzola
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Config — Environment-based logger configuration.
3
+ */
4
+ export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'silent';
5
+ export interface LoggerOptions {
6
+ /** Package name added to every log entry (e.g., "desktop", "cli", "sdk") */
7
+ package?: string;
8
+ /** Component name added to every log entry (e.g., "ipc", "agent-manager") */
9
+ component?: string;
10
+ /** Minimum log level (default: from LOG_LEVEL env or 'info') */
11
+ level?: LogLevel;
12
+ /** Write logs to file (absolute path). Enables rotation. */
13
+ filePath?: string;
14
+ /** Pretty-print to stdout (default: true when NODE_ENV=development and no filePath) */
15
+ pretty?: boolean;
16
+ /** Additional redaction paths (merged with defaults) */
17
+ redact?: string[];
18
+ /** Disable stdout/stderr output (useful when only writing to file) */
19
+ silent?: boolean;
20
+ }
21
+ /**
22
+ * Resolve the effective log level from options and environment.
23
+ */
24
+ export declare function resolveLevel(options?: LoggerOptions): LogLevel;
25
+ /**
26
+ * Determine if pretty-printing should be enabled.
27
+ */
28
+ export declare function resolvePretty(options?: LoggerOptions): boolean;
29
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,QAAQ,CAAC;AAE1F,MAAM,WAAW,aAAa;IAC5B,4EAA4E;IAC5E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,6EAA6E;IAC7E,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gEAAgE;IAChE,KAAK,CAAC,EAAE,QAAQ,CAAC;IACjB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uFAAuF;IACvF,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,wDAAwD;IACxD,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,sEAAsE;IACtE,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAMD;;GAEG;AACH,wBAAgB,YAAY,CAAC,OAAO,CAAC,EAAE,aAAa,GAAG,QAAQ,CAa9D;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,OAAO,CAAC,EAAE,aAAa,GAAG,OAAO,CAI9D"}
package/dist/config.js ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Config — Environment-based logger configuration.
3
+ */
4
+ const VALID_LEVELS = new Set([
5
+ 'trace', 'debug', 'info', 'warn', 'error', 'fatal', 'silent',
6
+ ]);
7
+ /**
8
+ * Resolve the effective log level from options and environment.
9
+ */
10
+ export function resolveLevel(options) {
11
+ // Explicit option takes precedence
12
+ if (options?.level)
13
+ return options.level;
14
+ // Environment variable
15
+ const envLevel = process.env['LOG_LEVEL']?.toLowerCase();
16
+ if (envLevel && VALID_LEVELS.has(envLevel))
17
+ return envLevel;
18
+ // Development default
19
+ if (process.env['NODE_ENV'] === 'development')
20
+ return 'debug';
21
+ // Production default
22
+ return 'info';
23
+ }
24
+ /**
25
+ * Determine if pretty-printing should be enabled.
26
+ */
27
+ export function resolvePretty(options) {
28
+ if (options?.pretty !== undefined)
29
+ return options.pretty;
30
+ // Pretty in development when outputting to terminal (no file-only mode)
31
+ return process.env['NODE_ENV'] === 'development' && !options?.silent;
32
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @compilr-dev/logger — Structured logging for the compilr-dev ecosystem.
3
+ *
4
+ * Built on pino. JSON output by default, automatic redaction of sensitive
5
+ * fields, file rotation, pretty-printing for development.
6
+ *
7
+ * Usage:
8
+ * import { createLogger } from '@compilr-dev/logger';
9
+ * const log = createLogger({ package: 'desktop', component: 'ipc' });
10
+ * log.info({ handler: 'files:write', durationMs: 12 }, 'Handler completed');
11
+ *
12
+ * For Electron renderer process, use the separate entry point:
13
+ * import { createRendererLogger } from '@compilr-dev/logger/renderer';
14
+ */
15
+ import type { Logger as PinoLogger } from 'pino';
16
+ import { type LoggerOptions } from './config.js';
17
+ /** Logger instance type (pino logger) */
18
+ export type Logger = PinoLogger;
19
+ export type { LoggerOptions, LogLevel } from './config.js';
20
+ export { REDACT_PATHS, SCRUB_PATTERNS, scrubSecrets } from './redaction.js';
21
+ /**
22
+ * Create a configured logger instance.
23
+ *
24
+ * @param options - Logger configuration
25
+ * @returns A pino logger with redaction, transports, and base fields
26
+ */
27
+ export declare function createLogger(options?: LoggerOptions): Logger;
28
+ /**
29
+ * Create a no-op logger that discards all output.
30
+ * Used as fallback in libraries when no logger is provided.
31
+ */
32
+ export declare function createSilentLogger(): Logger;
33
+ /**
34
+ * Default shared logger instance, configured from environment variables.
35
+ *
36
+ * For applications, prefer creating your own logger with `createLogger()`
37
+ * to set package/component context. This default is a convenience for
38
+ * quick use and testing.
39
+ */
40
+ export declare const logger: Logger;
41
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,KAAK,EAAE,MAAM,IAAI,UAAU,EAA0B,MAAM,MAAM,CAAC;AAEzE,OAAO,EAA+B,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAK9E,yCAAyC;AACzC,MAAM,MAAM,MAAM,GAAG,UAAU,CAAC;AAGhC,YAAY,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAI5E;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,OAAO,CAAC,EAAE,aAAa,GAAG,MAAM,CAoD5D;AAID;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAE3C;AAID;;;;;;GAMG;AACH,eAAO,MAAM,MAAM,EAAE,MAAuB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @compilr-dev/logger — Structured logging for the compilr-dev ecosystem.
3
+ *
4
+ * Built on pino. JSON output by default, automatic redaction of sensitive
5
+ * fields, file rotation, pretty-printing for development.
6
+ *
7
+ * Usage:
8
+ * import { createLogger } from '@compilr-dev/logger';
9
+ * const log = createLogger({ package: 'desktop', component: 'ipc' });
10
+ * log.info({ handler: 'files:write', durationMs: 12 }, 'Handler completed');
11
+ *
12
+ * For Electron renderer process, use the separate entry point:
13
+ * import { createRendererLogger } from '@compilr-dev/logger/renderer';
14
+ */
15
+ import pino from 'pino';
16
+ import { REDACT_PATHS } from './redaction.js';
17
+ import { resolveLevel, resolvePretty } from './config.js';
18
+ import { prettyTarget, fileTarget } from './transports.js';
19
+ export { REDACT_PATHS, SCRUB_PATTERNS, scrubSecrets } from './redaction.js';
20
+ // ─── Factory ────────────────────────────────────────────────────────────────
21
+ /**
22
+ * Create a configured logger instance.
23
+ *
24
+ * @param options - Logger configuration
25
+ * @returns A pino logger with redaction, transports, and base fields
26
+ */
27
+ export function createLogger(options) {
28
+ const level = resolveLevel(options);
29
+ const pretty = resolvePretty(options);
30
+ // Merge default redaction paths with any additional ones
31
+ const redactPaths = options?.redact
32
+ ? [...REDACT_PATHS, ...options.redact]
33
+ : REDACT_PATHS;
34
+ // Base fields attached to every log entry
35
+ const base = {};
36
+ if (options?.package)
37
+ base['package'] = options.package;
38
+ if (options?.component)
39
+ base['component'] = options.component;
40
+ // Build transport targets
41
+ const targets = [];
42
+ if (options?.filePath) {
43
+ targets.push(fileTarget(options.filePath));
44
+ }
45
+ if (!options?.silent) {
46
+ if (pretty) {
47
+ targets.push(prettyTarget());
48
+ }
49
+ else if (!options?.filePath) {
50
+ // JSON to stdout (production, no file configured)
51
+ targets.push({ target: 'pino/file', options: { destination: 1 } }); // fd 1 = stdout
52
+ }
53
+ }
54
+ // If we have both file and stdout, use multi-transport
55
+ // If we have only one target, use single transport
56
+ // If no targets (silent + no file), use destination /dev/null equivalent
57
+ const transport = targets.length > 0
58
+ ? { targets }
59
+ : undefined;
60
+ // When no transport is configured (silent + no file), disable output
61
+ if (targets.length === 0) {
62
+ return pino({ level: 'silent' });
63
+ }
64
+ return pino({
65
+ level,
66
+ base,
67
+ timestamp: pino.stdTimeFunctions.isoTime,
68
+ redact: {
69
+ paths: redactPaths,
70
+ censor: '[REDACTED]',
71
+ },
72
+ transport,
73
+ });
74
+ }
75
+ // ─── Silent Logger ──────────────────────────────────────────────────────────
76
+ /**
77
+ * Create a no-op logger that discards all output.
78
+ * Used as fallback in libraries when no logger is provided.
79
+ */
80
+ export function createSilentLogger() {
81
+ return pino({ level: 'silent' });
82
+ }
83
+ // ─── Default Instance ───────────────────────────────────────────────────────
84
+ /**
85
+ * Default shared logger instance, configured from environment variables.
86
+ *
87
+ * For applications, prefer creating your own logger with `createLogger()`
88
+ * to set package/component context. This default is a convenience for
89
+ * quick use and testing.
90
+ */
91
+ export const logger = createLogger();
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Redaction — Sensitive data paths that are automatically masked in log output.
3
+ *
4
+ * pino replaces these field values with "[REDACTED]" at serialization time.
5
+ * This is a safety net — callers should also avoid logging content/bodies.
6
+ */
7
+ /** Paths automatically redacted in all log output */
8
+ export declare const REDACT_PATHS: string[];
9
+ /**
10
+ * Patterns for scrubbing log files on export.
11
+ * These catch secrets that bypassed redaction (e.g., embedded in a string).
12
+ */
13
+ export declare const SCRUB_PATTERNS: RegExp[];
14
+ /**
15
+ * Scrub a string of accidentally-included secrets.
16
+ * Used when exporting logs for user support.
17
+ */
18
+ export declare function scrubSecrets(text: string): string;
19
+ //# sourceMappingURL=redaction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redaction.d.ts","sourceRoot":"","sources":["../src/redaction.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,qDAAqD;AACrD,eAAO,MAAM,YAAY,EAAE,MAAM,EAgDhC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,cAAc,EAAE,MAAM,EAiBlC,CAAC;AAEF;;;GAGG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAQjD"}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Redaction — Sensitive data paths that are automatically masked in log output.
3
+ *
4
+ * pino replaces these field values with "[REDACTED]" at serialization time.
5
+ * This is a safety net — callers should also avoid logging content/bodies.
6
+ */
7
+ /** Paths automatically redacted in all log output */
8
+ export const REDACT_PATHS = [
9
+ // Auth tokens & keys (top-level)
10
+ 'apiKey',
11
+ 'api_key',
12
+ 'token',
13
+ 'accessToken',
14
+ 'access_token',
15
+ 'refreshToken',
16
+ 'refresh_token',
17
+ 'secret',
18
+ 'password',
19
+ 'passwd',
20
+ 'authorization',
21
+ 'cookie',
22
+ 'session',
23
+ 'jwt',
24
+ 'credentials',
25
+ // Nested (one level deep — covers most structured objects)
26
+ '*.apiKey',
27
+ '*.api_key',
28
+ '*.token',
29
+ '*.accessToken',
30
+ '*.access_token',
31
+ '*.refreshToken',
32
+ '*.refresh_token',
33
+ '*.secret',
34
+ '*.password',
35
+ '*.passwd',
36
+ '*.authorization',
37
+ '*.cookie',
38
+ '*.credentials',
39
+ // HTTP headers
40
+ 'headers.authorization',
41
+ 'headers.cookie',
42
+ 'headers.set-cookie',
43
+ 'headers.x-api-key',
44
+ // Environment variables (when accidentally logged)
45
+ 'env.ANTHROPIC_API_KEY',
46
+ 'env.OPENAI_API_KEY',
47
+ 'env.GEMINI_API_KEY',
48
+ 'env.SUPABASE_SERVICE_ROLE_KEY',
49
+ 'env.GITHUB_TOKEN',
50
+ 'env.GH_TOKEN',
51
+ 'env.NPM_TOKEN',
52
+ 'env.DATABASE_URL',
53
+ ];
54
+ /**
55
+ * Patterns for scrubbing log files on export.
56
+ * These catch secrets that bypassed redaction (e.g., embedded in a string).
57
+ */
58
+ export const SCRUB_PATTERNS = [
59
+ // Anthropic API keys
60
+ /sk-ant-[a-zA-Z0-9_-]{20,}/g,
61
+ // OpenAI API keys
62
+ /sk-[a-zA-Z0-9]{20,}/g,
63
+ // GitHub tokens
64
+ /ghp_[a-zA-Z0-9]{36}/g,
65
+ /gho_[a-zA-Z0-9]{36}/g,
66
+ /ghs_[a-zA-Z0-9]{36}/g,
67
+ /ghu_[a-zA-Z0-9]{36}/g,
68
+ /github_pat_[a-zA-Z0-9_]{22,}/g,
69
+ // npm tokens
70
+ /npm_[a-zA-Z0-9]{36}/g,
71
+ // Generic bearer tokens
72
+ /Bearer [a-zA-Z0-9._-]{20,}/gi,
73
+ // compilr-dev API tokens
74
+ /tok_[a-zA-Z0-9]{32,}/g,
75
+ ];
76
+ /**
77
+ * Scrub a string of accidentally-included secrets.
78
+ * Used when exporting logs for user support.
79
+ */
80
+ export function scrubSecrets(text) {
81
+ let result = text;
82
+ for (const pattern of SCRUB_PATTERNS) {
83
+ // Reset lastIndex for global regexes
84
+ pattern.lastIndex = 0;
85
+ result = result.replace(pattern, '[SCRUBBED]');
86
+ }
87
+ return result;
88
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Renderer Logger — IPC-based logger for Electron renderer process.
3
+ *
4
+ * The renderer can't write files directly. This module creates a logger-like
5
+ * interface that sends structured log entries to the main process via IPC,
6
+ * where they're written to the same log file.
7
+ *
8
+ * Usage:
9
+ * import { createRendererLogger } from '@compilr-dev/logger/renderer';
10
+ * const log = createRendererLogger({ component: 'chat' });
11
+ * log.info('Message sent');
12
+ *
13
+ * The main process must register the IPC handler:
14
+ * ipcMain.on('log:write', (_event, entry) => mainLogger[entry.level](entry, entry.msg));
15
+ */
16
+ import type { LogLevel } from './config.js';
17
+ export interface RendererLoggerOptions {
18
+ /** Component name added to every log entry */
19
+ component?: string;
20
+ /** Package name (default: "desktop-renderer") */
21
+ package?: string;
22
+ /** Minimum log level (default: 'info') */
23
+ level?: LogLevel;
24
+ }
25
+ type LogFn = (msgOrObj: string | Record<string, unknown>, msg?: string) => void;
26
+ export interface RendererLogger {
27
+ trace: LogFn;
28
+ debug: LogFn;
29
+ info: LogFn;
30
+ warn: LogFn;
31
+ error: LogFn;
32
+ fatal: LogFn;
33
+ child: (bindings: Record<string, unknown>) => RendererLogger;
34
+ level: string;
35
+ }
36
+ /**
37
+ * Create a renderer-side logger that sends entries to the main process.
38
+ */
39
+ export declare function createRendererLogger(options?: RendererLoggerOptions): RendererLogger;
40
+ export {};
41
+ //# sourceMappingURL=renderer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"renderer.d.ts","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAI5C,MAAM,WAAW,qBAAqB;IACpC,8CAA8C;IAC9C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iDAAiD;IACjD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0CAA0C;IAC1C,KAAK,CAAC,EAAE,QAAQ,CAAC;CAClB;AAWD,KAAK,KAAK,GAAG,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;AAEhF,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,KAAK,CAAC;IACb,KAAK,EAAE,KAAK,CAAC;IACb,IAAI,EAAE,KAAK,CAAC;IACZ,IAAI,EAAE,KAAK,CAAC;IACZ,KAAK,EAAE,KAAK,CAAC;IACb,KAAK,EAAE,KAAK,CAAC;IACb,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,cAAc,CAAC;IAC7D,KAAK,EAAE,MAAM,CAAC;CACf;AA0CD;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,CAAC,EAAE,qBAAqB,GAAG,cAAc,CAiDpF"}
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Renderer Logger — IPC-based logger for Electron renderer process.
3
+ *
4
+ * The renderer can't write files directly. This module creates a logger-like
5
+ * interface that sends structured log entries to the main process via IPC,
6
+ * where they're written to the same log file.
7
+ *
8
+ * Usage:
9
+ * import { createRendererLogger } from '@compilr-dev/logger/renderer';
10
+ * const log = createRendererLogger({ component: 'chat' });
11
+ * log.info('Message sent');
12
+ *
13
+ * The main process must register the IPC handler:
14
+ * ipcMain.on('log:write', (_event, entry) => mainLogger[entry.level](entry, entry.msg));
15
+ */
16
+ // ─── Level Gating ───────────────────────────────────────────────────────────
17
+ const LEVEL_VALUES = {
18
+ trace: 10,
19
+ debug: 20,
20
+ info: 30,
21
+ warn: 40,
22
+ error: 50,
23
+ fatal: 60,
24
+ silent: Infinity,
25
+ };
26
+ // ─── IPC Send ───────────────────────────────────────────────────────────────
27
+ /**
28
+ * Send a log entry to the main process via IPC.
29
+ * Uses window.compilr.log.write if available, falls back to console.
30
+ */
31
+ function sendToMain(entry) {
32
+ // Check if the IPC bridge is available (Electron preload)
33
+ const w = globalThis;
34
+ const compilr = w['compilr'];
35
+ const logBridge = compilr?.['log'];
36
+ const writeFn = logBridge?.['write'];
37
+ if (writeFn) {
38
+ writeFn(entry);
39
+ }
40
+ else {
41
+ // Fallback: browser console (development, or IPC not yet ready)
42
+ const consoleFn = entry.level === 'error' || entry.level === 'fatal'
43
+ ? console.error // eslint-disable-line no-console
44
+ : entry.level === 'warn'
45
+ ? console.warn // eslint-disable-line no-console
46
+ : console.log; // eslint-disable-line no-console
47
+ consoleFn(`[${entry.component ?? entry.package ?? 'renderer'}] ${entry.msg}`, entry);
48
+ }
49
+ }
50
+ // ─── Factory ────────────────────────────────────────────────────────────────
51
+ /**
52
+ * Create a renderer-side logger that sends entries to the main process.
53
+ */
54
+ export function createRendererLogger(options) {
55
+ const pkg = options?.package ?? 'desktop-renderer';
56
+ const component = options?.component;
57
+ const minLevel = LEVEL_VALUES[options?.level ?? 'info'] ?? 30;
58
+ function makeLogFn(level) {
59
+ const levelValue = LEVEL_VALUES[level] ?? 30;
60
+ return (msgOrObj, msg) => {
61
+ // Level gating — skip if below threshold
62
+ if (levelValue < minLevel)
63
+ return;
64
+ const entry = {
65
+ level,
66
+ package: pkg,
67
+ time: new Date().toISOString(),
68
+ msg: '',
69
+ };
70
+ if (component)
71
+ entry['component'] = component;
72
+ if (typeof msgOrObj === 'string') {
73
+ entry.msg = msgOrObj;
74
+ }
75
+ else {
76
+ Object.assign(entry, msgOrObj);
77
+ entry.msg = msg ?? '';
78
+ }
79
+ sendToMain(entry);
80
+ };
81
+ }
82
+ const loggerInstance = {
83
+ trace: makeLogFn('trace'),
84
+ debug: makeLogFn('debug'),
85
+ info: makeLogFn('info'),
86
+ warn: makeLogFn('warn'),
87
+ error: makeLogFn('error'),
88
+ fatal: makeLogFn('fatal'),
89
+ level: options?.level ?? 'info',
90
+ child: (bindings) => {
91
+ return createRendererLogger({
92
+ ...options,
93
+ package: bindings['package'] ?? pkg,
94
+ component: bindings['component'] ?? component,
95
+ });
96
+ },
97
+ };
98
+ return loggerInstance;
99
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Transports — pino transport configurations for file, pretty, and multi-target.
3
+ */
4
+ import type { TransportTargetOptions } from 'pino';
5
+ /**
6
+ * Build a pretty-print transport target (for development).
7
+ */
8
+ export declare function prettyTarget(): TransportTargetOptions;
9
+ /**
10
+ * Build a file rotation transport target.
11
+ *
12
+ * Uses pino-roll: rotates daily or at 10MB, keeps last 5 files.
13
+ */
14
+ export declare function fileTarget(filePath: string): TransportTargetOptions;
15
+ //# sourceMappingURL=transports.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transports.d.ts","sourceRoot":"","sources":["../src/transports.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,MAAM,CAAC;AAEnD;;GAEG;AACH,wBAAgB,YAAY,IAAI,sBAAsB,CAUrD;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,sBAAsB,CAYnE"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Transports — pino transport configurations for file, pretty, and multi-target.
3
+ */
4
+ /**
5
+ * Build a pretty-print transport target (for development).
6
+ */
7
+ export function prettyTarget() {
8
+ return {
9
+ target: 'pino-pretty',
10
+ options: {
11
+ colorize: true,
12
+ translateTime: 'HH:MM:ss.l',
13
+ ignore: 'pid,hostname',
14
+ messageFormat: '{if package}[{package}]{end}{if component}.{component}{end} {msg}',
15
+ },
16
+ };
17
+ }
18
+ /**
19
+ * Build a file rotation transport target.
20
+ *
21
+ * Uses pino-roll: rotates daily or at 10MB, keeps last 5 files.
22
+ */
23
+ export function fileTarget(filePath) {
24
+ return {
25
+ target: 'pino-roll',
26
+ options: {
27
+ file: filePath,
28
+ frequency: 'daily',
29
+ size: '10m',
30
+ limit: { count: 5 },
31
+ dateFormat: 'yyyy-MM-dd',
32
+ mkdir: true,
33
+ },
34
+ };
35
+ }
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@compilr-dev/logger",
3
+ "version": "0.1.0",
4
+ "description": "Structured logging for the compilr-dev ecosystem",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ },
13
+ "./renderer": {
14
+ "import": "./dist/renderer.js",
15
+ "types": "./dist/renderer.d.ts"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "LICENSE"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc",
24
+ "lint": "eslint src/",
25
+ "format": "prettier --write src/",
26
+ "format:check": "prettier --check src/",
27
+ "test": "vitest",
28
+ "prepublishOnly": "npm run build"
29
+ },
30
+ "dependencies": {
31
+ "pino": "^9.6.0",
32
+ "pino-pretty": "^13.0.0",
33
+ "pino-roll": "^4.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^22.0.0",
37
+ "eslint": "^9.0.0",
38
+ "prettier": "^3.4.0",
39
+ "typescript": "^5.7.0",
40
+ "vitest": "^3.0.0"
41
+ },
42
+ "engines": {
43
+ "node": ">=22.0.0"
44
+ },
45
+ "license": "SEE LICENSE IN LICENSE",
46
+ "author": "Carmelo Scozzola",
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "https://github.com/scozzola/compilr-dev-logger.git"
50
+ },
51
+ "keywords": [
52
+ "logging",
53
+ "pino",
54
+ "structured-logging",
55
+ "compilr-dev"
56
+ ]
57
+ }