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