@statly/observe 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.
@@ -0,0 +1,861 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/integrations/express.ts
21
+ var express_exports = {};
22
+ __export(express_exports, {
23
+ expressErrorHandler: () => expressErrorHandler,
24
+ requestHandler: () => requestHandler
25
+ });
26
+ module.exports = __toCommonJS(express_exports);
27
+
28
+ // src/transport.ts
29
+ var Transport = class {
30
+ constructor(options) {
31
+ this.queue = [];
32
+ this.isSending = false;
33
+ this.maxQueueSize = 100;
34
+ this.flushInterval = 5e3;
35
+ this.dsn = options.dsn;
36
+ this.debug = options.debug ?? false;
37
+ this.endpoint = this.parseEndpoint(options.dsn);
38
+ this.startFlushTimer();
39
+ }
40
+ parseEndpoint(dsn) {
41
+ try {
42
+ const url = new URL(dsn);
43
+ return `${url.protocol}//${url.host}/api/v1/observe/ingest`;
44
+ } catch {
45
+ return `https://statly.live/api/v1/observe/ingest`;
46
+ }
47
+ }
48
+ startFlushTimer() {
49
+ if (typeof window !== "undefined") {
50
+ this.flushTimer = setInterval(() => {
51
+ this.flush();
52
+ }, this.flushInterval);
53
+ }
54
+ }
55
+ /**
56
+ * Add an event to the queue
57
+ */
58
+ enqueue(event) {
59
+ if (this.queue.length >= this.maxQueueSize) {
60
+ this.queue.shift();
61
+ if (this.debug) {
62
+ console.warn("[Statly] Event queue full, dropping oldest event");
63
+ }
64
+ }
65
+ this.queue.push(event);
66
+ if (this.queue.length >= 10) {
67
+ this.flush();
68
+ }
69
+ }
70
+ /**
71
+ * Send a single event immediately
72
+ */
73
+ async send(event) {
74
+ return this.sendBatch([event]);
75
+ }
76
+ /**
77
+ * Flush all queued events
78
+ */
79
+ async flush() {
80
+ if (this.isSending || this.queue.length === 0) {
81
+ return;
82
+ }
83
+ this.isSending = true;
84
+ const events = [...this.queue];
85
+ this.queue = [];
86
+ try {
87
+ await this.sendBatch(events);
88
+ } catch (error) {
89
+ this.queue = [...events, ...this.queue].slice(0, this.maxQueueSize);
90
+ if (this.debug) {
91
+ console.error("[Statly] Failed to send events:", error);
92
+ }
93
+ } finally {
94
+ this.isSending = false;
95
+ }
96
+ }
97
+ /**
98
+ * Send a batch of events
99
+ */
100
+ async sendBatch(events) {
101
+ if (events.length === 0) {
102
+ return { success: true };
103
+ }
104
+ const payload = events.length === 1 ? events[0] : { events };
105
+ try {
106
+ const response = await fetch(this.endpoint, {
107
+ method: "POST",
108
+ headers: {
109
+ "Content-Type": "application/json",
110
+ "X-Statly-DSN": this.dsn
111
+ },
112
+ body: JSON.stringify(payload),
113
+ // Use keepalive for better reliability during page unload
114
+ keepalive: true
115
+ });
116
+ if (!response.ok) {
117
+ const errorText = await response.text().catch(() => "Unknown error");
118
+ if (this.debug) {
119
+ console.error("[Statly] API error:", response.status, errorText);
120
+ }
121
+ return {
122
+ success: false,
123
+ status: response.status,
124
+ error: errorText
125
+ };
126
+ }
127
+ if (this.debug) {
128
+ console.log(`[Statly] Sent ${events.length} event(s)`);
129
+ }
130
+ return { success: true, status: response.status };
131
+ } catch (error) {
132
+ if (this.debug) {
133
+ console.error("[Statly] Network error:", error);
134
+ }
135
+ return {
136
+ success: false,
137
+ error: error instanceof Error ? error.message : "Network error"
138
+ };
139
+ }
140
+ }
141
+ /**
142
+ * Clean up resources
143
+ */
144
+ destroy() {
145
+ if (this.flushTimer) {
146
+ clearInterval(this.flushTimer);
147
+ }
148
+ this.flush();
149
+ }
150
+ };
151
+
152
+ // src/breadcrumbs.ts
153
+ var BreadcrumbManager = class {
154
+ constructor(maxBreadcrumbs = 100) {
155
+ this.breadcrumbs = [];
156
+ this.maxBreadcrumbs = maxBreadcrumbs;
157
+ }
158
+ /**
159
+ * Add a breadcrumb
160
+ */
161
+ add(breadcrumb) {
162
+ const crumb = {
163
+ timestamp: Date.now(),
164
+ ...breadcrumb
165
+ };
166
+ this.breadcrumbs.push(crumb);
167
+ if (this.breadcrumbs.length > this.maxBreadcrumbs) {
168
+ this.breadcrumbs = this.breadcrumbs.slice(-this.maxBreadcrumbs);
169
+ }
170
+ }
171
+ /**
172
+ * Get all breadcrumbs
173
+ */
174
+ getAll() {
175
+ return [...this.breadcrumbs];
176
+ }
177
+ /**
178
+ * Clear all breadcrumbs
179
+ */
180
+ clear() {
181
+ this.breadcrumbs = [];
182
+ }
183
+ /**
184
+ * Set maximum breadcrumbs to keep
185
+ */
186
+ setMaxBreadcrumbs(max) {
187
+ this.maxBreadcrumbs = max;
188
+ if (this.breadcrumbs.length > max) {
189
+ this.breadcrumbs = this.breadcrumbs.slice(-max);
190
+ }
191
+ }
192
+ };
193
+
194
+ // src/integrations/global-handlers.ts
195
+ var GlobalHandlers = class {
196
+ constructor(options = {}) {
197
+ this.originalOnError = null;
198
+ this.originalOnUnhandledRejection = null;
199
+ this.errorCallback = null;
200
+ this.handleUnhandledRejection = (event) => {
201
+ if (!this.errorCallback) {
202
+ return;
203
+ }
204
+ let error;
205
+ if (event.reason instanceof Error) {
206
+ error = event.reason;
207
+ } else if (typeof event.reason === "string") {
208
+ error = new Error(event.reason);
209
+ } else {
210
+ error = new Error("Unhandled Promise Rejection");
211
+ error.reason = event.reason;
212
+ }
213
+ this.errorCallback(error, {
214
+ mechanism: { type: "onunhandledrejection", handled: false }
215
+ });
216
+ };
217
+ this.options = {
218
+ onerror: options.onerror !== false,
219
+ onunhandledrejection: options.onunhandledrejection !== false
220
+ };
221
+ }
222
+ /**
223
+ * Install global error handlers
224
+ */
225
+ install(callback) {
226
+ this.errorCallback = callback;
227
+ if (typeof window === "undefined") {
228
+ return;
229
+ }
230
+ if (this.options.onerror) {
231
+ this.installOnError();
232
+ }
233
+ if (this.options.onunhandledrejection) {
234
+ this.installOnUnhandledRejection();
235
+ }
236
+ }
237
+ /**
238
+ * Uninstall global error handlers
239
+ */
240
+ uninstall() {
241
+ if (typeof window === "undefined") {
242
+ return;
243
+ }
244
+ if (this.originalOnError !== null) {
245
+ window.onerror = this.originalOnError;
246
+ this.originalOnError = null;
247
+ }
248
+ if (this.originalOnUnhandledRejection !== null) {
249
+ window.removeEventListener("unhandledrejection", this.handleUnhandledRejection);
250
+ this.originalOnUnhandledRejection = null;
251
+ }
252
+ this.errorCallback = null;
253
+ }
254
+ installOnError() {
255
+ this.originalOnError = window.onerror;
256
+ window.onerror = (message, source, lineno, colno, error) => {
257
+ if (this.originalOnError) {
258
+ this.originalOnError.call(window, message, source, lineno, colno, error);
259
+ }
260
+ if (this.errorCallback) {
261
+ const errorObj = error || new Error(String(message));
262
+ if (!error && source) {
263
+ errorObj.filename = source;
264
+ errorObj.lineno = lineno;
265
+ errorObj.colno = colno;
266
+ }
267
+ this.errorCallback(errorObj, {
268
+ mechanism: { type: "onerror", handled: false },
269
+ source,
270
+ lineno,
271
+ colno
272
+ });
273
+ }
274
+ return false;
275
+ };
276
+ }
277
+ installOnUnhandledRejection() {
278
+ this.originalOnUnhandledRejection = this.handleUnhandledRejection.bind(this);
279
+ window.addEventListener("unhandledrejection", this.handleUnhandledRejection);
280
+ }
281
+ };
282
+
283
+ // src/integrations/console.ts
284
+ var ConsoleIntegration = class {
285
+ constructor() {
286
+ this.originalMethods = {};
287
+ this.callback = null;
288
+ this.levels = ["debug", "info", "warn", "error", "log"];
289
+ }
290
+ /**
291
+ * Install console breadcrumb tracking
292
+ */
293
+ install(callback, levels) {
294
+ this.callback = callback;
295
+ if (levels) {
296
+ this.levels = levels;
297
+ }
298
+ if (typeof console === "undefined") {
299
+ return;
300
+ }
301
+ for (const level of this.levels) {
302
+ this.wrapConsoleMethod(level);
303
+ }
304
+ }
305
+ /**
306
+ * Uninstall console breadcrumb tracking
307
+ */
308
+ uninstall() {
309
+ if (typeof console === "undefined") {
310
+ return;
311
+ }
312
+ for (const level of this.levels) {
313
+ if (this.originalMethods[level]) {
314
+ console[level] = this.originalMethods[level];
315
+ delete this.originalMethods[level];
316
+ }
317
+ }
318
+ this.callback = null;
319
+ }
320
+ wrapConsoleMethod(level) {
321
+ const originalMethod = console[level];
322
+ if (!originalMethod) {
323
+ return;
324
+ }
325
+ this.originalMethods[level] = originalMethod;
326
+ const self = this;
327
+ console[level] = function(...args) {
328
+ if (self.callback) {
329
+ self.callback({
330
+ category: "console",
331
+ message: self.formatArgs(args),
332
+ level: self.mapLevel(level),
333
+ data: args.length > 1 ? { arguments: args } : void 0
334
+ });
335
+ }
336
+ originalMethod.apply(console, args);
337
+ };
338
+ }
339
+ formatArgs(args) {
340
+ return args.map((arg) => {
341
+ if (typeof arg === "string") {
342
+ return arg;
343
+ }
344
+ if (arg instanceof Error) {
345
+ return arg.message;
346
+ }
347
+ try {
348
+ return JSON.stringify(arg);
349
+ } catch {
350
+ return String(arg);
351
+ }
352
+ }).join(" ");
353
+ }
354
+ mapLevel(consoleLevel) {
355
+ switch (consoleLevel) {
356
+ case "debug":
357
+ return "debug";
358
+ case "info":
359
+ case "log":
360
+ return "info";
361
+ case "warn":
362
+ return "warning";
363
+ case "error":
364
+ return "error";
365
+ default:
366
+ return "info";
367
+ }
368
+ }
369
+ };
370
+
371
+ // src/client.ts
372
+ var SDK_NAME = "@statly/observe-sdk";
373
+ var SDK_VERSION = "0.1.0";
374
+ var StatlyClient = class {
375
+ constructor(options) {
376
+ this.user = null;
377
+ this.initialized = false;
378
+ this.options = this.mergeOptions(options);
379
+ this.transport = new Transport({
380
+ dsn: this.options.dsn,
381
+ debug: this.options.debug
382
+ });
383
+ this.breadcrumbs = new BreadcrumbManager(this.options.maxBreadcrumbs);
384
+ this.globalHandlers = new GlobalHandlers();
385
+ this.consoleIntegration = new ConsoleIntegration();
386
+ }
387
+ mergeOptions(options) {
388
+ return {
389
+ dsn: options.dsn,
390
+ release: options.release ?? "",
391
+ environment: options.environment ?? this.detectEnvironment(),
392
+ debug: options.debug ?? false,
393
+ sampleRate: options.sampleRate ?? 1,
394
+ maxBreadcrumbs: options.maxBreadcrumbs ?? 100,
395
+ autoCapture: options.autoCapture !== false,
396
+ captureConsole: options.captureConsole !== false,
397
+ captureNetwork: options.captureNetwork ?? false,
398
+ tags: options.tags ?? {},
399
+ beforeSend: options.beforeSend ?? ((e) => e)
400
+ };
401
+ }
402
+ detectEnvironment() {
403
+ if (typeof window !== "undefined") {
404
+ if (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1") {
405
+ return "development";
406
+ }
407
+ if (window.location.hostname.includes("staging") || window.location.hostname.includes("stage")) {
408
+ return "staging";
409
+ }
410
+ }
411
+ return "production";
412
+ }
413
+ /**
414
+ * Initialize the SDK
415
+ */
416
+ init() {
417
+ if (this.initialized) {
418
+ if (this.options.debug) {
419
+ console.warn("[Statly] SDK already initialized");
420
+ }
421
+ return;
422
+ }
423
+ this.initialized = true;
424
+ if (this.options.autoCapture) {
425
+ this.globalHandlers.install((error, context) => {
426
+ this.captureError(error, context);
427
+ });
428
+ }
429
+ if (this.options.captureConsole) {
430
+ this.consoleIntegration.install((breadcrumb) => {
431
+ this.breadcrumbs.add(breadcrumb);
432
+ });
433
+ }
434
+ this.addBreadcrumb({
435
+ category: "navigation",
436
+ message: "SDK initialized",
437
+ level: "info"
438
+ });
439
+ if (this.options.debug) {
440
+ console.log("[Statly] SDK initialized", {
441
+ environment: this.options.environment,
442
+ release: this.options.release
443
+ });
444
+ }
445
+ }
446
+ /**
447
+ * Capture an exception/error
448
+ */
449
+ captureException(error, context) {
450
+ let errorObj;
451
+ if (error instanceof Error) {
452
+ errorObj = error;
453
+ } else if (typeof error === "string") {
454
+ errorObj = new Error(error);
455
+ } else {
456
+ errorObj = new Error("Unknown error");
457
+ errorObj.originalError = error;
458
+ }
459
+ return this.captureError(errorObj, context);
460
+ }
461
+ /**
462
+ * Capture a message
463
+ */
464
+ captureMessage(message, level = "info") {
465
+ const event = this.buildEvent({
466
+ message,
467
+ level
468
+ });
469
+ return this.sendEvent(event);
470
+ }
471
+ /**
472
+ * Internal method to capture an error
473
+ */
474
+ captureError(error, context) {
475
+ if (Math.random() > this.options.sampleRate) {
476
+ return "";
477
+ }
478
+ const event = this.buildEvent({
479
+ message: error.message,
480
+ level: "error",
481
+ stack: error.stack,
482
+ exception: {
483
+ type: error.name,
484
+ value: error.message,
485
+ stacktrace: this.parseStackTrace(error.stack)
486
+ },
487
+ extra: context
488
+ });
489
+ return this.sendEvent(event);
490
+ }
491
+ /**
492
+ * Build a complete event from partial data
493
+ */
494
+ buildEvent(partial) {
495
+ const event = {
496
+ message: partial.message || "Unknown error",
497
+ timestamp: Date.now(),
498
+ level: partial.level || "error",
499
+ environment: this.options.environment,
500
+ release: this.options.release || void 0,
501
+ url: typeof window !== "undefined" ? window.location.href : void 0,
502
+ user: this.user || void 0,
503
+ tags: { ...this.options.tags, ...partial.tags },
504
+ extra: partial.extra,
505
+ breadcrumbs: this.breadcrumbs.getAll(),
506
+ browser: this.getBrowserInfo(),
507
+ os: this.getOSInfo(),
508
+ sdk: {
509
+ name: SDK_NAME,
510
+ version: SDK_VERSION
511
+ },
512
+ ...partial
513
+ };
514
+ return event;
515
+ }
516
+ /**
517
+ * Parse a stack trace string into structured frames
518
+ */
519
+ parseStackTrace(stack) {
520
+ if (!stack) {
521
+ return void 0;
522
+ }
523
+ const frames = [];
524
+ const lines = stack.split("\n");
525
+ for (const line of lines) {
526
+ const chromeMatch = line.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
527
+ if (chromeMatch) {
528
+ frames.push({
529
+ function: chromeMatch[1] || "<anonymous>",
530
+ filename: chromeMatch[2],
531
+ lineno: parseInt(chromeMatch[3], 10),
532
+ colno: parseInt(chromeMatch[4], 10)
533
+ });
534
+ continue;
535
+ }
536
+ const firefoxMatch = line.match(/^(.+?)@(.+?):(\d+):(\d+)$/);
537
+ if (firefoxMatch) {
538
+ frames.push({
539
+ function: firefoxMatch[1] || "<anonymous>",
540
+ filename: firefoxMatch[2],
541
+ lineno: parseInt(firefoxMatch[3], 10),
542
+ colno: parseInt(firefoxMatch[4], 10)
543
+ });
544
+ }
545
+ }
546
+ return frames.length > 0 ? { frames } : void 0;
547
+ }
548
+ /**
549
+ * Send an event to the server
550
+ */
551
+ sendEvent(event) {
552
+ const processed = this.options.beforeSend(event);
553
+ if (!processed) {
554
+ if (this.options.debug) {
555
+ console.log("[Statly] Event dropped by beforeSend");
556
+ }
557
+ return "";
558
+ }
559
+ const eventId = this.generateEventId();
560
+ this.breadcrumbs.add({
561
+ category: "statly",
562
+ message: `Captured ${event.level}: ${event.message.slice(0, 50)}`,
563
+ level: "info"
564
+ });
565
+ this.transport.enqueue(processed);
566
+ if (this.options.debug) {
567
+ console.log("[Statly] Event captured:", eventId, event.message);
568
+ }
569
+ return eventId;
570
+ }
571
+ generateEventId() {
572
+ return crypto.randomUUID?.() || "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
573
+ const r = Math.random() * 16 | 0;
574
+ const v = c === "x" ? r : r & 3 | 8;
575
+ return v.toString(16);
576
+ });
577
+ }
578
+ /**
579
+ * Set user context
580
+ */
581
+ setUser(user) {
582
+ this.user = user;
583
+ if (this.options.debug && user) {
584
+ console.log("[Statly] User set:", user.id || user.email);
585
+ }
586
+ }
587
+ /**
588
+ * Set a single tag
589
+ */
590
+ setTag(key, value) {
591
+ this.options.tags[key] = value;
592
+ }
593
+ /**
594
+ * Set multiple tags
595
+ */
596
+ setTags(tags) {
597
+ Object.assign(this.options.tags, tags);
598
+ }
599
+ /**
600
+ * Add a breadcrumb
601
+ */
602
+ addBreadcrumb(breadcrumb) {
603
+ this.breadcrumbs.add(breadcrumb);
604
+ }
605
+ /**
606
+ * Get browser info
607
+ */
608
+ getBrowserInfo() {
609
+ if (typeof navigator === "undefined") {
610
+ return void 0;
611
+ }
612
+ const ua = navigator.userAgent;
613
+ let name = "Unknown";
614
+ let version = "";
615
+ if (ua.includes("Firefox/")) {
616
+ name = "Firefox";
617
+ version = ua.split("Firefox/")[1]?.split(" ")[0] || "";
618
+ } else if (ua.includes("Chrome/")) {
619
+ name = "Chrome";
620
+ version = ua.split("Chrome/")[1]?.split(" ")[0] || "";
621
+ } else if (ua.includes("Safari/") && !ua.includes("Chrome")) {
622
+ name = "Safari";
623
+ version = ua.split("Version/")[1]?.split(" ")[0] || "";
624
+ } else if (ua.includes("Edge/") || ua.includes("Edg/")) {
625
+ name = "Edge";
626
+ version = ua.split(/Edg?e?\//)[1]?.split(" ")[0] || "";
627
+ }
628
+ return { name, version };
629
+ }
630
+ /**
631
+ * Get OS info
632
+ */
633
+ getOSInfo() {
634
+ if (typeof navigator === "undefined") {
635
+ return void 0;
636
+ }
637
+ const ua = navigator.userAgent;
638
+ let name = "Unknown";
639
+ let version = "";
640
+ if (ua.includes("Windows")) {
641
+ name = "Windows";
642
+ const match = ua.match(/Windows NT (\d+\.\d+)/);
643
+ if (match) version = match[1];
644
+ } else if (ua.includes("Mac OS X")) {
645
+ name = "macOS";
646
+ const match = ua.match(/Mac OS X (\d+[._]\d+)/);
647
+ if (match) version = match[1].replace("_", ".");
648
+ } else if (ua.includes("Linux")) {
649
+ name = "Linux";
650
+ } else if (ua.includes("Android")) {
651
+ name = "Android";
652
+ const match = ua.match(/Android (\d+\.\d+)/);
653
+ if (match) version = match[1];
654
+ } else if (ua.includes("iOS") || ua.includes("iPhone") || ua.includes("iPad")) {
655
+ name = "iOS";
656
+ const match = ua.match(/OS (\d+_\d+)/);
657
+ if (match) version = match[1].replace("_", ".");
658
+ }
659
+ return { name, version };
660
+ }
661
+ /**
662
+ * Flush pending events and clean up
663
+ */
664
+ async close() {
665
+ this.globalHandlers.uninstall();
666
+ this.consoleIntegration.uninstall();
667
+ await this.transport.flush();
668
+ this.transport.destroy();
669
+ this.initialized = false;
670
+ }
671
+ /**
672
+ * Force flush pending events
673
+ */
674
+ async flush() {
675
+ await this.transport.flush();
676
+ }
677
+ };
678
+
679
+ // src/index.ts
680
+ var client = null;
681
+ function init(options) {
682
+ if (client) {
683
+ console.warn("[Statly] SDK already initialized. Call close() first to reinitialize.");
684
+ return;
685
+ }
686
+ client = new StatlyClient(options);
687
+ client.init();
688
+ }
689
+ function captureException(error, context) {
690
+ if (!client) {
691
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
692
+ return "";
693
+ }
694
+ return client.captureException(error, context);
695
+ }
696
+ function captureMessage(message, level = "info") {
697
+ if (!client) {
698
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
699
+ return "";
700
+ }
701
+ return client.captureMessage(message, level);
702
+ }
703
+ function setUser(user) {
704
+ if (!client) {
705
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
706
+ return;
707
+ }
708
+ client.setUser(user);
709
+ }
710
+ function setTag(key, value) {
711
+ if (!client) {
712
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
713
+ return;
714
+ }
715
+ client.setTag(key, value);
716
+ }
717
+ function setTags(tags) {
718
+ if (!client) {
719
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
720
+ return;
721
+ }
722
+ client.setTags(tags);
723
+ }
724
+ function addBreadcrumb(breadcrumb) {
725
+ if (!client) {
726
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
727
+ return;
728
+ }
729
+ client.addBreadcrumb(breadcrumb);
730
+ }
731
+ async function flush() {
732
+ if (!client) {
733
+ return;
734
+ }
735
+ await client.flush();
736
+ }
737
+ async function close() {
738
+ if (!client) {
739
+ return;
740
+ }
741
+ await client.close();
742
+ client = null;
743
+ }
744
+ function getClient() {
745
+ return client;
746
+ }
747
+ var Statly = {
748
+ init,
749
+ captureException,
750
+ captureMessage,
751
+ setUser,
752
+ setTag,
753
+ setTags,
754
+ addBreadcrumb,
755
+ flush,
756
+ close,
757
+ getClient
758
+ };
759
+
760
+ // src/integrations/express.ts
761
+ function requestHandler() {
762
+ return (req, res, next) => {
763
+ req.statlyContext = {
764
+ transactionName: `${req.method} ${req.path || req.url}`,
765
+ startTime: Date.now()
766
+ };
767
+ Statly.addBreadcrumb({
768
+ category: "http",
769
+ message: `${req.method} ${req.originalUrl || req.url}`,
770
+ level: "info",
771
+ data: {
772
+ method: req.method,
773
+ url: req.originalUrl || req.url
774
+ }
775
+ });
776
+ if (req.user) {
777
+ Statly.setUser({
778
+ id: req.user.id?.toString(),
779
+ email: req.user.email?.toString()
780
+ });
781
+ }
782
+ res.on("finish", () => {
783
+ const duration = req.statlyContext?.startTime ? Date.now() - req.statlyContext.startTime : void 0;
784
+ Statly.addBreadcrumb({
785
+ category: "http",
786
+ message: `Response ${res.statusCode}`,
787
+ level: res.statusCode >= 400 ? "error" : "info",
788
+ data: {
789
+ statusCode: res.statusCode,
790
+ duration
791
+ }
792
+ });
793
+ });
794
+ next();
795
+ };
796
+ }
797
+ function expressErrorHandler(options = {}) {
798
+ return (err, req, res, next) => {
799
+ const error = err instanceof Error ? err : new Error(String(err));
800
+ if (options.shouldHandleError && !options.shouldHandleError(error)) {
801
+ return next(err);
802
+ }
803
+ const context = {
804
+ request: {
805
+ method: req.method,
806
+ url: req.originalUrl || req.url,
807
+ headers: sanitizeHeaders(req.headers),
808
+ query: req.query,
809
+ data: sanitizeBody(req.body)
810
+ }
811
+ };
812
+ if (req.ip) {
813
+ context.ip = req.ip;
814
+ }
815
+ if (req.user) {
816
+ Statly.setUser({
817
+ id: req.user.id?.toString(),
818
+ email: req.user.email?.toString()
819
+ });
820
+ }
821
+ if (req.statlyContext?.transactionName) {
822
+ Statly.setTag("transaction", req.statlyContext.transactionName);
823
+ }
824
+ Statly.captureException(error, context);
825
+ next(err);
826
+ };
827
+ }
828
+ function sanitizeHeaders(headers) {
829
+ const sensitiveHeaders = ["authorization", "cookie", "x-api-key", "x-auth-token"];
830
+ const sanitized = {};
831
+ for (const [key, value] of Object.entries(headers)) {
832
+ if (sensitiveHeaders.includes(key.toLowerCase())) {
833
+ sanitized[key] = "[Filtered]";
834
+ } else {
835
+ sanitized[key] = value;
836
+ }
837
+ }
838
+ return sanitized;
839
+ }
840
+ function sanitizeBody(body) {
841
+ if (!body || typeof body !== "object") {
842
+ return body;
843
+ }
844
+ const sensitiveFields = ["password", "secret", "token", "apiKey", "api_key", "credit_card", "creditCard", "ssn"];
845
+ const sanitized = {};
846
+ for (const [key, value] of Object.entries(body)) {
847
+ if (sensitiveFields.some((field) => key.toLowerCase().includes(field.toLowerCase()))) {
848
+ sanitized[key] = "[Filtered]";
849
+ } else if (typeof value === "object" && value !== null) {
850
+ sanitized[key] = sanitizeBody(value);
851
+ } else {
852
+ sanitized[key] = value;
853
+ }
854
+ }
855
+ return sanitized;
856
+ }
857
+ // Annotate the CommonJS export names for ESM import in node:
858
+ 0 && (module.exports = {
859
+ expressErrorHandler,
860
+ requestHandler
861
+ });