vedatrace 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.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Aaron Will Djaba
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,293 @@
1
+ # VedaTrace SDK
2
+
3
+ Universal JavaScript logging SDK for VedaTrace. Type-safe, lightweight, and developer-friendly.
4
+
5
+ [![npm version](https://badge.fury.io/js/vedatrace.svg)](https://www.npmjs.com/package/vedatrace)
6
+ [![bundle size](https://img.shields.io/bundlephobia/minzip/vedatrace)](https://bundlephobia.com/package/vedatrace)
7
+
8
+ ## Features
9
+
10
+ - 🎯 **Type-safe** - Full TypeScript support with autocomplete
11
+ - 🚀 **Universal** - Works in Node.js, Cloudflare Workers, and browsers
12
+ - 📦 **Lightweight** - ~3KB core, tree-shakeable
13
+ - âš¡ **Fast** - Background batching, non-blocking
14
+ - 🔒 **Safe** - Never breaks your app, graceful failures
15
+ - 🎨 **Flexible** - Console + HTTP transports, child loggers
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install vedatrace
21
+ # or
22
+ yarn add vedatrace
23
+ # or
24
+ bun add vedatrace
25
+ ```
26
+
27
+ ## Quick Start
28
+
29
+ ### Basic Usage
30
+
31
+ ```typescript
32
+ import { vedatrace } from 'vedatrace'
33
+
34
+ const logger = vedatrace({
35
+ apiKey: 'your-api-key',
36
+ service: 'my-service'
37
+ })
38
+
39
+ logger.info('Hello world')
40
+ logger.error('Something went wrong', { error: err.message })
41
+ ```
42
+
43
+ ### Development Mode
44
+
45
+ ```typescript
46
+ import { devVedatrace } from 'vedatrace'
47
+
48
+ // Console-only logging for development
49
+ const logger = devVedatrace({ service: 'my-service' })
50
+ ```
51
+
52
+ ## Configuration
53
+
54
+ ```typescript
55
+ const logger = vedatrace({
56
+ apiKey: 'your-api-key', // Required for HTTP transport
57
+ service: 'my-service', // Default service name
58
+ endpoint: 'https://ingest.vedatrace.dev/v1/logs',
59
+ environment: 'production',
60
+
61
+ // Batching
62
+ batchSize: 100, // Flush after N logs
63
+ flushInterval: 5000, // Flush after N ms
64
+
65
+ // Retry
66
+ maxRetries: 3,
67
+ retryDelay: 1000,
68
+
69
+ // Redaction
70
+ redaction: {
71
+ paths: ['password', 'token'],
72
+ mask: '[REDACTED]'
73
+ },
74
+
75
+ // Callbacks
76
+ onError: (err) => console.error('VedaTrace error:', err),
77
+ onSuccess: () => console.log('Logs sent')
78
+ })
79
+ ```
80
+
81
+ ## Logging
82
+
83
+ ### All Log Levels
84
+
85
+ ```typescript
86
+ logger.debug('Debug info', { query: 'SELECT *' })
87
+ logger.info('User action', { userId: '123' })
88
+ logger.warn('Performance warning', { duration: 500 })
89
+ logger.error('Error occurred', { error: err })
90
+ logger.fatal('Critical failure', { stack: err.stack })
91
+ ```
92
+
93
+ ### Service Override
94
+
95
+ Override the default service for individual logs:
96
+
97
+ ```typescript
98
+ logger.info('Payment processed', {
99
+ service: 'billing-service', // Override default
100
+ amount: 99.99
101
+ })
102
+ ```
103
+
104
+ ## Child Loggers
105
+
106
+ Create context-aware loggers:
107
+
108
+ ```typescript
109
+ const requestLogger = logger.child({
110
+ requestId: 'req_123',
111
+ userId: 'user_456'
112
+ })
113
+
114
+ requestLogger.info('Processing request')
115
+ // Includes requestId, userId, and default service
116
+ ```
117
+
118
+ ## Framework Integrations
119
+
120
+ ### Express.js
121
+
122
+ ```typescript
123
+ import express from 'express'
124
+ import { vedaTraceMiddleware } from 'vedatrace/express'
125
+
126
+ const app = express()
127
+ app.use(vedaTraceMiddleware({
128
+ apiKey: process.env.VEDATRACE_API_KEY
129
+ }))
130
+
131
+ app.get('/', (req, res) => {
132
+ req.vedatrace.info('Home page visited')
133
+ res.json({ ok: true })
134
+ })
135
+ ```
136
+
137
+ ### Next.js (App Router)
138
+
139
+ ```typescript
140
+ import { withVedaTrace } from 'vedatrace/next'
141
+
142
+ export const GET = withVedaTrace(async (req, { logger }) => {
143
+ logger.info('API called')
144
+ return Response.json({ success: true })
145
+ }, { apiKey: '...' })
146
+ ```
147
+
148
+ ### React
149
+
150
+ ```tsx
151
+ import { VedaTraceProvider, useVedaTrace } from 'vedatrace/react'
152
+
153
+ function App() {
154
+ return (
155
+ <VedaTraceProvider apiKey="..." service="frontend">
156
+ <MyComponent />
157
+ </VedaTraceProvider>
158
+ )
159
+ }
160
+
161
+ function MyComponent() {
162
+ const logger = useVedaTrace()
163
+
164
+ useEffect(() => {
165
+ logger.info('Component mounted')
166
+ }, [])
167
+
168
+ return <div>Hello</div>
169
+ }
170
+ ```
171
+
172
+ ## Cloudflare Workers
173
+
174
+ ```typescript
175
+ import { vedatrace } from 'vedatrace'
176
+
177
+ export default {
178
+ async fetch(req, env, ctx) {
179
+ const logger = vedatrace({
180
+ apiKey: env.VEDATRACE_API_KEY,
181
+ service: 'worker'
182
+ })
183
+
184
+ logger.info('Request received', {
185
+ method: req.method,
186
+ url: req.url
187
+ })
188
+
189
+ // Ensure logs are sent before response
190
+ ctx.waitUntil(logger.flush())
191
+
192
+ return new Response('OK')
193
+ }
194
+ }
195
+ ```
196
+
197
+ ## Advanced Usage
198
+
199
+ ### Custom Transports
200
+
201
+ ```typescript
202
+ import { VedaTraceHttpTransport, VedaTraceConsoleTransport } from 'vedatrace/transports'
203
+
204
+ const logger = vedatrace({
205
+ transports: [
206
+ new VedaTraceHttpTransport({ apiKey: '...' }),
207
+ new VedaTraceConsoleTransport({ format: 'pretty' })
208
+ ]
209
+ })
210
+ ```
211
+
212
+ ### Manual Flush
213
+
214
+ ```typescript
215
+ // Flush all pending logs
216
+ await logger.flush()
217
+
218
+ // Use in request handlers
219
+ app.post('/webhook', async (req, res) => {
220
+ logger.info('Webhook received')
221
+ await logger.flush() // Ensure sent before responding
222
+ res.json({ ok: true })
223
+ })
224
+ ```
225
+
226
+ ### Error Handling
227
+
228
+ ```typescript
229
+ const logger = vedatrace({
230
+ apiKey: '...',
231
+ onError: (err) => {
232
+ // Handle transport errors
233
+ metrics.increment('vedatrace.errors')
234
+ }
235
+ })
236
+
237
+ // SDK never throws - errors are logged to onError
238
+ logger.error('Critical error', { stack: err.stack })
239
+ ```
240
+
241
+ ## Log Schema
242
+
243
+ Logs sent to VedaTrace follow this schema:
244
+
245
+ ```typescript
246
+ {
247
+ level: 'debug' | 'info' | 'warn' | 'error' | 'fatal'
248
+ message: string
249
+ service?: string
250
+ timestamp?: number // Auto-generated if not provided
251
+ metadata?: {
252
+ // Any arbitrary metadata
253
+ }
254
+ }
255
+ ```
256
+
257
+ ## API Reference
258
+
259
+ ### `vedatrace(config)`
260
+
261
+ Creates a new logger instance.
262
+
263
+ ### `logger.debug(message, metadata?)`
264
+
265
+ Log at debug level.
266
+
267
+ ### `logger.info(message, metadata?)`
268
+
269
+ Log at info level.
270
+
271
+ ### `logger.warn(message, metadata?)`
272
+
273
+ Log at warn level.
274
+
275
+ ### `logger.error(message | Error, metadata?)`
276
+
277
+ Log at error level. Accepts string or Error object.
278
+
279
+ ### `logger.fatal(message | Error, metadata?)`
280
+
281
+ Log at fatal level. Accepts string or Error object.
282
+
283
+ ### `logger.child(defaults)`
284
+
285
+ Create a child logger with default metadata.
286
+
287
+ ### `logger.flush()`
288
+
289
+ Manually flush pending logs. Returns a Promise.
290
+
291
+ ## License
292
+
293
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,338 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var transports_index = require('./transports/index.cjs');
6
+
7
+ class VedaTraceBatcher {
8
+ constructor(transports, config, onError, onSuccess) {
9
+ this.transports = transports;
10
+ this.config = config;
11
+ this.onError = onError;
12
+ this.onSuccess = onSuccess;
13
+ this.startFlushTimer();
14
+ }
15
+ queue = [];
16
+ flushTimer = null;
17
+ isFlushing = false;
18
+ pendingFlush = null;
19
+ /** Add log to queue */
20
+ add(log) {
21
+ this.queue.push(log);
22
+ if (this.queue.length >= this.config.batchSize) {
23
+ this.flush();
24
+ }
25
+ }
26
+ /** Flush logs to all transports */
27
+ async flush() {
28
+ if (this.isFlushing) {
29
+ return this.pendingFlush ?? Promise.resolve();
30
+ }
31
+ if (this.queue.length === 0) {
32
+ return Promise.resolve();
33
+ }
34
+ this.isFlushing = true;
35
+ const logsToSend = [...this.queue];
36
+ this.queue = [];
37
+ this.pendingFlush = this.sendWithRetry(logsToSend).finally(() => {
38
+ this.isFlushing = false;
39
+ this.pendingFlush = null;
40
+ });
41
+ return this.pendingFlush;
42
+ }
43
+ /** Send logs with retry logic */
44
+ async sendWithRetry(logs, attempt = 0) {
45
+ const errors = [];
46
+ for (const transport of this.transports) {
47
+ try {
48
+ await transport.send(logs);
49
+ } catch (error) {
50
+ errors.push(error instanceof Error ? error : new Error(String(error)));
51
+ }
52
+ }
53
+ if (errors.length > 0 && errors.length === this.transports.length) {
54
+ if (attempt < this.config.maxRetries) {
55
+ await this.delay(this.config.retryDelay * (attempt + 1));
56
+ return this.sendWithRetry(logs, attempt + 1);
57
+ }
58
+ const combinedError = new Error(
59
+ `Failed to send logs after ${this.config.maxRetries} retries: ${errors.map((e) => e.message).join(", ")}`
60
+ );
61
+ this.onError?.(combinedError);
62
+ return;
63
+ }
64
+ this.onSuccess?.();
65
+ }
66
+ /** Start the flush interval timer */
67
+ startFlushTimer() {
68
+ if (this.flushTimer) {
69
+ clearInterval(this.flushTimer);
70
+ }
71
+ this.flushTimer = setInterval(() => {
72
+ if (this.queue.length > 0) {
73
+ this.flush();
74
+ }
75
+ }, this.config.flushInterval);
76
+ }
77
+ /** Stop the flush timer */
78
+ stop() {
79
+ if (this.flushTimer) {
80
+ clearInterval(this.flushTimer);
81
+ this.flushTimer = null;
82
+ }
83
+ }
84
+ /** Delay helper */
85
+ delay(ms) {
86
+ return new Promise((resolve) => setTimeout(resolve, ms));
87
+ }
88
+ /** Get current queue size */
89
+ getQueueSize() {
90
+ return this.queue.length;
91
+ }
92
+ }
93
+
94
+ const SDK_VERSION = "1.0.0";
95
+ class VedaTraceLogger {
96
+ batcher = null;
97
+ config;
98
+ childDefaults;
99
+ constructor(config = {}, childDefaults = {}) {
100
+ this.childDefaults = childDefaults;
101
+ this.config = {
102
+ service: config.service,
103
+ apiKey: config.apiKey,
104
+ endpoint: config.endpoint ?? "https://api.vedatrace.io/v1/logs",
105
+ environment: config.environment,
106
+ batchSize: config.batchSize ?? 100,
107
+ flushInterval: config.flushInterval ?? 5e3,
108
+ maxRetries: config.maxRetries ?? 3,
109
+ retryDelay: config.retryDelay ?? 1e3,
110
+ onError: config.onError,
111
+ onSuccess: config.onSuccess,
112
+ debug: config.debug ?? false
113
+ };
114
+ if (!config.disabled) {
115
+ this.initializeBatcher(config);
116
+ }
117
+ }
118
+ /** Initialize the batcher with transports */
119
+ initializeBatcher(config) {
120
+ const transports = config.transports ?? [];
121
+ if (config.apiKey && transports.length === 0) ;
122
+ if (transports.length > 0) {
123
+ this.batcher = new VedaTraceBatcher(
124
+ transports,
125
+ {
126
+ batchSize: this.config.batchSize,
127
+ flushInterval: this.config.flushInterval,
128
+ maxRetries: this.config.maxRetries,
129
+ retryDelay: this.config.retryDelay
130
+ },
131
+ this.config.onError,
132
+ this.config.onSuccess
133
+ );
134
+ }
135
+ }
136
+ /** Set batcher (called from factory function) */
137
+ setBatcher(batcher) {
138
+ this.batcher = batcher;
139
+ }
140
+ /** Log at debug level */
141
+ debug(message, metadata) {
142
+ this.log("debug", message, metadata);
143
+ }
144
+ /** Log at info level */
145
+ info(message, metadata) {
146
+ this.log("info", message, metadata);
147
+ }
148
+ /** Log at warn level */
149
+ warn(message, metadata) {
150
+ this.log("warn", message, metadata);
151
+ }
152
+ /** Log at error level */
153
+ error(message, metadata) {
154
+ this.log("error", message, metadata);
155
+ }
156
+ /** Log at fatal level */
157
+ fatal(message, metadata) {
158
+ this.log("fatal", message, metadata);
159
+ }
160
+ /** Internal log method */
161
+ log(level, message, metadata) {
162
+ if (!this.batcher) {
163
+ return;
164
+ }
165
+ const mergedMetadata = { ...this.childDefaults, ...metadata };
166
+ const { service: metaService, ...cleanMetadata } = mergedMetadata;
167
+ const service = metaService ?? this.config.service;
168
+ const logEntry = {
169
+ level,
170
+ message: message instanceof Error ? message.message : message,
171
+ service,
172
+ timestamp: Date.now(),
173
+ metadata: cleanMetadata,
174
+ _sdk: {
175
+ source: this.detectEnvironment(),
176
+ version: SDK_VERSION
177
+ }
178
+ };
179
+ if (message instanceof Error) {
180
+ logEntry._sdk ??= {};
181
+ logEntry._sdk.stackTrace = message.stack;
182
+ }
183
+ if (this.config.debug) {
184
+ console.log(`[VedaTrace:${level}]`, logEntry);
185
+ }
186
+ this.batcher.add(logEntry);
187
+ }
188
+ /** Create a child logger with default metadata */
189
+ child(defaults) {
190
+ const mergedDefaults = { ...this.childDefaults, ...defaults };
191
+ const childLogger = new VedaTraceLogger(
192
+ {
193
+ service: this.config.service,
194
+ apiKey: this.config.apiKey,
195
+ endpoint: this.config.endpoint,
196
+ environment: this.config.environment,
197
+ disabled: !this.batcher
198
+ },
199
+ mergedDefaults
200
+ );
201
+ if (this.batcher) {
202
+ childLogger.setBatcher(this.batcher);
203
+ }
204
+ return childLogger;
205
+ }
206
+ /** Flush pending logs */
207
+ async flush() {
208
+ if (this.batcher) {
209
+ await this.batcher.flush();
210
+ }
211
+ }
212
+ /** Detect runtime environment */
213
+ detectEnvironment() {
214
+ if (typeof globalThis !== "undefined" && "navigator" in globalThis) {
215
+ return "browser";
216
+ }
217
+ if (typeof process !== "undefined" && process.versions?.node) {
218
+ return "node";
219
+ }
220
+ return "edge";
221
+ }
222
+ }
223
+
224
+ const PII_PATTERNS = {
225
+ // Email addresses
226
+ email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,
227
+ // Phone numbers (various formats)
228
+ phone: /(\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}/g,
229
+ // Social Security Numbers
230
+ ssn: /\b\d{3}-?\d{2}-?\d{4}\b/g,
231
+ // Credit card numbers (simplified)
232
+ creditCard: /\b(?:\d{4}[-\s]?){3}\d{4}\b/g
233
+ };
234
+ const SENSITIVE_KEYS = [
235
+ "password",
236
+ "token",
237
+ "secret",
238
+ "key",
239
+ "apiKey",
240
+ "api_key",
241
+ "auth",
242
+ "authorization",
243
+ "cookie",
244
+ "session",
245
+ "credit_card",
246
+ "creditCard",
247
+ "cvv",
248
+ "ssn",
249
+ "social_security",
250
+ "dob",
251
+ "birthdate"
252
+ ];
253
+ function redact(obj, config = {}) {
254
+ if (!obj || typeof obj !== "object") {
255
+ return obj;
256
+ }
257
+ const { paths = [], mask = "[REDACTED]", autoDetectPii = true } = config;
258
+ if (Array.isArray(obj)) {
259
+ return obj.map((item) => redact(item, config));
260
+ }
261
+ const result = {};
262
+ for (const [key, value] of Object.entries(obj)) {
263
+ if (isSensitiveKey(key, paths)) {
264
+ result[key] = mask;
265
+ continue;
266
+ }
267
+ if (value && typeof value === "object") {
268
+ result[key] = redact(value, config);
269
+ continue;
270
+ }
271
+ if (autoDetectPii && typeof value === "string") {
272
+ result[key] = redactPii(value, mask);
273
+ } else {
274
+ result[key] = value;
275
+ }
276
+ }
277
+ return result;
278
+ }
279
+ function isSensitiveKey(key, customPaths) {
280
+ const lowerKey = key.toLowerCase();
281
+ if (SENSITIVE_KEYS.some((sensitive) => lowerKey.includes(sensitive))) {
282
+ return true;
283
+ }
284
+ return customPaths.some((path) => {
285
+ const parts = path.split(".");
286
+ const lastPart = parts[parts.length - 1];
287
+ return lastPart ? lastPart.toLowerCase() === lowerKey : false;
288
+ });
289
+ }
290
+ function redactPii(value, mask) {
291
+ let result = value;
292
+ for (const [type, pattern] of Object.entries(PII_PATTERNS)) {
293
+ result = result.replace(pattern, `[${type.toUpperCase()}:${mask}]`);
294
+ }
295
+ return result;
296
+ }
297
+
298
+ function vedatrace(config = {}) {
299
+ const logger = new VedaTraceLogger(config);
300
+ if (config.apiKey && (!config.transports || config.transports.length === 0)) {
301
+ const httpConfig = { apiKey: config.apiKey };
302
+ if (config.endpoint) httpConfig.endpoint = config.endpoint;
303
+ const httpTransport = new transports_index.VedaTraceHttpTransport(httpConfig);
304
+ const batcher = new VedaTraceBatcher(
305
+ [httpTransport],
306
+ {
307
+ batchSize: config.batchSize ?? 100,
308
+ flushInterval: config.flushInterval ?? 5e3,
309
+ maxRetries: config.maxRetries ?? 3,
310
+ retryDelay: config.retryDelay ?? 1e3
311
+ },
312
+ config.onError,
313
+ config.onSuccess
314
+ );
315
+ logger.setBatcher(batcher);
316
+ }
317
+ return logger;
318
+ }
319
+ function devVedatrace(config = {}) {
320
+ return vedatrace({
321
+ ...config,
322
+ transports: [
323
+ new transports_index.VedaTraceConsoleTransport({
324
+ format: "pretty",
325
+ colors: true
326
+ })
327
+ ]
328
+ });
329
+ }
330
+
331
+ exports.VedaTraceConsoleTransport = transports_index.VedaTraceConsoleTransport;
332
+ exports.VedaTraceHttpTransport = transports_index.VedaTraceHttpTransport;
333
+ exports.VedaTraceBatcher = VedaTraceBatcher;
334
+ exports.VedaTraceLogger = VedaTraceLogger;
335
+ exports.default = vedatrace;
336
+ exports.devVedatrace = devVedatrace;
337
+ exports.redact = redact;
338
+ exports.vedatrace = vedatrace;