@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.
package/dist/index.js ADDED
@@ -0,0 +1,1138 @@
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/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Statly: () => Statly,
24
+ StatlyClient: () => StatlyClient,
25
+ addBreadcrumb: () => addBreadcrumb,
26
+ captureException: () => captureException,
27
+ captureMessage: () => captureMessage,
28
+ captureNextJsError: () => captureNextJsError,
29
+ close: () => close,
30
+ createRequestCapture: () => createRequestCapture,
31
+ expressErrorHandler: () => expressErrorHandler,
32
+ flush: () => flush,
33
+ getClient: () => getClient,
34
+ init: () => init,
35
+ requestHandler: () => requestHandler,
36
+ setTag: () => setTag,
37
+ setTags: () => setTags,
38
+ setUser: () => setUser,
39
+ statlyFastifyPlugin: () => statlyFastifyPlugin,
40
+ statlyPlugin: () => statlyPlugin,
41
+ withStatly: () => withStatly,
42
+ withStatlyGetServerSideProps: () => withStatlyGetServerSideProps,
43
+ withStatlyGetStaticProps: () => withStatlyGetStaticProps,
44
+ withStatlyPagesApi: () => withStatlyPagesApi,
45
+ withStatlyServerAction: () => withStatlyServerAction
46
+ });
47
+ module.exports = __toCommonJS(index_exports);
48
+
49
+ // src/transport.ts
50
+ var Transport = class {
51
+ constructor(options) {
52
+ this.queue = [];
53
+ this.isSending = false;
54
+ this.maxQueueSize = 100;
55
+ this.flushInterval = 5e3;
56
+ this.dsn = options.dsn;
57
+ this.debug = options.debug ?? false;
58
+ this.endpoint = this.parseEndpoint(options.dsn);
59
+ this.startFlushTimer();
60
+ }
61
+ parseEndpoint(dsn) {
62
+ try {
63
+ const url = new URL(dsn);
64
+ return `${url.protocol}//${url.host}/api/v1/observe/ingest`;
65
+ } catch {
66
+ return `https://statly.live/api/v1/observe/ingest`;
67
+ }
68
+ }
69
+ startFlushTimer() {
70
+ if (typeof window !== "undefined") {
71
+ this.flushTimer = setInterval(() => {
72
+ this.flush();
73
+ }, this.flushInterval);
74
+ }
75
+ }
76
+ /**
77
+ * Add an event to the queue
78
+ */
79
+ enqueue(event) {
80
+ if (this.queue.length >= this.maxQueueSize) {
81
+ this.queue.shift();
82
+ if (this.debug) {
83
+ console.warn("[Statly] Event queue full, dropping oldest event");
84
+ }
85
+ }
86
+ this.queue.push(event);
87
+ if (this.queue.length >= 10) {
88
+ this.flush();
89
+ }
90
+ }
91
+ /**
92
+ * Send a single event immediately
93
+ */
94
+ async send(event) {
95
+ return this.sendBatch([event]);
96
+ }
97
+ /**
98
+ * Flush all queued events
99
+ */
100
+ async flush() {
101
+ if (this.isSending || this.queue.length === 0) {
102
+ return;
103
+ }
104
+ this.isSending = true;
105
+ const events = [...this.queue];
106
+ this.queue = [];
107
+ try {
108
+ await this.sendBatch(events);
109
+ } catch (error) {
110
+ this.queue = [...events, ...this.queue].slice(0, this.maxQueueSize);
111
+ if (this.debug) {
112
+ console.error("[Statly] Failed to send events:", error);
113
+ }
114
+ } finally {
115
+ this.isSending = false;
116
+ }
117
+ }
118
+ /**
119
+ * Send a batch of events
120
+ */
121
+ async sendBatch(events) {
122
+ if (events.length === 0) {
123
+ return { success: true };
124
+ }
125
+ const payload = events.length === 1 ? events[0] : { events };
126
+ try {
127
+ const response = await fetch(this.endpoint, {
128
+ method: "POST",
129
+ headers: {
130
+ "Content-Type": "application/json",
131
+ "X-Statly-DSN": this.dsn
132
+ },
133
+ body: JSON.stringify(payload),
134
+ // Use keepalive for better reliability during page unload
135
+ keepalive: true
136
+ });
137
+ if (!response.ok) {
138
+ const errorText = await response.text().catch(() => "Unknown error");
139
+ if (this.debug) {
140
+ console.error("[Statly] API error:", response.status, errorText);
141
+ }
142
+ return {
143
+ success: false,
144
+ status: response.status,
145
+ error: errorText
146
+ };
147
+ }
148
+ if (this.debug) {
149
+ console.log(`[Statly] Sent ${events.length} event(s)`);
150
+ }
151
+ return { success: true, status: response.status };
152
+ } catch (error) {
153
+ if (this.debug) {
154
+ console.error("[Statly] Network error:", error);
155
+ }
156
+ return {
157
+ success: false,
158
+ error: error instanceof Error ? error.message : "Network error"
159
+ };
160
+ }
161
+ }
162
+ /**
163
+ * Clean up resources
164
+ */
165
+ destroy() {
166
+ if (this.flushTimer) {
167
+ clearInterval(this.flushTimer);
168
+ }
169
+ this.flush();
170
+ }
171
+ };
172
+
173
+ // src/breadcrumbs.ts
174
+ var BreadcrumbManager = class {
175
+ constructor(maxBreadcrumbs = 100) {
176
+ this.breadcrumbs = [];
177
+ this.maxBreadcrumbs = maxBreadcrumbs;
178
+ }
179
+ /**
180
+ * Add a breadcrumb
181
+ */
182
+ add(breadcrumb) {
183
+ const crumb = {
184
+ timestamp: Date.now(),
185
+ ...breadcrumb
186
+ };
187
+ this.breadcrumbs.push(crumb);
188
+ if (this.breadcrumbs.length > this.maxBreadcrumbs) {
189
+ this.breadcrumbs = this.breadcrumbs.slice(-this.maxBreadcrumbs);
190
+ }
191
+ }
192
+ /**
193
+ * Get all breadcrumbs
194
+ */
195
+ getAll() {
196
+ return [...this.breadcrumbs];
197
+ }
198
+ /**
199
+ * Clear all breadcrumbs
200
+ */
201
+ clear() {
202
+ this.breadcrumbs = [];
203
+ }
204
+ /**
205
+ * Set maximum breadcrumbs to keep
206
+ */
207
+ setMaxBreadcrumbs(max) {
208
+ this.maxBreadcrumbs = max;
209
+ if (this.breadcrumbs.length > max) {
210
+ this.breadcrumbs = this.breadcrumbs.slice(-max);
211
+ }
212
+ }
213
+ };
214
+
215
+ // src/integrations/global-handlers.ts
216
+ var GlobalHandlers = class {
217
+ constructor(options = {}) {
218
+ this.originalOnError = null;
219
+ this.originalOnUnhandledRejection = null;
220
+ this.errorCallback = null;
221
+ this.handleUnhandledRejection = (event) => {
222
+ if (!this.errorCallback) {
223
+ return;
224
+ }
225
+ let error;
226
+ if (event.reason instanceof Error) {
227
+ error = event.reason;
228
+ } else if (typeof event.reason === "string") {
229
+ error = new Error(event.reason);
230
+ } else {
231
+ error = new Error("Unhandled Promise Rejection");
232
+ error.reason = event.reason;
233
+ }
234
+ this.errorCallback(error, {
235
+ mechanism: { type: "onunhandledrejection", handled: false }
236
+ });
237
+ };
238
+ this.options = {
239
+ onerror: options.onerror !== false,
240
+ onunhandledrejection: options.onunhandledrejection !== false
241
+ };
242
+ }
243
+ /**
244
+ * Install global error handlers
245
+ */
246
+ install(callback) {
247
+ this.errorCallback = callback;
248
+ if (typeof window === "undefined") {
249
+ return;
250
+ }
251
+ if (this.options.onerror) {
252
+ this.installOnError();
253
+ }
254
+ if (this.options.onunhandledrejection) {
255
+ this.installOnUnhandledRejection();
256
+ }
257
+ }
258
+ /**
259
+ * Uninstall global error handlers
260
+ */
261
+ uninstall() {
262
+ if (typeof window === "undefined") {
263
+ return;
264
+ }
265
+ if (this.originalOnError !== null) {
266
+ window.onerror = this.originalOnError;
267
+ this.originalOnError = null;
268
+ }
269
+ if (this.originalOnUnhandledRejection !== null) {
270
+ window.removeEventListener("unhandledrejection", this.handleUnhandledRejection);
271
+ this.originalOnUnhandledRejection = null;
272
+ }
273
+ this.errorCallback = null;
274
+ }
275
+ installOnError() {
276
+ this.originalOnError = window.onerror;
277
+ window.onerror = (message, source, lineno, colno, error) => {
278
+ if (this.originalOnError) {
279
+ this.originalOnError.call(window, message, source, lineno, colno, error);
280
+ }
281
+ if (this.errorCallback) {
282
+ const errorObj = error || new Error(String(message));
283
+ if (!error && source) {
284
+ errorObj.filename = source;
285
+ errorObj.lineno = lineno;
286
+ errorObj.colno = colno;
287
+ }
288
+ this.errorCallback(errorObj, {
289
+ mechanism: { type: "onerror", handled: false },
290
+ source,
291
+ lineno,
292
+ colno
293
+ });
294
+ }
295
+ return false;
296
+ };
297
+ }
298
+ installOnUnhandledRejection() {
299
+ this.originalOnUnhandledRejection = this.handleUnhandledRejection.bind(this);
300
+ window.addEventListener("unhandledrejection", this.handleUnhandledRejection);
301
+ }
302
+ };
303
+
304
+ // src/integrations/console.ts
305
+ var ConsoleIntegration = class {
306
+ constructor() {
307
+ this.originalMethods = {};
308
+ this.callback = null;
309
+ this.levels = ["debug", "info", "warn", "error", "log"];
310
+ }
311
+ /**
312
+ * Install console breadcrumb tracking
313
+ */
314
+ install(callback, levels) {
315
+ this.callback = callback;
316
+ if (levels) {
317
+ this.levels = levels;
318
+ }
319
+ if (typeof console === "undefined") {
320
+ return;
321
+ }
322
+ for (const level of this.levels) {
323
+ this.wrapConsoleMethod(level);
324
+ }
325
+ }
326
+ /**
327
+ * Uninstall console breadcrumb tracking
328
+ */
329
+ uninstall() {
330
+ if (typeof console === "undefined") {
331
+ return;
332
+ }
333
+ for (const level of this.levels) {
334
+ if (this.originalMethods[level]) {
335
+ console[level] = this.originalMethods[level];
336
+ delete this.originalMethods[level];
337
+ }
338
+ }
339
+ this.callback = null;
340
+ }
341
+ wrapConsoleMethod(level) {
342
+ const originalMethod = console[level];
343
+ if (!originalMethod) {
344
+ return;
345
+ }
346
+ this.originalMethods[level] = originalMethod;
347
+ const self = this;
348
+ console[level] = function(...args) {
349
+ if (self.callback) {
350
+ self.callback({
351
+ category: "console",
352
+ message: self.formatArgs(args),
353
+ level: self.mapLevel(level),
354
+ data: args.length > 1 ? { arguments: args } : void 0
355
+ });
356
+ }
357
+ originalMethod.apply(console, args);
358
+ };
359
+ }
360
+ formatArgs(args) {
361
+ return args.map((arg) => {
362
+ if (typeof arg === "string") {
363
+ return arg;
364
+ }
365
+ if (arg instanceof Error) {
366
+ return arg.message;
367
+ }
368
+ try {
369
+ return JSON.stringify(arg);
370
+ } catch {
371
+ return String(arg);
372
+ }
373
+ }).join(" ");
374
+ }
375
+ mapLevel(consoleLevel) {
376
+ switch (consoleLevel) {
377
+ case "debug":
378
+ return "debug";
379
+ case "info":
380
+ case "log":
381
+ return "info";
382
+ case "warn":
383
+ return "warning";
384
+ case "error":
385
+ return "error";
386
+ default:
387
+ return "info";
388
+ }
389
+ }
390
+ };
391
+
392
+ // src/client.ts
393
+ var SDK_NAME = "@statly/observe-sdk";
394
+ var SDK_VERSION = "0.1.0";
395
+ var StatlyClient = class {
396
+ constructor(options) {
397
+ this.user = null;
398
+ this.initialized = false;
399
+ this.options = this.mergeOptions(options);
400
+ this.transport = new Transport({
401
+ dsn: this.options.dsn,
402
+ debug: this.options.debug
403
+ });
404
+ this.breadcrumbs = new BreadcrumbManager(this.options.maxBreadcrumbs);
405
+ this.globalHandlers = new GlobalHandlers();
406
+ this.consoleIntegration = new ConsoleIntegration();
407
+ }
408
+ mergeOptions(options) {
409
+ return {
410
+ dsn: options.dsn,
411
+ release: options.release ?? "",
412
+ environment: options.environment ?? this.detectEnvironment(),
413
+ debug: options.debug ?? false,
414
+ sampleRate: options.sampleRate ?? 1,
415
+ maxBreadcrumbs: options.maxBreadcrumbs ?? 100,
416
+ autoCapture: options.autoCapture !== false,
417
+ captureConsole: options.captureConsole !== false,
418
+ captureNetwork: options.captureNetwork ?? false,
419
+ tags: options.tags ?? {},
420
+ beforeSend: options.beforeSend ?? ((e) => e)
421
+ };
422
+ }
423
+ detectEnvironment() {
424
+ if (typeof window !== "undefined") {
425
+ if (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1") {
426
+ return "development";
427
+ }
428
+ if (window.location.hostname.includes("staging") || window.location.hostname.includes("stage")) {
429
+ return "staging";
430
+ }
431
+ }
432
+ return "production";
433
+ }
434
+ /**
435
+ * Initialize the SDK
436
+ */
437
+ init() {
438
+ if (this.initialized) {
439
+ if (this.options.debug) {
440
+ console.warn("[Statly] SDK already initialized");
441
+ }
442
+ return;
443
+ }
444
+ this.initialized = true;
445
+ if (this.options.autoCapture) {
446
+ this.globalHandlers.install((error, context) => {
447
+ this.captureError(error, context);
448
+ });
449
+ }
450
+ if (this.options.captureConsole) {
451
+ this.consoleIntegration.install((breadcrumb) => {
452
+ this.breadcrumbs.add(breadcrumb);
453
+ });
454
+ }
455
+ this.addBreadcrumb({
456
+ category: "navigation",
457
+ message: "SDK initialized",
458
+ level: "info"
459
+ });
460
+ if (this.options.debug) {
461
+ console.log("[Statly] SDK initialized", {
462
+ environment: this.options.environment,
463
+ release: this.options.release
464
+ });
465
+ }
466
+ }
467
+ /**
468
+ * Capture an exception/error
469
+ */
470
+ captureException(error, context) {
471
+ let errorObj;
472
+ if (error instanceof Error) {
473
+ errorObj = error;
474
+ } else if (typeof error === "string") {
475
+ errorObj = new Error(error);
476
+ } else {
477
+ errorObj = new Error("Unknown error");
478
+ errorObj.originalError = error;
479
+ }
480
+ return this.captureError(errorObj, context);
481
+ }
482
+ /**
483
+ * Capture a message
484
+ */
485
+ captureMessage(message, level = "info") {
486
+ const event = this.buildEvent({
487
+ message,
488
+ level
489
+ });
490
+ return this.sendEvent(event);
491
+ }
492
+ /**
493
+ * Internal method to capture an error
494
+ */
495
+ captureError(error, context) {
496
+ if (Math.random() > this.options.sampleRate) {
497
+ return "";
498
+ }
499
+ const event = this.buildEvent({
500
+ message: error.message,
501
+ level: "error",
502
+ stack: error.stack,
503
+ exception: {
504
+ type: error.name,
505
+ value: error.message,
506
+ stacktrace: this.parseStackTrace(error.stack)
507
+ },
508
+ extra: context
509
+ });
510
+ return this.sendEvent(event);
511
+ }
512
+ /**
513
+ * Build a complete event from partial data
514
+ */
515
+ buildEvent(partial) {
516
+ const event = {
517
+ message: partial.message || "Unknown error",
518
+ timestamp: Date.now(),
519
+ level: partial.level || "error",
520
+ environment: this.options.environment,
521
+ release: this.options.release || void 0,
522
+ url: typeof window !== "undefined" ? window.location.href : void 0,
523
+ user: this.user || void 0,
524
+ tags: { ...this.options.tags, ...partial.tags },
525
+ extra: partial.extra,
526
+ breadcrumbs: this.breadcrumbs.getAll(),
527
+ browser: this.getBrowserInfo(),
528
+ os: this.getOSInfo(),
529
+ sdk: {
530
+ name: SDK_NAME,
531
+ version: SDK_VERSION
532
+ },
533
+ ...partial
534
+ };
535
+ return event;
536
+ }
537
+ /**
538
+ * Parse a stack trace string into structured frames
539
+ */
540
+ parseStackTrace(stack) {
541
+ if (!stack) {
542
+ return void 0;
543
+ }
544
+ const frames = [];
545
+ const lines = stack.split("\n");
546
+ for (const line of lines) {
547
+ const chromeMatch = line.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
548
+ if (chromeMatch) {
549
+ frames.push({
550
+ function: chromeMatch[1] || "<anonymous>",
551
+ filename: chromeMatch[2],
552
+ lineno: parseInt(chromeMatch[3], 10),
553
+ colno: parseInt(chromeMatch[4], 10)
554
+ });
555
+ continue;
556
+ }
557
+ const firefoxMatch = line.match(/^(.+?)@(.+?):(\d+):(\d+)$/);
558
+ if (firefoxMatch) {
559
+ frames.push({
560
+ function: firefoxMatch[1] || "<anonymous>",
561
+ filename: firefoxMatch[2],
562
+ lineno: parseInt(firefoxMatch[3], 10),
563
+ colno: parseInt(firefoxMatch[4], 10)
564
+ });
565
+ }
566
+ }
567
+ return frames.length > 0 ? { frames } : void 0;
568
+ }
569
+ /**
570
+ * Send an event to the server
571
+ */
572
+ sendEvent(event) {
573
+ const processed = this.options.beforeSend(event);
574
+ if (!processed) {
575
+ if (this.options.debug) {
576
+ console.log("[Statly] Event dropped by beforeSend");
577
+ }
578
+ return "";
579
+ }
580
+ const eventId = this.generateEventId();
581
+ this.breadcrumbs.add({
582
+ category: "statly",
583
+ message: `Captured ${event.level}: ${event.message.slice(0, 50)}`,
584
+ level: "info"
585
+ });
586
+ this.transport.enqueue(processed);
587
+ if (this.options.debug) {
588
+ console.log("[Statly] Event captured:", eventId, event.message);
589
+ }
590
+ return eventId;
591
+ }
592
+ generateEventId() {
593
+ return crypto.randomUUID?.() || "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
594
+ const r = Math.random() * 16 | 0;
595
+ const v = c === "x" ? r : r & 3 | 8;
596
+ return v.toString(16);
597
+ });
598
+ }
599
+ /**
600
+ * Set user context
601
+ */
602
+ setUser(user) {
603
+ this.user = user;
604
+ if (this.options.debug && user) {
605
+ console.log("[Statly] User set:", user.id || user.email);
606
+ }
607
+ }
608
+ /**
609
+ * Set a single tag
610
+ */
611
+ setTag(key, value) {
612
+ this.options.tags[key] = value;
613
+ }
614
+ /**
615
+ * Set multiple tags
616
+ */
617
+ setTags(tags) {
618
+ Object.assign(this.options.tags, tags);
619
+ }
620
+ /**
621
+ * Add a breadcrumb
622
+ */
623
+ addBreadcrumb(breadcrumb) {
624
+ this.breadcrumbs.add(breadcrumb);
625
+ }
626
+ /**
627
+ * Get browser info
628
+ */
629
+ getBrowserInfo() {
630
+ if (typeof navigator === "undefined") {
631
+ return void 0;
632
+ }
633
+ const ua = navigator.userAgent;
634
+ let name = "Unknown";
635
+ let version = "";
636
+ if (ua.includes("Firefox/")) {
637
+ name = "Firefox";
638
+ version = ua.split("Firefox/")[1]?.split(" ")[0] || "";
639
+ } else if (ua.includes("Chrome/")) {
640
+ name = "Chrome";
641
+ version = ua.split("Chrome/")[1]?.split(" ")[0] || "";
642
+ } else if (ua.includes("Safari/") && !ua.includes("Chrome")) {
643
+ name = "Safari";
644
+ version = ua.split("Version/")[1]?.split(" ")[0] || "";
645
+ } else if (ua.includes("Edge/") || ua.includes("Edg/")) {
646
+ name = "Edge";
647
+ version = ua.split(/Edg?e?\//)[1]?.split(" ")[0] || "";
648
+ }
649
+ return { name, version };
650
+ }
651
+ /**
652
+ * Get OS info
653
+ */
654
+ getOSInfo() {
655
+ if (typeof navigator === "undefined") {
656
+ return void 0;
657
+ }
658
+ const ua = navigator.userAgent;
659
+ let name = "Unknown";
660
+ let version = "";
661
+ if (ua.includes("Windows")) {
662
+ name = "Windows";
663
+ const match = ua.match(/Windows NT (\d+\.\d+)/);
664
+ if (match) version = match[1];
665
+ } else if (ua.includes("Mac OS X")) {
666
+ name = "macOS";
667
+ const match = ua.match(/Mac OS X (\d+[._]\d+)/);
668
+ if (match) version = match[1].replace("_", ".");
669
+ } else if (ua.includes("Linux")) {
670
+ name = "Linux";
671
+ } else if (ua.includes("Android")) {
672
+ name = "Android";
673
+ const match = ua.match(/Android (\d+\.\d+)/);
674
+ if (match) version = match[1];
675
+ } else if (ua.includes("iOS") || ua.includes("iPhone") || ua.includes("iPad")) {
676
+ name = "iOS";
677
+ const match = ua.match(/OS (\d+_\d+)/);
678
+ if (match) version = match[1].replace("_", ".");
679
+ }
680
+ return { name, version };
681
+ }
682
+ /**
683
+ * Flush pending events and clean up
684
+ */
685
+ async close() {
686
+ this.globalHandlers.uninstall();
687
+ this.consoleIntegration.uninstall();
688
+ await this.transport.flush();
689
+ this.transport.destroy();
690
+ this.initialized = false;
691
+ }
692
+ /**
693
+ * Force flush pending events
694
+ */
695
+ async flush() {
696
+ await this.transport.flush();
697
+ }
698
+ };
699
+
700
+ // src/integrations/express.ts
701
+ function requestHandler() {
702
+ return (req, res, next) => {
703
+ req.statlyContext = {
704
+ transactionName: `${req.method} ${req.path || req.url}`,
705
+ startTime: Date.now()
706
+ };
707
+ Statly.addBreadcrumb({
708
+ category: "http",
709
+ message: `${req.method} ${req.originalUrl || req.url}`,
710
+ level: "info",
711
+ data: {
712
+ method: req.method,
713
+ url: req.originalUrl || req.url
714
+ }
715
+ });
716
+ if (req.user) {
717
+ Statly.setUser({
718
+ id: req.user.id?.toString(),
719
+ email: req.user.email?.toString()
720
+ });
721
+ }
722
+ res.on("finish", () => {
723
+ const duration = req.statlyContext?.startTime ? Date.now() - req.statlyContext.startTime : void 0;
724
+ Statly.addBreadcrumb({
725
+ category: "http",
726
+ message: `Response ${res.statusCode}`,
727
+ level: res.statusCode >= 400 ? "error" : "info",
728
+ data: {
729
+ statusCode: res.statusCode,
730
+ duration
731
+ }
732
+ });
733
+ });
734
+ next();
735
+ };
736
+ }
737
+ function expressErrorHandler(options = {}) {
738
+ return (err, req, res, next) => {
739
+ const error = err instanceof Error ? err : new Error(String(err));
740
+ if (options.shouldHandleError && !options.shouldHandleError(error)) {
741
+ return next(err);
742
+ }
743
+ const context = {
744
+ request: {
745
+ method: req.method,
746
+ url: req.originalUrl || req.url,
747
+ headers: sanitizeHeaders(req.headers),
748
+ query: req.query,
749
+ data: sanitizeBody(req.body)
750
+ }
751
+ };
752
+ if (req.ip) {
753
+ context.ip = req.ip;
754
+ }
755
+ if (req.user) {
756
+ Statly.setUser({
757
+ id: req.user.id?.toString(),
758
+ email: req.user.email?.toString()
759
+ });
760
+ }
761
+ if (req.statlyContext?.transactionName) {
762
+ Statly.setTag("transaction", req.statlyContext.transactionName);
763
+ }
764
+ Statly.captureException(error, context);
765
+ next(err);
766
+ };
767
+ }
768
+ function sanitizeHeaders(headers) {
769
+ const sensitiveHeaders = ["authorization", "cookie", "x-api-key", "x-auth-token"];
770
+ const sanitized = {};
771
+ for (const [key, value] of Object.entries(headers)) {
772
+ if (sensitiveHeaders.includes(key.toLowerCase())) {
773
+ sanitized[key] = "[Filtered]";
774
+ } else {
775
+ sanitized[key] = value;
776
+ }
777
+ }
778
+ return sanitized;
779
+ }
780
+ function sanitizeBody(body) {
781
+ if (!body || typeof body !== "object") {
782
+ return body;
783
+ }
784
+ const sensitiveFields = ["password", "secret", "token", "apiKey", "api_key", "credit_card", "creditCard", "ssn"];
785
+ const sanitized = {};
786
+ for (const [key, value] of Object.entries(body)) {
787
+ if (sensitiveFields.some((field) => key.toLowerCase().includes(field.toLowerCase()))) {
788
+ sanitized[key] = "[Filtered]";
789
+ } else if (typeof value === "object" && value !== null) {
790
+ sanitized[key] = sanitizeBody(value);
791
+ } else {
792
+ sanitized[key] = value;
793
+ }
794
+ }
795
+ return sanitized;
796
+ }
797
+
798
+ // src/integrations/nextjs.ts
799
+ function withStatlyPagesApi(handler) {
800
+ return async (req, res) => {
801
+ Statly.addBreadcrumb({
802
+ category: "http",
803
+ message: `${req.method} ${req.url}`,
804
+ level: "info",
805
+ data: {
806
+ method: req.method,
807
+ url: req.url
808
+ }
809
+ });
810
+ try {
811
+ return await handler(req, res);
812
+ } catch (error) {
813
+ const context = {
814
+ request: {
815
+ method: req.method,
816
+ url: req.url,
817
+ headers: sanitizeHeaders2(req.headers),
818
+ query: req.query
819
+ }
820
+ };
821
+ Statly.captureException(error, context);
822
+ throw error;
823
+ }
824
+ };
825
+ }
826
+ function withStatly(handler) {
827
+ const wrappedHandler = async (request, context) => {
828
+ Statly.addBreadcrumb({
829
+ category: "http",
830
+ message: `${request.method} ${request.nextUrl?.pathname || request.url}`,
831
+ level: "info",
832
+ data: {
833
+ method: request.method,
834
+ url: request.nextUrl?.pathname || request.url
835
+ }
836
+ });
837
+ try {
838
+ return await handler(request, context);
839
+ } catch (error) {
840
+ const headers = {};
841
+ request.headers.forEach((value, key) => {
842
+ headers[key] = value;
843
+ });
844
+ const errorContext = {
845
+ request: {
846
+ method: request.method,
847
+ url: request.nextUrl?.pathname || request.url,
848
+ headers: sanitizeHeaders2(headers),
849
+ searchParams: request.nextUrl?.searchParams?.toString()
850
+ }
851
+ };
852
+ if (context?.params) {
853
+ try {
854
+ errorContext.params = await context.params;
855
+ } catch {
856
+ }
857
+ }
858
+ Statly.captureException(error, errorContext);
859
+ throw error;
860
+ }
861
+ };
862
+ return wrappedHandler;
863
+ }
864
+ function captureNextJsError(error, context) {
865
+ return Statly.captureException(error, {
866
+ ...context,
867
+ digest: error.digest,
868
+ source: "nextjs-error-boundary"
869
+ });
870
+ }
871
+ function withStatlyGetServerSideProps(handler) {
872
+ return async (context) => {
873
+ try {
874
+ return await handler(context);
875
+ } catch (error) {
876
+ Statly.captureException(error, {
877
+ source: "getServerSideProps",
878
+ url: context.req?.url || context.resolvedUrl
879
+ });
880
+ throw error;
881
+ }
882
+ };
883
+ }
884
+ function withStatlyGetStaticProps(handler) {
885
+ return async (context) => {
886
+ try {
887
+ return await handler(context);
888
+ } catch (error) {
889
+ Statly.captureException(error, {
890
+ source: "getStaticProps",
891
+ params: context.params
892
+ });
893
+ throw error;
894
+ }
895
+ };
896
+ }
897
+ function withStatlyServerAction(action, actionName) {
898
+ return async (...args) => {
899
+ Statly.addBreadcrumb({
900
+ category: "action",
901
+ message: `Server action: ${actionName || "unknown"}`,
902
+ level: "info"
903
+ });
904
+ try {
905
+ return await action(...args);
906
+ } catch (error) {
907
+ Statly.captureException(error, {
908
+ source: "server-action",
909
+ actionName
910
+ });
911
+ throw error;
912
+ }
913
+ };
914
+ }
915
+ function sanitizeHeaders2(headers) {
916
+ const sensitiveHeaders = ["authorization", "cookie", "x-api-key", "x-auth-token"];
917
+ const sanitized = {};
918
+ for (const [key, value] of Object.entries(headers)) {
919
+ if (sensitiveHeaders.includes(key.toLowerCase())) {
920
+ sanitized[key] = "[Filtered]";
921
+ } else {
922
+ sanitized[key] = value;
923
+ }
924
+ }
925
+ return sanitized;
926
+ }
927
+
928
+ // src/integrations/fastify.ts
929
+ function statlyFastifyPlugin(fastify, options, done) {
930
+ const {
931
+ captureValidationErrors = true,
932
+ shouldCapture,
933
+ skipStatusCodes = [400, 401, 403, 404]
934
+ } = options;
935
+ fastify.addHook("onRequest", (request, _reply, hookDone) => {
936
+ request.statlyStartTime = Date.now();
937
+ Statly.addBreadcrumb({
938
+ category: "http",
939
+ message: `${request.method} ${request.routerPath || request.url}`,
940
+ level: "info",
941
+ data: {
942
+ method: request.method,
943
+ url: request.url,
944
+ routerPath: request.routerPath,
945
+ requestId: request.id
946
+ }
947
+ });
948
+ hookDone();
949
+ });
950
+ fastify.addHook("onResponse", (request, reply, hookDone) => {
951
+ const startTime = request.statlyStartTime;
952
+ const duration = startTime ? Date.now() - startTime : void 0;
953
+ Statly.addBreadcrumb({
954
+ category: "http",
955
+ message: `Response ${reply.statusCode}`,
956
+ level: reply.statusCode >= 400 ? "error" : "info",
957
+ data: {
958
+ statusCode: reply.statusCode,
959
+ duration,
960
+ requestId: request.id
961
+ }
962
+ });
963
+ hookDone();
964
+ });
965
+ fastify.setErrorHandler((error, request, reply) => {
966
+ const statusCode = error.statusCode || 500;
967
+ if (skipStatusCodes.includes(statusCode)) {
968
+ throw error;
969
+ }
970
+ if (!captureValidationErrors && error.validation) {
971
+ throw error;
972
+ }
973
+ if (shouldCapture && !shouldCapture(error)) {
974
+ throw error;
975
+ }
976
+ const context = {
977
+ request: {
978
+ id: request.id,
979
+ method: request.method,
980
+ url: request.url,
981
+ routerPath: request.routerPath,
982
+ headers: sanitizeHeaders3(request.headers),
983
+ query: request.query,
984
+ params: request.params
985
+ },
986
+ error: {
987
+ statusCode: error.statusCode,
988
+ code: error.code
989
+ }
990
+ };
991
+ if (request.ip) {
992
+ context.ip = request.ip;
993
+ }
994
+ if (error.validation) {
995
+ context.validation = error.validation;
996
+ }
997
+ Statly.setTag("http.method", request.method);
998
+ Statly.setTag("http.url", request.routerPath || request.url);
999
+ Statly.setTag("http.status_code", String(statusCode));
1000
+ Statly.captureException(error, context);
1001
+ throw error;
1002
+ });
1003
+ done();
1004
+ }
1005
+ var statlyPlugin = statlyFastifyPlugin;
1006
+ function createRequestCapture(request) {
1007
+ return (error, additionalContext) => {
1008
+ const context = {
1009
+ request: {
1010
+ id: request.id,
1011
+ method: request.method,
1012
+ url: request.url,
1013
+ routerPath: request.routerPath
1014
+ },
1015
+ ...additionalContext
1016
+ };
1017
+ return Statly.captureException(error, context);
1018
+ };
1019
+ }
1020
+ function sanitizeHeaders3(headers) {
1021
+ const sensitiveHeaders = ["authorization", "cookie", "x-api-key", "x-auth-token"];
1022
+ const sanitized = {};
1023
+ for (const [key, value] of Object.entries(headers)) {
1024
+ if (sensitiveHeaders.includes(key.toLowerCase())) {
1025
+ sanitized[key] = "[Filtered]";
1026
+ } else {
1027
+ sanitized[key] = value;
1028
+ }
1029
+ }
1030
+ return sanitized;
1031
+ }
1032
+
1033
+ // src/index.ts
1034
+ var client = null;
1035
+ function init(options) {
1036
+ if (client) {
1037
+ console.warn("[Statly] SDK already initialized. Call close() first to reinitialize.");
1038
+ return;
1039
+ }
1040
+ client = new StatlyClient(options);
1041
+ client.init();
1042
+ }
1043
+ function captureException(error, context) {
1044
+ if (!client) {
1045
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
1046
+ return "";
1047
+ }
1048
+ return client.captureException(error, context);
1049
+ }
1050
+ function captureMessage(message, level = "info") {
1051
+ if (!client) {
1052
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
1053
+ return "";
1054
+ }
1055
+ return client.captureMessage(message, level);
1056
+ }
1057
+ function setUser(user) {
1058
+ if (!client) {
1059
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
1060
+ return;
1061
+ }
1062
+ client.setUser(user);
1063
+ }
1064
+ function setTag(key, value) {
1065
+ if (!client) {
1066
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
1067
+ return;
1068
+ }
1069
+ client.setTag(key, value);
1070
+ }
1071
+ function setTags(tags) {
1072
+ if (!client) {
1073
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
1074
+ return;
1075
+ }
1076
+ client.setTags(tags);
1077
+ }
1078
+ function addBreadcrumb(breadcrumb) {
1079
+ if (!client) {
1080
+ console.warn("[Statly] SDK not initialized. Call Statly.init() first.");
1081
+ return;
1082
+ }
1083
+ client.addBreadcrumb(breadcrumb);
1084
+ }
1085
+ async function flush() {
1086
+ if (!client) {
1087
+ return;
1088
+ }
1089
+ await client.flush();
1090
+ }
1091
+ async function close() {
1092
+ if (!client) {
1093
+ return;
1094
+ }
1095
+ await client.close();
1096
+ client = null;
1097
+ }
1098
+ function getClient() {
1099
+ return client;
1100
+ }
1101
+ var Statly = {
1102
+ init,
1103
+ captureException,
1104
+ captureMessage,
1105
+ setUser,
1106
+ setTag,
1107
+ setTags,
1108
+ addBreadcrumb,
1109
+ flush,
1110
+ close,
1111
+ getClient
1112
+ };
1113
+ // Annotate the CommonJS export names for ESM import in node:
1114
+ 0 && (module.exports = {
1115
+ Statly,
1116
+ StatlyClient,
1117
+ addBreadcrumb,
1118
+ captureException,
1119
+ captureMessage,
1120
+ captureNextJsError,
1121
+ close,
1122
+ createRequestCapture,
1123
+ expressErrorHandler,
1124
+ flush,
1125
+ getClient,
1126
+ init,
1127
+ requestHandler,
1128
+ setTag,
1129
+ setTags,
1130
+ setUser,
1131
+ statlyFastifyPlugin,
1132
+ statlyPlugin,
1133
+ withStatly,
1134
+ withStatlyGetServerSideProps,
1135
+ withStatlyGetStaticProps,
1136
+ withStatlyPagesApi,
1137
+ withStatlyServerAction
1138
+ });