@statly/observe 1.2.0 → 1.2.1

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.
@@ -1,1459 +1,4 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/logger/index.ts
31
- var logger_exports = {};
32
- __export(logger_exports, {
33
- AIFeatures: () => AIFeatures,
34
- ConsoleDestination: () => ConsoleDestination,
35
- DEFAULT_LEVELS: () => DEFAULT_LEVELS,
36
- EXTENDED_LEVELS: () => EXTENDED_LEVELS,
37
- FileDestination: () => FileDestination,
38
- LOG_LEVELS: () => LOG_LEVELS,
39
- Logger: () => Logger,
40
- ObserveDestination: () => ObserveDestination,
41
- REDACTED: () => REDACTED,
42
- SCRUB_PATTERNS: () => SCRUB_PATTERNS,
43
- SENSITIVE_KEYS: () => SENSITIVE_KEYS,
44
- Scrubber: () => Scrubber,
45
- audit: () => audit,
46
- debug: () => debug,
47
- error: () => error,
48
- fatal: () => fatal,
49
- formatJson: () => formatJson,
50
- formatJsonPretty: () => formatJsonPretty,
51
- formatPretty: () => formatPretty,
52
- getConsoleMethod: () => getConsoleMethod,
53
- getDefaultLogger: () => getDefaultLogger,
54
- info: () => info,
55
- isSensitiveKey: () => isSensitiveKey,
56
- setDefaultLogger: () => setDefaultLogger,
57
- trace: () => trace,
58
- warn: () => warn
59
- });
60
- module.exports = __toCommonJS(logger_exports);
61
-
62
- // src/logger/types.ts
63
- var LOG_LEVELS = {
64
- trace: 0,
65
- debug: 1,
66
- info: 2,
67
- warn: 3,
68
- error: 4,
69
- fatal: 5,
70
- audit: 6
71
- // Special: always logged, never sampled
72
- };
73
- var DEFAULT_LEVELS = ["debug", "info", "warn", "error", "fatal"];
74
- var EXTENDED_LEVELS = ["trace", "debug", "info", "warn", "error", "fatal", "audit"];
75
-
76
- // src/logger/scrubbing/patterns.ts
77
- var SENSITIVE_KEYS = /* @__PURE__ */ new Set([
78
- "password",
79
- "passwd",
80
- "pwd",
81
- "secret",
82
- "api_key",
83
- "apikey",
84
- "api-key",
85
- "token",
86
- "access_token",
87
- "accesstoken",
88
- "refresh_token",
89
- "auth",
90
- "authorization",
91
- "bearer",
92
- "credential",
93
- "credentials",
94
- "private_key",
95
- "privatekey",
96
- "private-key",
97
- "secret_key",
98
- "secretkey",
99
- "secret-key",
100
- "session_id",
101
- "sessionid",
102
- "session-id",
103
- "session",
104
- "cookie",
105
- "x-api-key",
106
- "x-auth-token",
107
- "x-access-token"
108
- ]);
109
- var SCRUB_PATTERNS = {
110
- apiKey: {
111
- regex: /(?:api[_-]?key|apikey)\s*[=:]\s*["']?([a-zA-Z0-9_\-]{20,})["']?/gi,
112
- description: "API keys in various formats"
113
- },
114
- password: {
115
- regex: /(?:password|passwd|pwd|secret)\s*[=:]\s*["']?([^"'\s]{3,})["']?/gi,
116
- description: "Passwords and secrets"
117
- },
118
- token: {
119
- regex: /(?:bearer\s+|token\s*[=:]\s*["']?)([a-zA-Z0-9_\-\.]{20,})["']?/gi,
120
- description: "Bearer tokens and auth tokens"
121
- },
122
- creditCard: {
123
- // Visa, Mastercard, Amex, Discover, etc.
124
- regex: /\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})\b/g,
125
- description: "Credit card numbers"
126
- },
127
- ssn: {
128
- regex: /\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b/g,
129
- description: "US Social Security Numbers"
130
- },
131
- email: {
132
- regex: /\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/g,
133
- description: "Email addresses"
134
- },
135
- ipAddress: {
136
- regex: /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,
137
- description: "IPv4 addresses"
138
- },
139
- awsKey: {
140
- regex: /(?:AKIA|ABIA|ACCA)[A-Z0-9]{16}/g,
141
- description: "AWS Access Key IDs"
142
- },
143
- privateKey: {
144
- regex: /-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |DSA )?PRIVATE KEY-----/g,
145
- description: "Private keys in PEM format"
146
- },
147
- jwt: {
148
- regex: /eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*/g,
149
- description: "JSON Web Tokens"
150
- }
151
- };
152
- var REDACTED = "[REDACTED]";
153
- function isSensitiveKey(key) {
154
- const lowerKey = key.toLowerCase();
155
- return SENSITIVE_KEYS.has(lowerKey);
156
- }
157
-
158
- // src/logger/scrubbing/scrubber.ts
159
- var Scrubber = class {
160
- constructor(config = {}) {
161
- this.enabled = config.enabled !== false;
162
- this.patterns = /* @__PURE__ */ new Map();
163
- this.customPatterns = config.customPatterns || [];
164
- this.allowlist = new Set((config.allowlist || []).map((k) => k.toLowerCase()));
165
- this.customScrubber = config.customScrubber;
166
- const patternNames = config.patterns || [
167
- "apiKey",
168
- "password",
169
- "token",
170
- "creditCard",
171
- "ssn",
172
- "awsKey",
173
- "privateKey",
174
- "jwt"
175
- ];
176
- for (const name of patternNames) {
177
- const pattern = SCRUB_PATTERNS[name];
178
- if (pattern) {
179
- this.patterns.set(name, new RegExp(pattern.regex.source, pattern.regex.flags));
180
- }
181
- }
182
- }
183
- /**
184
- * Scrub sensitive data from a value
185
- */
186
- scrub(value) {
187
- if (!this.enabled) {
188
- return value;
189
- }
190
- return this.scrubValue(value, "");
191
- }
192
- /**
193
- * Scrub a log message string
194
- */
195
- scrubMessage(message) {
196
- if (!this.enabled) {
197
- return message;
198
- }
199
- let result = message;
200
- for (const [, regex] of this.patterns) {
201
- result = result.replace(regex, REDACTED);
202
- }
203
- for (const regex of this.customPatterns) {
204
- result = result.replace(regex, REDACTED);
205
- }
206
- return result;
207
- }
208
- /**
209
- * Recursively scrub sensitive data
210
- */
211
- scrubValue(value, key) {
212
- if (key && this.allowlist.has(key.toLowerCase())) {
213
- return value;
214
- }
215
- if (this.customScrubber && key) {
216
- const result = this.customScrubber(key, value);
217
- if (result !== value) {
218
- return result;
219
- }
220
- }
221
- if (key && isSensitiveKey(key)) {
222
- return REDACTED;
223
- }
224
- if (value === null || value === void 0) {
225
- return value;
226
- }
227
- if (typeof value === "string") {
228
- return this.scrubString(value);
229
- }
230
- if (Array.isArray(value)) {
231
- return value.map((item, index) => this.scrubValue(item, String(index)));
232
- }
233
- if (typeof value === "object") {
234
- return this.scrubObject(value);
235
- }
236
- return value;
237
- }
238
- /**
239
- * Scrub sensitive patterns from a string
240
- */
241
- scrubString(value) {
242
- let result = value;
243
- for (const [, regex] of this.patterns) {
244
- regex.lastIndex = 0;
245
- result = result.replace(regex, REDACTED);
246
- }
247
- for (const regex of this.customPatterns) {
248
- const newRegex = new RegExp(regex.source, regex.flags);
249
- result = result.replace(newRegex, REDACTED);
250
- }
251
- return result;
252
- }
253
- /**
254
- * Scrub sensitive data from an object
255
- */
256
- scrubObject(obj) {
257
- const result = {};
258
- for (const [key, value] of Object.entries(obj)) {
259
- result[key] = this.scrubValue(value, key);
260
- }
261
- return result;
262
- }
263
- /**
264
- * Add a custom pattern at runtime
265
- */
266
- addPattern(pattern) {
267
- this.customPatterns.push(pattern);
268
- }
269
- /**
270
- * Add a key to the allowlist
271
- */
272
- addToAllowlist(key) {
273
- this.allowlist.add(key.toLowerCase());
274
- }
275
- /**
276
- * Check if scrubbing is enabled
277
- */
278
- isEnabled() {
279
- return this.enabled;
280
- }
281
- /**
282
- * Enable or disable scrubbing
283
- */
284
- setEnabled(enabled) {
285
- this.enabled = enabled;
286
- }
287
- };
288
-
289
- // src/logger/formatters/console.ts
290
- var COLORS = {
291
- reset: "\x1B[0m",
292
- bold: "\x1B[1m",
293
- dim: "\x1B[2m",
294
- // Foreground colors
295
- black: "\x1B[30m",
296
- red: "\x1B[31m",
297
- green: "\x1B[32m",
298
- yellow: "\x1B[33m",
299
- blue: "\x1B[34m",
300
- magenta: "\x1B[35m",
301
- cyan: "\x1B[36m",
302
- white: "\x1B[37m",
303
- gray: "\x1B[90m",
304
- // Background colors
305
- bgRed: "\x1B[41m",
306
- bgYellow: "\x1B[43m"
307
- };
308
- var LEVEL_COLORS = {
309
- trace: COLORS.gray,
310
- debug: COLORS.cyan,
311
- info: COLORS.green,
312
- warn: COLORS.yellow,
313
- error: COLORS.red,
314
- fatal: `${COLORS.bgRed}${COLORS.white}`,
315
- audit: COLORS.magenta
316
- };
317
- var LEVEL_LABELS = {
318
- trace: "TRACE",
319
- debug: "DEBUG",
320
- info: "INFO ",
321
- warn: "WARN ",
322
- error: "ERROR",
323
- fatal: "FATAL",
324
- audit: "AUDIT"
325
- };
326
- function formatPretty(entry, options = {}) {
327
- const {
328
- colors = true,
329
- timestamps = true,
330
- showLevel = true,
331
- showLogger = true,
332
- showContext = true,
333
- showSource = false
334
- } = options;
335
- const parts = [];
336
- if (timestamps) {
337
- const date = new Date(entry.timestamp);
338
- const time = date.toISOString().replace("T", " ").replace("Z", "");
339
- parts.push(colors ? `${COLORS.dim}${time}${COLORS.reset}` : time);
340
- }
341
- if (showLevel) {
342
- const levelColor = colors ? LEVEL_COLORS[entry.level] : "";
343
- const levelLabel = LEVEL_LABELS[entry.level];
344
- parts.push(colors ? `${levelColor}${levelLabel}${COLORS.reset}` : levelLabel);
345
- }
346
- if (showLogger && entry.loggerName) {
347
- parts.push(colors ? `${COLORS.blue}[${entry.loggerName}]${COLORS.reset}` : `[${entry.loggerName}]`);
348
- }
349
- parts.push(entry.message);
350
- if (showSource && entry.source) {
351
- const { file, line, function: fn } = entry.source;
352
- const loc = [file, line, fn].filter(Boolean).join(":");
353
- if (loc) {
354
- parts.push(colors ? `${COLORS.dim}(${loc})${COLORS.reset}` : `(${loc})`);
355
- }
356
- }
357
- let result = parts.join(" ");
358
- if (showContext && entry.context && Object.keys(entry.context).length > 0) {
359
- const contextStr = JSON.stringify(entry.context, null, 2);
360
- result += "\n" + (colors ? `${COLORS.dim}${contextStr}${COLORS.reset}` : contextStr);
361
- }
362
- return result;
363
- }
364
- function formatJson(entry) {
365
- return JSON.stringify(entry);
366
- }
367
- function formatJsonPretty(entry) {
368
- return JSON.stringify(entry, null, 2);
369
- }
370
- function getConsoleMethod(level) {
371
- switch (level) {
372
- case "trace":
373
- return "trace";
374
- case "debug":
375
- return "debug";
376
- case "info":
377
- return "info";
378
- case "warn":
379
- return "warn";
380
- case "error":
381
- case "fatal":
382
- return "error";
383
- case "audit":
384
- return "info";
385
- default:
386
- return "log";
387
- }
388
- }
389
-
390
- // src/logger/destinations/console.ts
391
- var ConsoleDestination = class {
392
- constructor(config = {}) {
393
- this.name = "console";
394
- this.config = {
395
- enabled: config.enabled !== false,
396
- colors: config.colors !== false,
397
- format: config.format || "pretty",
398
- timestamps: config.timestamps !== false,
399
- levels: config.levels || ["trace", "debug", "info", "warn", "error", "fatal", "audit"]
400
- };
401
- this.minLevel = 0;
402
- }
403
- /**
404
- * Write a log entry to the console
405
- */
406
- write(entry) {
407
- if (!this.config.enabled) {
408
- return;
409
- }
410
- if (!this.config.levels.includes(entry.level)) {
411
- return;
412
- }
413
- if (LOG_LEVELS[entry.level] < this.minLevel) {
414
- return;
415
- }
416
- let output;
417
- if (this.config.format === "json") {
418
- output = formatJson(entry);
419
- } else {
420
- output = formatPretty(entry, {
421
- colors: this.config.colors && this.supportsColors(),
422
- timestamps: this.config.timestamps
423
- });
424
- }
425
- const method = getConsoleMethod(entry.level);
426
- console[method](output);
427
- }
428
- /**
429
- * Check if the environment supports colors
430
- */
431
- supportsColors() {
432
- if (typeof window !== "undefined") {
433
- return true;
434
- }
435
- if (typeof process !== "undefined") {
436
- if (process.stdout && "isTTY" in process.stdout) {
437
- return Boolean(process.stdout.isTTY);
438
- }
439
- const env = process.env;
440
- if (env.FORCE_COLOR !== void 0) {
441
- return env.FORCE_COLOR !== "0";
442
- }
443
- if (env.NO_COLOR !== void 0) {
444
- return false;
445
- }
446
- if (env.TERM === "dumb") {
447
- return false;
448
- }
449
- return true;
450
- }
451
- return false;
452
- }
453
- /**
454
- * Set minimum log level
455
- */
456
- setMinLevel(level) {
457
- this.minLevel = LOG_LEVELS[level];
458
- }
459
- /**
460
- * Enable or disable the destination
461
- */
462
- setEnabled(enabled) {
463
- this.config.enabled = enabled;
464
- }
465
- /**
466
- * Set color mode
467
- */
468
- setColors(enabled) {
469
- this.config.colors = enabled;
470
- }
471
- /**
472
- * Set output format
473
- */
474
- setFormat(format) {
475
- this.config.format = format;
476
- }
477
- };
478
-
479
- // src/logger/destinations/observe.ts
480
- var DEFAULT_BATCH_SIZE = 50;
481
- var DEFAULT_FLUSH_INTERVAL = 5e3;
482
- var DEFAULT_SAMPLING = {
483
- trace: 0.01,
484
- // 1%
485
- debug: 0.1,
486
- // 10%
487
- info: 0.5,
488
- // 50%
489
- warn: 1,
490
- // 100%
491
- error: 1,
492
- // 100%
493
- fatal: 1,
494
- // 100%
495
- audit: 1
496
- // 100% - never sampled
497
- };
498
- var ObserveDestination = class {
499
- constructor(dsn, config = {}) {
500
- this.name = "observe";
501
- this.queue = [];
502
- this.isFlushing = false;
503
- this.minLevel = 0;
504
- this.dsn = dsn;
505
- this.endpoint = this.parseEndpoint(dsn);
506
- this.config = {
507
- enabled: config.enabled !== false,
508
- batchSize: config.batchSize || DEFAULT_BATCH_SIZE,
509
- flushInterval: config.flushInterval || DEFAULT_FLUSH_INTERVAL,
510
- sampling: { ...DEFAULT_SAMPLING, ...config.sampling },
511
- levels: config.levels || ["trace", "debug", "info", "warn", "error", "fatal", "audit"]
512
- };
513
- this.startFlushTimer();
514
- }
515
- /**
516
- * Parse DSN to construct endpoint
517
- */
518
- parseEndpoint(dsn) {
519
- try {
520
- const url = new URL(dsn);
521
- return `${url.protocol}//${url.host}/api/v1/logs/ingest`;
522
- } catch {
523
- return "https://statly.live/api/v1/logs/ingest";
524
- }
525
- }
526
- /**
527
- * Start the flush timer
528
- */
529
- startFlushTimer() {
530
- if (this.flushTimer) {
531
- clearInterval(this.flushTimer);
532
- }
533
- if (typeof setInterval !== "undefined") {
534
- this.flushTimer = setInterval(() => {
535
- this.flush();
536
- }, this.config.flushInterval);
537
- }
538
- }
539
- /**
540
- * Write a log entry (queues for batching)
541
- */
542
- write(entry) {
543
- if (!this.config.enabled) {
544
- return;
545
- }
546
- if (!this.config.levels.includes(entry.level)) {
547
- return;
548
- }
549
- if (LOG_LEVELS[entry.level] < this.minLevel) {
550
- return;
551
- }
552
- if (entry.level !== "audit") {
553
- const sampleRate = this.config.sampling[entry.level] ?? 1;
554
- if (Math.random() > sampleRate) {
555
- return;
556
- }
557
- }
558
- this.queue.push(entry);
559
- if (this.queue.length >= this.config.batchSize) {
560
- this.flush();
561
- }
562
- }
563
- /**
564
- * Flush all queued entries to the server
565
- */
566
- async flush() {
567
- if (this.isFlushing || this.queue.length === 0) {
568
- return;
569
- }
570
- this.isFlushing = true;
571
- const entries = [...this.queue];
572
- this.queue = [];
573
- try {
574
- await this.sendBatch(entries);
575
- } catch (error2) {
576
- const maxQueue = this.config.batchSize * 3;
577
- this.queue = [...entries, ...this.queue].slice(0, maxQueue);
578
- console.error("[Statly Logger] Failed to send logs:", error2);
579
- } finally {
580
- this.isFlushing = false;
581
- }
582
- }
583
- /**
584
- * Send a batch of entries to the server
585
- */
586
- async sendBatch(entries) {
587
- if (entries.length === 0) {
588
- return;
589
- }
590
- const response = await fetch(this.endpoint, {
591
- method: "POST",
592
- headers: {
593
- "Content-Type": "application/json",
594
- "X-Statly-DSN": this.dsn
595
- },
596
- body: JSON.stringify({ logs: entries }),
597
- keepalive: true
598
- });
599
- if (!response.ok) {
600
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
601
- }
602
- }
603
- /**
604
- * Close the destination
605
- */
606
- async close() {
607
- if (this.flushTimer) {
608
- clearInterval(this.flushTimer);
609
- }
610
- await this.flush();
611
- }
612
- /**
613
- * Set minimum log level
614
- */
615
- setMinLevel(level) {
616
- this.minLevel = LOG_LEVELS[level];
617
- }
618
- /**
619
- * Set sampling rate for a level
620
- */
621
- setSamplingRate(level, rate) {
622
- this.config.sampling[level] = Math.max(0, Math.min(1, rate));
623
- }
624
- /**
625
- * Enable or disable the destination
626
- */
627
- setEnabled(enabled) {
628
- this.config.enabled = enabled;
629
- }
630
- /**
631
- * Get the current queue size
632
- */
633
- getQueueSize() {
634
- return this.queue.length;
635
- }
636
- };
637
-
638
- // src/logger/destinations/file.ts
639
- function parseSize(size) {
640
- const match = size.match(/^(\d+(?:\.\d+)?)\s*(KB|MB|GB|B)?$/i);
641
- if (!match) return 10 * 1024 * 1024;
642
- const value = parseFloat(match[1]);
643
- const unit = (match[2] || "B").toUpperCase();
644
- switch (unit) {
645
- case "KB":
646
- return value * 1024;
647
- case "MB":
648
- return value * 1024 * 1024;
649
- case "GB":
650
- return value * 1024 * 1024 * 1024;
651
- default:
652
- return value;
653
- }
654
- }
655
- function formatDate(date) {
656
- return date.toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
657
- }
658
- var FileDestination = class {
659
- constructor(config) {
660
- this.name = "file";
661
- this.minLevel = 0;
662
- this.buffer = [];
663
- this.currentSize = 0;
664
- this.writePromise = Promise.resolve();
665
- // File system operations (injected for Node.js compatibility)
666
- this.fs = null;
667
- this.config = {
668
- enabled: config.enabled !== false,
669
- path: config.path,
670
- format: config.format || "json",
671
- rotation: config.rotation || { type: "size", maxSize: "10MB", maxFiles: 5 },
672
- levels: config.levels || ["trace", "debug", "info", "warn", "error", "fatal", "audit"]
673
- };
674
- this.maxSize = parseSize(this.config.rotation.maxSize || "10MB");
675
- this.lastRotation = /* @__PURE__ */ new Date();
676
- this.rotationInterval = this.getRotationInterval();
677
- this.initFileSystem();
678
- }
679
- /**
680
- * Initialize file system operations
681
- */
682
- async initFileSystem() {
683
- if (typeof process !== "undefined" && process.versions?.node) {
684
- try {
685
- const fs = await import("fs/promises");
686
- const path = await import("path");
687
- const fsOps = {
688
- appendFile: fs.appendFile,
689
- rename: fs.rename,
690
- stat: fs.stat,
691
- mkdir: (p, opts) => fs.mkdir(p, opts),
692
- readdir: fs.readdir,
693
- unlink: fs.unlink
694
- };
695
- this.fs = fsOps;
696
- const dir = path.dirname(this.config.path);
697
- await fsOps.mkdir(dir, { recursive: true });
698
- } catch {
699
- console.warn("[Statly Logger] File destination not available (not Node.js)");
700
- this.config.enabled = false;
701
- }
702
- } else {
703
- this.config.enabled = false;
704
- }
705
- }
706
- /**
707
- * Get rotation interval in milliseconds
708
- */
709
- getRotationInterval() {
710
- const { interval } = this.config.rotation;
711
- switch (interval) {
712
- case "hourly":
713
- return 60 * 60 * 1e3;
714
- case "daily":
715
- return 24 * 60 * 60 * 1e3;
716
- case "weekly":
717
- return 7 * 24 * 60 * 60 * 1e3;
718
- default:
719
- return Infinity;
720
- }
721
- }
722
- /**
723
- * Write a log entry
724
- */
725
- write(entry) {
726
- if (!this.config.enabled || !this.fs) {
727
- return;
728
- }
729
- if (!this.config.levels.includes(entry.level)) {
730
- return;
731
- }
732
- if (LOG_LEVELS[entry.level] < this.minLevel) {
733
- return;
734
- }
735
- let line;
736
- if (this.config.format === "json") {
737
- line = formatJson(entry);
738
- } else {
739
- const date = new Date(entry.timestamp).toISOString();
740
- line = `${date} [${entry.level.toUpperCase()}] ${entry.loggerName ? `[${entry.loggerName}] ` : ""}${entry.message}`;
741
- if (entry.context && Object.keys(entry.context).length > 0) {
742
- line += ` ${JSON.stringify(entry.context)}`;
743
- }
744
- }
745
- this.buffer.push(line + "\n");
746
- this.currentSize += line.length + 1;
747
- if (this.buffer.length >= 100 || this.currentSize >= 64 * 1024) {
748
- this.scheduleWrite();
749
- }
750
- }
751
- /**
752
- * Schedule a buffered write
753
- */
754
- scheduleWrite() {
755
- this.writePromise = this.writePromise.then(() => this.writeBuffer());
756
- }
757
- /**
758
- * Write buffer to file
759
- */
760
- async writeBuffer() {
761
- if (!this.fs || this.buffer.length === 0) {
762
- return;
763
- }
764
- await this.checkRotation();
765
- const data = this.buffer.join("");
766
- this.buffer = [];
767
- this.currentSize = 0;
768
- try {
769
- await this.fs.appendFile(this.config.path, data);
770
- } catch (error2) {
771
- console.error("[Statly Logger] Failed to write to file:", error2);
772
- }
773
- }
774
- /**
775
- * Check if rotation is needed
776
- */
777
- async checkRotation() {
778
- if (!this.fs) return;
779
- const { type } = this.config.rotation;
780
- let shouldRotate = false;
781
- if (type === "size") {
782
- try {
783
- const stats = await this.fs.stat(this.config.path);
784
- shouldRotate = stats.size >= this.maxSize;
785
- } catch {
786
- }
787
- } else if (type === "time") {
788
- const now = /* @__PURE__ */ new Date();
789
- shouldRotate = now.getTime() - this.lastRotation.getTime() >= this.rotationInterval;
790
- }
791
- if (shouldRotate) {
792
- await this.rotate();
793
- }
794
- }
795
- /**
796
- * Rotate the log file
797
- */
798
- async rotate() {
799
- if (!this.fs) return;
800
- try {
801
- const rotatedPath = `${this.config.path}.${formatDate(/* @__PURE__ */ new Date())}`;
802
- await this.fs.rename(this.config.path, rotatedPath);
803
- this.lastRotation = /* @__PURE__ */ new Date();
804
- await this.cleanupOldFiles();
805
- } catch (error2) {
806
- console.error("[Statly Logger] Failed to rotate file:", error2);
807
- }
808
- }
809
- /**
810
- * Clean up old rotated files
811
- */
812
- async cleanupOldFiles() {
813
- if (!this.fs) return;
814
- const { maxFiles, retentionDays } = this.config.rotation;
815
- try {
816
- const path = await import("path");
817
- const dir = path.dirname(this.config.path);
818
- const basename = path.basename(this.config.path);
819
- const files = await this.fs.readdir(dir);
820
- const rotatedFiles = files.filter((f) => f.startsWith(basename + ".")).map((f) => ({ name: f, path: path.join(dir, f) })).sort((a, b) => b.name.localeCompare(a.name));
821
- if (maxFiles) {
822
- for (const file of rotatedFiles.slice(maxFiles)) {
823
- await this.fs.unlink(file.path);
824
- }
825
- }
826
- if (retentionDays) {
827
- const cutoff = Date.now() - retentionDays * 24 * 60 * 60 * 1e3;
828
- for (const file of rotatedFiles) {
829
- const match = file.name.match(/\.(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})$/);
830
- if (match) {
831
- const fileDate = new Date(match[1].replace("_", "T").replace(/-/g, ":"));
832
- if (fileDate.getTime() < cutoff) {
833
- await this.fs.unlink(file.path);
834
- }
835
- }
836
- }
837
- }
838
- } catch (error2) {
839
- console.error("[Statly Logger] Failed to cleanup old files:", error2);
840
- }
841
- }
842
- /**
843
- * Flush buffered writes
844
- */
845
- async flush() {
846
- this.scheduleWrite();
847
- await this.writePromise;
848
- }
849
- /**
850
- * Close the destination
851
- */
852
- async close() {
853
- await this.flush();
854
- }
855
- /**
856
- * Set minimum log level
857
- */
858
- setMinLevel(level) {
859
- this.minLevel = LOG_LEVELS[level];
860
- }
861
- /**
862
- * Enable or disable the destination
863
- */
864
- setEnabled(enabled) {
865
- this.config.enabled = enabled;
866
- }
867
- };
868
-
869
- // src/logger/ai/index.ts
870
- var AIFeatures = class {
871
- constructor(dsn, config = {}) {
872
- this.dsn = dsn;
873
- this.config = {
874
- enabled: config.enabled ?? true,
875
- apiKey: config.apiKey || "",
876
- model: config.model || "claude-3-haiku-20240307",
877
- endpoint: config.endpoint || this.parseEndpoint(dsn)
878
- };
879
- }
880
- /**
881
- * Parse DSN to construct AI endpoint
882
- */
883
- parseEndpoint(dsn) {
884
- try {
885
- const url = new URL(dsn);
886
- return `${url.protocol}//${url.host}/api/v1/logs/ai`;
887
- } catch {
888
- return "https://statly.live/api/v1/logs/ai";
889
- }
890
- }
891
- /**
892
- * Explain an error using AI
893
- */
894
- async explainError(error2) {
895
- if (!this.config.enabled) {
896
- return {
897
- summary: "AI features are disabled",
898
- possibleCauses: []
899
- };
900
- }
901
- const errorData = this.normalizeError(error2);
902
- try {
903
- const response = await fetch(`${this.config.endpoint}/explain`, {
904
- method: "POST",
905
- headers: {
906
- "Content-Type": "application/json",
907
- "X-Statly-DSN": this.dsn,
908
- ...this.config.apiKey && { "X-AI-API-Key": this.config.apiKey }
909
- },
910
- body: JSON.stringify({
911
- error: errorData,
912
- model: this.config.model
913
- })
914
- });
915
- if (!response.ok) {
916
- throw new Error(`HTTP ${response.status}`);
917
- }
918
- return await response.json();
919
- } catch (err) {
920
- console.error("[Statly Logger AI] Failed to explain error:", err);
921
- return {
922
- summary: "Failed to get AI explanation",
923
- possibleCauses: []
924
- };
925
- }
926
- }
927
- /**
928
- * Suggest fixes for an error using AI
929
- */
930
- async suggestFix(error2, context) {
931
- if (!this.config.enabled) {
932
- return {
933
- summary: "AI features are disabled",
934
- suggestedFixes: []
935
- };
936
- }
937
- const errorData = this.normalizeError(error2);
938
- try {
939
- const response = await fetch(`${this.config.endpoint}/suggest-fix`, {
940
- method: "POST",
941
- headers: {
942
- "Content-Type": "application/json",
943
- "X-Statly-DSN": this.dsn,
944
- ...this.config.apiKey && { "X-AI-API-Key": this.config.apiKey }
945
- },
946
- body: JSON.stringify({
947
- error: errorData,
948
- context,
949
- model: this.config.model
950
- })
951
- });
952
- if (!response.ok) {
953
- throw new Error(`HTTP ${response.status}`);
954
- }
955
- return await response.json();
956
- } catch (err) {
957
- console.error("[Statly Logger AI] Failed to suggest fix:", err);
958
- return {
959
- summary: "Failed to get AI fix suggestion",
960
- suggestedFixes: []
961
- };
962
- }
963
- }
964
- /**
965
- * Analyze a batch of logs for patterns
966
- */
967
- async analyzePatterns(logs) {
968
- if (!this.config.enabled) {
969
- return {
970
- patterns: [],
971
- summary: "AI features are disabled",
972
- recommendations: []
973
- };
974
- }
975
- try {
976
- const response = await fetch(`${this.config.endpoint}/analyze-patterns`, {
977
- method: "POST",
978
- headers: {
979
- "Content-Type": "application/json",
980
- "X-Statly-DSN": this.dsn,
981
- ...this.config.apiKey && { "X-AI-API-Key": this.config.apiKey }
982
- },
983
- body: JSON.stringify({
984
- logs: logs.slice(0, 1e3),
985
- // Limit to 1000 logs
986
- model: this.config.model
987
- })
988
- });
989
- if (!response.ok) {
990
- throw new Error(`HTTP ${response.status}`);
991
- }
992
- return await response.json();
993
- } catch (err) {
994
- console.error("[Statly Logger AI] Failed to analyze patterns:", err);
995
- return {
996
- patterns: [],
997
- summary: "Failed to analyze patterns",
998
- recommendations: []
999
- };
1000
- }
1001
- }
1002
- /**
1003
- * Normalize error input to a standard format
1004
- */
1005
- normalizeError(error2) {
1006
- if (typeof error2 === "string") {
1007
- return { message: error2 };
1008
- }
1009
- if (error2 instanceof Error) {
1010
- return {
1011
- message: error2.message,
1012
- stack: error2.stack,
1013
- type: error2.name
1014
- };
1015
- }
1016
- return {
1017
- message: error2.message,
1018
- type: error2.level,
1019
- context: error2.context
1020
- };
1021
- }
1022
- /**
1023
- * Set API key for AI features
1024
- */
1025
- setApiKey(apiKey) {
1026
- this.config.apiKey = apiKey;
1027
- }
1028
- /**
1029
- * Enable or disable AI features
1030
- */
1031
- setEnabled(enabled) {
1032
- this.config.enabled = enabled;
1033
- }
1034
- /**
1035
- * Check if AI features are enabled
1036
- */
1037
- isEnabled() {
1038
- return this.config.enabled;
1039
- }
1040
- };
1041
-
1042
- // src/logger/logger.ts
1043
- var SDK_NAME = "@statly/observe";
1044
- var SDK_VERSION = "1.1.0";
1045
- var Logger = class _Logger {
1046
- constructor(config = {}) {
1047
- this.destinations = [];
1048
- this.ai = null;
1049
- this.context = {};
1050
- this.tags = {};
1051
- this.name = config.loggerName || "default";
1052
- this.config = config;
1053
- this.minLevel = LOG_LEVELS[config.level || "debug"];
1054
- this.enabledLevels = this.parseLevelSet(config.levels || "default");
1055
- this.scrubber = new Scrubber(config.scrubbing);
1056
- this.context = config.context || {};
1057
- this.tags = config.tags || {};
1058
- this.sessionId = this.generateId();
1059
- this.initDestinations();
1060
- if (config.dsn) {
1061
- this.ai = new AIFeatures(config.dsn);
1062
- }
1063
- }
1064
- /**
1065
- * Parse level set configuration
1066
- */
1067
- parseLevelSet(levels) {
1068
- if (levels === "default") {
1069
- return new Set(DEFAULT_LEVELS);
1070
- }
1071
- if (levels === "extended") {
1072
- return new Set(EXTENDED_LEVELS);
1073
- }
1074
- return new Set(levels);
1075
- }
1076
- /**
1077
- * Initialize destinations from config
1078
- */
1079
- initDestinations() {
1080
- const { destinations } = this.config;
1081
- if (!destinations || destinations.console?.enabled !== false) {
1082
- this.destinations.push(new ConsoleDestination(destinations?.console));
1083
- }
1084
- if (destinations?.file?.enabled && destinations.file.path) {
1085
- this.destinations.push(new FileDestination(destinations.file));
1086
- }
1087
- if (this.config.dsn && destinations?.observe?.enabled !== false) {
1088
- this.destinations.push(new ObserveDestination(this.config.dsn, destinations?.observe));
1089
- }
1090
- }
1091
- /**
1092
- * Generate a unique ID
1093
- */
1094
- generateId() {
1095
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
1096
- return crypto.randomUUID();
1097
- }
1098
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1099
- const r = Math.random() * 16 | 0;
1100
- const v = c === "x" ? r : r & 3 | 8;
1101
- return v.toString(16);
1102
- });
1103
- }
1104
- /**
1105
- * Check if a level should be logged
1106
- */
1107
- shouldLog(level) {
1108
- if (level === "audit") {
1109
- return true;
1110
- }
1111
- if (LOG_LEVELS[level] < this.minLevel) {
1112
- return false;
1113
- }
1114
- return this.enabledLevels.has(level);
1115
- }
1116
- /**
1117
- * Get source location (if available)
1118
- */
1119
- getSource() {
1120
- try {
1121
- const err = new Error();
1122
- const stack = err.stack?.split("\n");
1123
- if (!stack || stack.length < 5) return void 0;
1124
- for (let i = 3; i < stack.length; i++) {
1125
- const frame = stack[i];
1126
- if (!frame.includes("logger.ts") && !frame.includes("Logger.")) {
1127
- const match = frame.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+)(?::\d+)?\)?/);
1128
- if (match) {
1129
- return {
1130
- function: match[1] || void 0,
1131
- file: match[2],
1132
- line: parseInt(match[3], 10)
1133
- };
1134
- }
1135
- }
1136
- }
1137
- } catch {
1138
- }
1139
- return void 0;
1140
- }
1141
- /**
1142
- * Create a log entry
1143
- */
1144
- createEntry(level, message, context) {
1145
- return {
1146
- level,
1147
- message: this.scrubber.scrubMessage(message),
1148
- timestamp: Date.now(),
1149
- loggerName: this.name,
1150
- context: context ? this.scrubber.scrub({ ...this.context, ...context }) : this.scrubber.scrub(this.context),
1151
- tags: this.tags,
1152
- source: this.getSource(),
1153
- traceId: this.traceId,
1154
- spanId: this.spanId,
1155
- sessionId: this.sessionId,
1156
- environment: this.config.environment,
1157
- release: this.config.release,
1158
- sdkName: SDK_NAME,
1159
- sdkVersion: SDK_VERSION
1160
- };
1161
- }
1162
- /**
1163
- * Write to all destinations
1164
- */
1165
- write(entry) {
1166
- for (const dest of this.destinations) {
1167
- try {
1168
- dest.write(entry);
1169
- } catch (error2) {
1170
- console.error(`[Statly Logger] Failed to write to ${dest.name}:`, error2);
1171
- }
1172
- }
1173
- }
1174
- // ==================== Public Logging Methods ====================
1175
- /**
1176
- * Log a trace message
1177
- */
1178
- trace(message, context) {
1179
- if (!this.shouldLog("trace")) return;
1180
- this.write(this.createEntry("trace", message, context));
1181
- }
1182
- /**
1183
- * Log a debug message
1184
- */
1185
- debug(message, context) {
1186
- if (!this.shouldLog("debug")) return;
1187
- this.write(this.createEntry("debug", message, context));
1188
- }
1189
- /**
1190
- * Log an info message
1191
- */
1192
- info(message, context) {
1193
- if (!this.shouldLog("info")) return;
1194
- this.write(this.createEntry("info", message, context));
1195
- }
1196
- /**
1197
- * Log a warning message
1198
- */
1199
- warn(message, context) {
1200
- if (!this.shouldLog("warn")) return;
1201
- this.write(this.createEntry("warn", message, context));
1202
- }
1203
- error(messageOrError, context) {
1204
- if (!this.shouldLog("error")) return;
1205
- if (messageOrError instanceof Error) {
1206
- const entry = this.createEntry("error", messageOrError.message, {
1207
- ...context,
1208
- stack: messageOrError.stack,
1209
- errorType: messageOrError.name
1210
- });
1211
- this.write(entry);
1212
- } else {
1213
- this.write(this.createEntry("error", messageOrError, context));
1214
- }
1215
- }
1216
- fatal(messageOrError, context) {
1217
- if (!this.shouldLog("fatal")) return;
1218
- if (messageOrError instanceof Error) {
1219
- const entry = this.createEntry("fatal", messageOrError.message, {
1220
- ...context,
1221
- stack: messageOrError.stack,
1222
- errorType: messageOrError.name
1223
- });
1224
- this.write(entry);
1225
- } else {
1226
- this.write(this.createEntry("fatal", messageOrError, context));
1227
- }
1228
- }
1229
- /**
1230
- * Log an audit message (always logged, never sampled)
1231
- */
1232
- audit(message, context) {
1233
- this.write(this.createEntry("audit", message, context));
1234
- }
1235
- /**
1236
- * Log at a specific level
1237
- */
1238
- log(level, message, context) {
1239
- if (!this.shouldLog(level)) return;
1240
- this.write(this.createEntry(level, message, context));
1241
- }
1242
- // ==================== Context & Tags ====================
1243
- /**
1244
- * Set persistent context
1245
- */
1246
- setContext(context) {
1247
- this.context = { ...this.context, ...context };
1248
- }
1249
- /**
1250
- * Clear context
1251
- */
1252
- clearContext() {
1253
- this.context = {};
1254
- }
1255
- /**
1256
- * Set a tag
1257
- */
1258
- setTag(key, value) {
1259
- this.tags[key] = value;
1260
- }
1261
- /**
1262
- * Set multiple tags
1263
- */
1264
- setTags(tags) {
1265
- this.tags = { ...this.tags, ...tags };
1266
- }
1267
- /**
1268
- * Clear tags
1269
- */
1270
- clearTags() {
1271
- this.tags = {};
1272
- }
1273
- // ==================== Tracing ====================
1274
- /**
1275
- * Set trace ID for distributed tracing
1276
- */
1277
- setTraceId(traceId) {
1278
- this.traceId = traceId;
1279
- }
1280
- /**
1281
- * Set span ID
1282
- */
1283
- setSpanId(spanId) {
1284
- this.spanId = spanId;
1285
- }
1286
- /**
1287
- * Clear tracing context
1288
- */
1289
- clearTracing() {
1290
- this.traceId = void 0;
1291
- this.spanId = void 0;
1292
- }
1293
- // ==================== Child Loggers ====================
1294
- /**
1295
- * Create a child logger with additional context
1296
- */
1297
- child(options = {}) {
1298
- const childConfig = {
1299
- ...this.config,
1300
- loggerName: options.name || `${this.name}.child`,
1301
- context: { ...this.context, ...options.context },
1302
- tags: { ...this.tags, ...options.tags }
1303
- };
1304
- const child = new _Logger(childConfig);
1305
- child.traceId = this.traceId;
1306
- child.spanId = this.spanId;
1307
- child.sessionId = this.sessionId;
1308
- return child;
1309
- }
1310
- // ==================== AI Features ====================
1311
- /**
1312
- * Explain an error using AI
1313
- */
1314
- async explainError(error2) {
1315
- if (!this.ai) {
1316
- return {
1317
- summary: "AI features not available (no DSN configured)",
1318
- possibleCauses: []
1319
- };
1320
- }
1321
- return this.ai.explainError(error2);
1322
- }
1323
- /**
1324
- * Suggest fixes for an error using AI
1325
- */
1326
- async suggestFix(error2, context) {
1327
- if (!this.ai) {
1328
- return {
1329
- summary: "AI features not available (no DSN configured)",
1330
- suggestedFixes: []
1331
- };
1332
- }
1333
- return this.ai.suggestFix(error2, context);
1334
- }
1335
- /**
1336
- * Configure AI features
1337
- */
1338
- configureAI(config) {
1339
- if (this.ai) {
1340
- if (config.apiKey) this.ai.setApiKey(config.apiKey);
1341
- if (config.enabled !== void 0) this.ai.setEnabled(config.enabled);
1342
- }
1343
- }
1344
- // ==================== Destination Management ====================
1345
- /**
1346
- * Add a custom destination
1347
- */
1348
- addDestination(destination) {
1349
- this.destinations.push(destination);
1350
- }
1351
- /**
1352
- * Remove a destination by name
1353
- */
1354
- removeDestination(name) {
1355
- this.destinations = this.destinations.filter((d) => d.name !== name);
1356
- }
1357
- /**
1358
- * Get all destinations
1359
- */
1360
- getDestinations() {
1361
- return [...this.destinations];
1362
- }
1363
- // ==================== Level Configuration ====================
1364
- /**
1365
- * Set minimum log level
1366
- */
1367
- setLevel(level) {
1368
- this.minLevel = LOG_LEVELS[level];
1369
- }
1370
- /**
1371
- * Get current minimum level
1372
- */
1373
- getLevel() {
1374
- const entries = Object.entries(LOG_LEVELS);
1375
- const entry = entries.find(([, value]) => value === this.minLevel);
1376
- return entry ? entry[0] : "debug";
1377
- }
1378
- /**
1379
- * Check if a level is enabled
1380
- */
1381
- isLevelEnabled(level) {
1382
- return this.shouldLog(level);
1383
- }
1384
- // ==================== Lifecycle ====================
1385
- /**
1386
- * Flush all destinations
1387
- */
1388
- async flush() {
1389
- await Promise.all(
1390
- this.destinations.filter((d) => d.flush).map((d) => d.flush())
1391
- );
1392
- }
1393
- /**
1394
- * Close the logger and all destinations
1395
- */
1396
- async close() {
1397
- await Promise.all(
1398
- this.destinations.filter((d) => d.close).map((d) => d.close())
1399
- );
1400
- }
1401
- /**
1402
- * Get logger name
1403
- */
1404
- getName() {
1405
- return this.name;
1406
- }
1407
- /**
1408
- * Get session ID
1409
- */
1410
- getSessionId() {
1411
- return this.sessionId;
1412
- }
1413
- };
1414
-
1415
- // src/logger/index.ts
1416
- var defaultLogger = null;
1417
- function getDefaultLogger() {
1418
- if (!defaultLogger) {
1419
- defaultLogger = new Logger();
1420
- }
1421
- return defaultLogger;
1422
- }
1423
- function setDefaultLogger(logger) {
1424
- defaultLogger = logger;
1425
- }
1426
- function trace(message, context) {
1427
- getDefaultLogger().trace(message, context);
1428
- }
1429
- function debug(message, context) {
1430
- getDefaultLogger().debug(message, context);
1431
- }
1432
- function info(message, context) {
1433
- getDefaultLogger().info(message, context);
1434
- }
1435
- function warn(message, context) {
1436
- getDefaultLogger().warn(message, context);
1437
- }
1438
- function error(messageOrError, context) {
1439
- if (messageOrError instanceof Error) {
1440
- getDefaultLogger().error(messageOrError, context);
1441
- } else {
1442
- getDefaultLogger().error(messageOrError, context);
1443
- }
1444
- }
1445
- function fatal(messageOrError, context) {
1446
- if (messageOrError instanceof Error) {
1447
- getDefaultLogger().fatal(messageOrError, context);
1448
- } else {
1449
- getDefaultLogger().fatal(messageOrError, context);
1450
- }
1451
- }
1452
- function audit(message, context) {
1453
- getDefaultLogger().audit(message, context);
1454
- }
1455
- // Annotate the CommonJS export names for ESM import in node:
1456
- 0 && (module.exports = {
1
+ import {
1457
2
  AIFeatures,
1458
3
  ConsoleDestination,
1459
4
  DEFAULT_LEVELS,
@@ -1480,4 +25,32 @@ function audit(message, context) {
1480
25
  setDefaultLogger,
1481
26
  trace,
1482
27
  warn
1483
- });
28
+ } from "../chunk-RUEXBTHM.js";
29
+ export {
30
+ AIFeatures,
31
+ ConsoleDestination,
32
+ DEFAULT_LEVELS,
33
+ EXTENDED_LEVELS,
34
+ FileDestination,
35
+ LOG_LEVELS,
36
+ Logger,
37
+ ObserveDestination,
38
+ REDACTED,
39
+ SCRUB_PATTERNS,
40
+ SENSITIVE_KEYS,
41
+ Scrubber,
42
+ audit,
43
+ debug,
44
+ error,
45
+ fatal,
46
+ formatJson,
47
+ formatJsonPretty,
48
+ formatPretty,
49
+ getConsoleMethod,
50
+ getDefaultLogger,
51
+ info,
52
+ isSensitiveKey,
53
+ setDefaultLogger,
54
+ trace,
55
+ warn
56
+ };