bugstack-sdk 1.0.0 → 2.0.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,998 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/core/fingerprint.ts
9
+ function generateErrorFingerprint(error) {
10
+ const errorType = error.name || "Error";
11
+ const route = error.route || "unknown";
12
+ const stackFirstLine = getStackFirstLine(error.stack);
13
+ const key = `${errorType}:${route}:${stackFirstLine}`;
14
+ return simpleHash(key);
15
+ }
16
+ function getStackFirstLine(stack) {
17
+ if (!stack) return "unknown";
18
+ const lines = stack.split("\n");
19
+ for (const line of lines) {
20
+ const trimmed = line.trim();
21
+ if (trimmed.startsWith("at ")) {
22
+ return trimmed;
23
+ }
24
+ }
25
+ for (const line of lines) {
26
+ const trimmed = line.trim();
27
+ if (trimmed) {
28
+ return trimmed;
29
+ }
30
+ }
31
+ return "unknown";
32
+ }
33
+ function simpleHash(str) {
34
+ let hash = 5381;
35
+ for (let i = 0; i < str.length; i++) {
36
+ hash = (hash << 5) + hash + str.charCodeAt(i);
37
+ hash = hash & hash;
38
+ }
39
+ const unsignedHash = hash >>> 0;
40
+ return unsignedHash.toString(16).padStart(8, "0");
41
+ }
42
+
43
+ // src/core/deduplicator.ts
44
+ var ErrorDeduplicator = class {
45
+ /**
46
+ * Cache of fingerprint → timestamp mapping
47
+ * Key: error fingerprint (hex string)
48
+ * Value: timestamp (ms) when error was last sent
49
+ */
50
+ cache;
51
+ /**
52
+ * Time window in milliseconds
53
+ * Errors with the same fingerprint within this window are considered duplicates
54
+ */
55
+ window;
56
+ /**
57
+ * Interval ID for cleanup task
58
+ */
59
+ cleanupIntervalId;
60
+ /**
61
+ * Create a new deduplicator
62
+ *
63
+ * @param window - Deduplication window in milliseconds (default: 5 minutes)
64
+ */
65
+ constructor(window = 5 * 60 * 1e3) {
66
+ this.cache = /* @__PURE__ */ new Map();
67
+ this.window = window;
68
+ this.startCleanup();
69
+ }
70
+ /**
71
+ * Check if an error should be sent
72
+ *
73
+ * @param fingerprint - Error fingerprint
74
+ * @returns true if error should be sent, false if it's a duplicate
75
+ */
76
+ shouldSend(fingerprint) {
77
+ const now = Date.now();
78
+ const lastSent = this.cache.get(fingerprint);
79
+ if (lastSent !== void 0) {
80
+ const elapsed = now - lastSent;
81
+ if (elapsed < this.window) {
82
+ return false;
83
+ }
84
+ }
85
+ this.cache.set(fingerprint, now);
86
+ return true;
87
+ }
88
+ /**
89
+ * Mark an error as sent (manually)
90
+ *
91
+ * This can be used to pre-populate the cache or update the timestamp
92
+ * after a successful send.
93
+ *
94
+ * @param fingerprint - Error fingerprint
95
+ */
96
+ markSent(fingerprint) {
97
+ this.cache.set(fingerprint, Date.now());
98
+ }
99
+ /**
100
+ * Check if an error fingerprint is in the cache
101
+ *
102
+ * @param fingerprint - Error fingerprint
103
+ * @returns true if fingerprint exists and is within the window
104
+ */
105
+ has(fingerprint) {
106
+ const lastSent = this.cache.get(fingerprint);
107
+ if (lastSent === void 0) {
108
+ return false;
109
+ }
110
+ const elapsed = Date.now() - lastSent;
111
+ return elapsed < this.window;
112
+ }
113
+ /**
114
+ * Get the number of entries in the cache
115
+ */
116
+ get size() {
117
+ return this.cache.size;
118
+ }
119
+ /**
120
+ * Clear all entries from the cache
121
+ */
122
+ clear() {
123
+ this.cache.clear();
124
+ }
125
+ /**
126
+ * Remove expired entries from the cache
127
+ *
128
+ * This is called automatically every minute, but can also be
129
+ * called manually to free up memory.
130
+ */
131
+ cleanup() {
132
+ const now = Date.now();
133
+ const toDelete = [];
134
+ for (const [fingerprint, timestamp] of this.cache.entries()) {
135
+ const elapsed = now - timestamp;
136
+ if (elapsed >= this.window) {
137
+ toDelete.push(fingerprint);
138
+ }
139
+ }
140
+ for (const fingerprint of toDelete) {
141
+ this.cache.delete(fingerprint);
142
+ }
143
+ }
144
+ /**
145
+ * Start automatic cleanup task
146
+ *
147
+ * Runs cleanup every minute to remove expired entries
148
+ */
149
+ startCleanup() {
150
+ this.cleanupIntervalId = setInterval(() => {
151
+ this.cleanup();
152
+ }, 60 * 1e3);
153
+ if (this.cleanupIntervalId.unref) {
154
+ this.cleanupIntervalId.unref();
155
+ }
156
+ }
157
+ /**
158
+ * Stop automatic cleanup task
159
+ *
160
+ * This should be called when shutting down to prevent memory leaks
161
+ */
162
+ destroy() {
163
+ if (this.cleanupIntervalId) {
164
+ clearInterval(this.cleanupIntervalId);
165
+ this.cleanupIntervalId = void 0;
166
+ }
167
+ this.cache.clear();
168
+ }
169
+ /**
170
+ * Get cache statistics (for debugging)
171
+ */
172
+ getStats() {
173
+ const now = Date.now();
174
+ const entries = Array.from(this.cache.entries()).map(([fingerprint, timestamp]) => ({
175
+ fingerprint,
176
+ age: now - timestamp
177
+ }));
178
+ return {
179
+ size: this.cache.size,
180
+ window: this.window,
181
+ entries
182
+ };
183
+ }
184
+ };
185
+
186
+ // src/core/queue.ts
187
+ var RetryQueue = class {
188
+ /**
189
+ * Queue of errors waiting to be sent
190
+ */
191
+ queue = [];
192
+ /**
193
+ * Whether the queue is currently processing
194
+ */
195
+ processing = false;
196
+ /**
197
+ * Maximum number of retry attempts
198
+ */
199
+ maxRetries = 5;
200
+ /**
201
+ * Base backoff delay in milliseconds
202
+ */
203
+ baseDelay = 1e3;
204
+ // 1 second
205
+ /**
206
+ * Maximum backoff delay in milliseconds
207
+ */
208
+ maxDelay = 16e3;
209
+ // 16 seconds
210
+ /**
211
+ * Function to send errors
212
+ */
213
+ sendFn;
214
+ /**
215
+ * Debug mode
216
+ */
217
+ debug;
218
+ /**
219
+ * Processing interval ID
220
+ */
221
+ intervalId;
222
+ /**
223
+ * Create a new retry queue
224
+ *
225
+ * @param sendFn - Function to send errors
226
+ * @param options - Configuration options
227
+ */
228
+ constructor(sendFn, options) {
229
+ this.sendFn = sendFn;
230
+ this.maxRetries = options?.maxRetries ?? 5;
231
+ this.baseDelay = options?.baseDelay ?? 1e3;
232
+ this.maxDelay = options?.maxDelay ?? 16e3;
233
+ this.debug = options?.debug ?? false;
234
+ this.startProcessing();
235
+ }
236
+ /**
237
+ * Enqueue an error for sending
238
+ *
239
+ * This is non-blocking and returns immediately.
240
+ *
241
+ * @param error - The error to send
242
+ * @param sourceContext - Source context (optional)
243
+ */
244
+ enqueue(error, sourceContext) {
245
+ const queuedError = {
246
+ error,
247
+ sourceContext,
248
+ attempts: 0,
249
+ nextRetry: Date.now()
250
+ // Send immediately on first attempt
251
+ };
252
+ this.queue.push(queuedError);
253
+ this.log(`Enqueued error: ${error.id} (queue size: ${this.queue.length})`);
254
+ this.processQueue();
255
+ }
256
+ /**
257
+ * Get the current queue size
258
+ */
259
+ get size() {
260
+ return this.queue.length;
261
+ }
262
+ /**
263
+ * Clear all items from the queue
264
+ */
265
+ clear() {
266
+ this.queue = [];
267
+ }
268
+ /**
269
+ * Destroy the queue and stop processing
270
+ */
271
+ destroy() {
272
+ if (this.intervalId) {
273
+ clearInterval(this.intervalId);
274
+ this.intervalId = void 0;
275
+ }
276
+ this.queue = [];
277
+ this.processing = false;
278
+ }
279
+ /**
280
+ * Start periodic queue processing
281
+ */
282
+ startProcessing() {
283
+ this.intervalId = setInterval(() => {
284
+ this.processQueue();
285
+ }, 500);
286
+ if (this.intervalId.unref) {
287
+ this.intervalId.unref();
288
+ }
289
+ }
290
+ /**
291
+ * Process the queue
292
+ *
293
+ * This is called periodically and also immediately after enqueue.
294
+ * Non-blocking - errors are caught and logged.
295
+ */
296
+ async processQueue() {
297
+ if (this.processing || this.queue.length === 0) {
298
+ return;
299
+ }
300
+ this.processing = true;
301
+ try {
302
+ const now = Date.now();
303
+ const readyErrors = this.queue.filter((item) => item.nextRetry <= now);
304
+ if (readyErrors.length === 0) {
305
+ return;
306
+ }
307
+ this.log(`Processing ${readyErrors.length} ready errors`);
308
+ for (const item of readyErrors) {
309
+ await this.processItem(item);
310
+ }
311
+ } catch (err) {
312
+ this.logError("Queue processing error:", err);
313
+ } finally {
314
+ this.processing = false;
315
+ }
316
+ }
317
+ /**
318
+ * Process a single queued error
319
+ *
320
+ * @param item - The queued error item
321
+ */
322
+ async processItem(item) {
323
+ try {
324
+ item.attempts++;
325
+ item.lastAttempt = Date.now();
326
+ this.log(
327
+ `Sending error ${item.error.id} (attempt ${item.attempts}/${this.maxRetries})`
328
+ );
329
+ const success = await this.sendFn(item.error, item.sourceContext);
330
+ if (success) {
331
+ this.log(`Successfully sent error: ${item.error.id}`);
332
+ this.removeFromQueue(item);
333
+ } else {
334
+ this.handleFailure(item);
335
+ }
336
+ } catch (err) {
337
+ this.logError(`Error sending ${item.error.id}:`, err);
338
+ this.handleFailure(item);
339
+ }
340
+ }
341
+ /**
342
+ * Handle a failed send attempt
343
+ *
344
+ * @param item - The queued error item
345
+ */
346
+ handleFailure(item) {
347
+ if (item.attempts >= this.maxRetries) {
348
+ this.logError(
349
+ `Max retries exceeded for error ${item.error.id}, dropping`
350
+ );
351
+ this.removeFromQueue(item);
352
+ } else {
353
+ const delay = this.calculateBackoff(item.attempts);
354
+ item.nextRetry = Date.now() + delay;
355
+ this.log(
356
+ `Scheduling retry for error ${item.error.id} in ${delay}ms (attempt ${item.attempts}/${this.maxRetries})`
357
+ );
358
+ }
359
+ }
360
+ /**
361
+ * Calculate exponential backoff delay
362
+ *
363
+ * Backoff formula: min(baseDelay * 2^(attempts - 1), maxDelay)
364
+ * - Attempt 1: 1s
365
+ * - Attempt 2: 2s
366
+ * - Attempt 3: 4s
367
+ * - Attempt 4: 8s
368
+ * - Attempt 5: 16s
369
+ *
370
+ * @param attempts - Number of attempts
371
+ * @returns Delay in milliseconds
372
+ */
373
+ calculateBackoff(attempts) {
374
+ const delay = this.baseDelay * Math.pow(2, attempts - 1);
375
+ return Math.min(delay, this.maxDelay);
376
+ }
377
+ /**
378
+ * Remove an item from the queue
379
+ *
380
+ * @param item - The item to remove
381
+ */
382
+ removeFromQueue(item) {
383
+ const index = this.queue.indexOf(item);
384
+ if (index !== -1) {
385
+ this.queue.splice(index, 1);
386
+ }
387
+ }
388
+ /**
389
+ * Log a message (if debug mode is enabled)
390
+ *
391
+ * @param message - Message to log
392
+ */
393
+ log(message) {
394
+ if (this.debug) {
395
+ console.log(`[BugStack Queue] ${message}`);
396
+ }
397
+ }
398
+ /**
399
+ * Log an error (if debug mode is enabled)
400
+ *
401
+ * @param message - Message to log
402
+ * @param error - Error object (optional)
403
+ */
404
+ logError(message, error) {
405
+ if (this.debug) {
406
+ if (error) {
407
+ console.error(`[BugStack Queue] ${message}`, error);
408
+ } else {
409
+ console.error(`[BugStack Queue] ${message}`);
410
+ }
411
+ }
412
+ }
413
+ /**
414
+ * Get queue statistics (for debugging)
415
+ */
416
+ getStats() {
417
+ const now = Date.now();
418
+ return {
419
+ size: this.queue.length,
420
+ processing: this.processing,
421
+ items: this.queue.map((item) => ({
422
+ errorId: item.error.id,
423
+ attempts: item.attempts,
424
+ nextRetry: item.nextRetry,
425
+ timeUntilRetry: Math.max(0, item.nextRetry - now)
426
+ }))
427
+ };
428
+ }
429
+ };
430
+
431
+ // src/core/client.ts
432
+ var SDK_VERSION = "0.2.0";
433
+ var DEFAULT_ENDPOINT = "http://localhost:3001/api/capture";
434
+ var DEFAULT_TIMEOUT = 5e3;
435
+ var DEFAULT_MAX_BODY_SIZE = 1e4;
436
+ var DEFAULT_DEDUPLICATION_WINDOW = 5 * 60 * 1e3;
437
+ var DEFAULT_REDACT_FIELDS = [
438
+ "password",
439
+ "secret",
440
+ "token",
441
+ "apikey",
442
+ "api_key",
443
+ "apiKey",
444
+ "authorization",
445
+ "auth",
446
+ "credential",
447
+ "private",
448
+ "credit_card",
449
+ "creditcard",
450
+ "card_number",
451
+ "cvv",
452
+ "ssn",
453
+ "social_security"
454
+ ];
455
+ var ErrorCaptureClient = class _ErrorCaptureClient {
456
+ config;
457
+ static instance = null;
458
+ deduplicator;
459
+ retryQueue;
460
+ constructor(config) {
461
+ const isProduction = process.env.NODE_ENV === "production";
462
+ this.config = {
463
+ apiKey: config.apiKey,
464
+ endpoint: config.endpoint ?? process.env.BUGSTACK_ENDPOINT ?? DEFAULT_ENDPOINT,
465
+ projectId: config.projectId ?? process.env.BUGSTACK_PROJECT_ID ?? "",
466
+ environment: config.environment ?? process.env.NODE_ENV ?? "development",
467
+ autoFix: config.autoFix ?? false,
468
+ enabled: config.enabled ?? true,
469
+ captureRequestBody: config.captureRequestBody ?? true,
470
+ captureQueryParams: config.captureQueryParams ?? true,
471
+ captureHeaders: config.captureHeaders ?? true,
472
+ maxBodySize: config.maxBodySize ?? DEFAULT_MAX_BODY_SIZE,
473
+ redactFields: [
474
+ ...DEFAULT_REDACT_FIELDS,
475
+ ...config.redactFields ?? []
476
+ ],
477
+ metadata: config.metadata ?? {},
478
+ timeout: config.timeout ?? DEFAULT_TIMEOUT,
479
+ deduplicationWindow: config.deduplicationWindow ?? DEFAULT_DEDUPLICATION_WINDOW,
480
+ debug: config.debug ?? !isProduction,
481
+ shouldCapture: config.shouldCapture,
482
+ beforeSend: config.beforeSend
483
+ };
484
+ this.deduplicator = new ErrorDeduplicator(this.config.deduplicationWindow);
485
+ this.retryQueue = new RetryQueue(
486
+ (error, sourceContext) => this.sendErrorToService(error, sourceContext),
487
+ {
488
+ maxRetries: 5,
489
+ baseDelay: 1e3,
490
+ maxDelay: 16e3,
491
+ debug: this.config.debug
492
+ }
493
+ );
494
+ this.log("BugStack client initialized", {
495
+ endpoint: this.config.endpoint,
496
+ projectId: this.config.projectId,
497
+ environment: this.config.environment,
498
+ autoFix: this.config.autoFix,
499
+ deduplicationWindow: this.config.deduplicationWindow
500
+ });
501
+ }
502
+ /**
503
+ * Initialize the singleton client instance
504
+ */
505
+ static init(config) {
506
+ if (_ErrorCaptureClient.instance) {
507
+ _ErrorCaptureClient.instance.destroy();
508
+ }
509
+ _ErrorCaptureClient.instance = new _ErrorCaptureClient(config);
510
+ return _ErrorCaptureClient.instance;
511
+ }
512
+ /**
513
+ * Get the singleton client instance
514
+ */
515
+ static getInstance() {
516
+ return _ErrorCaptureClient.instance;
517
+ }
518
+ /**
519
+ * Check if the client has been initialized
520
+ */
521
+ static isInitialized() {
522
+ return _ErrorCaptureClient.instance !== null;
523
+ }
524
+ /**
525
+ * Reset the client (mainly for testing)
526
+ */
527
+ static reset() {
528
+ if (_ErrorCaptureClient.instance) {
529
+ _ErrorCaptureClient.instance.destroy();
530
+ }
531
+ _ErrorCaptureClient.instance = null;
532
+ }
533
+ /**
534
+ * Report an error to the BugStack service
535
+ *
536
+ * This method includes deduplication and queuing for resilience.
537
+ *
538
+ * @param error - The captured error
539
+ * @param sourceContext - Source code context (optional)
540
+ * @returns Promise that resolves to true if error was accepted (not deduplicated)
541
+ */
542
+ async reportError(error, sourceContext) {
543
+ if (!this.config.enabled) {
544
+ this.log("Error capture is disabled, skipping report");
545
+ return false;
546
+ }
547
+ let errorToSend = error;
548
+ if (this.config.beforeSend) {
549
+ const modified = this.config.beforeSend(error);
550
+ if (modified === null) {
551
+ this.log("Error filtered by beforeSend hook");
552
+ return false;
553
+ }
554
+ errorToSend = modified;
555
+ }
556
+ const fingerprint = generateErrorFingerprint(errorToSend);
557
+ errorToSend.fingerprint = fingerprint;
558
+ if (!this.deduplicator.shouldSend(fingerprint)) {
559
+ this.log(`Error deduplicated: ${error.id} (fingerprint: ${fingerprint})`);
560
+ return false;
561
+ }
562
+ this.log(`Reporting error: ${error.id} (fingerprint: ${fingerprint})`);
563
+ errorToSend.projectId = this.config.projectId || errorToSend.projectId;
564
+ errorToSend.environment = this.config.environment;
565
+ errorToSend.metadata = {
566
+ ...this.config.metadata,
567
+ ...errorToSend.metadata,
568
+ autoFix: this.config.autoFix
569
+ };
570
+ this.retryQueue.enqueue(errorToSend, sourceContext);
571
+ return true;
572
+ }
573
+ /**
574
+ * Send an error to the service (internal method)
575
+ *
576
+ * This is used by the retry queue. Returns true on success, false on failure.
577
+ *
578
+ * @param error - The error to send
579
+ * @param sourceContext - Source context (optional)
580
+ * @returns Promise that resolves to true on success
581
+ */
582
+ async sendErrorToService(error, sourceContext) {
583
+ const payload = {
584
+ error,
585
+ sourceContext
586
+ };
587
+ try {
588
+ const controller = new AbortController();
589
+ const timeoutId = setTimeout(
590
+ () => controller.abort(),
591
+ this.config.timeout
592
+ );
593
+ const response = await fetch(this.config.endpoint, {
594
+ method: "POST",
595
+ headers: {
596
+ "Content-Type": "application/json",
597
+ "X-BugStack-API-Key": this.config.apiKey,
598
+ "X-BugStack-SDK-Version": SDK_VERSION
599
+ },
600
+ body: JSON.stringify(payload),
601
+ signal: controller.signal
602
+ });
603
+ clearTimeout(timeoutId);
604
+ if (!response.ok) {
605
+ this.logError(
606
+ `Failed to send error: HTTP ${response.status} ${response.statusText}`
607
+ );
608
+ return false;
609
+ }
610
+ this.log(`Error sent successfully: ${error.id}`);
611
+ return true;
612
+ } catch (err) {
613
+ if (err instanceof Error && err.name === "AbortError") {
614
+ this.logError(`Error send timed out after ${this.config.timeout}ms`);
615
+ } else {
616
+ this.logError("Failed to send error:", err);
617
+ }
618
+ return false;
619
+ }
620
+ }
621
+ /**
622
+ * Get the resolved configuration
623
+ */
624
+ getConfig() {
625
+ return { ...this.config };
626
+ }
627
+ /**
628
+ * Check if a field should be redacted
629
+ */
630
+ shouldRedact(fieldName) {
631
+ const lowerField = fieldName.toLowerCase();
632
+ return this.config.redactFields.some(
633
+ (redact) => lowerField.includes(redact.toLowerCase()) || redact.toLowerCase().includes(lowerField)
634
+ );
635
+ }
636
+ /**
637
+ * Get the SDK version
638
+ */
639
+ static getVersion() {
640
+ return SDK_VERSION;
641
+ }
642
+ /**
643
+ * Get client statistics (for debugging)
644
+ */
645
+ getStats() {
646
+ return {
647
+ deduplicator: this.deduplicator.getStats(),
648
+ retryQueue: this.retryQueue.getStats()
649
+ };
650
+ }
651
+ /**
652
+ * Clean up resources
653
+ *
654
+ * Should be called when shutting down to prevent memory leaks
655
+ */
656
+ destroy() {
657
+ this.deduplicator.destroy();
658
+ this.retryQueue.destroy();
659
+ }
660
+ log(message, data) {
661
+ if (this.config.debug) {
662
+ if (data) {
663
+ console.log(`[BugStack] ${message}`, data);
664
+ } else {
665
+ console.log(`[BugStack] ${message}`);
666
+ }
667
+ }
668
+ }
669
+ logError(message, error) {
670
+ if (this.config.debug) {
671
+ if (error) {
672
+ console.error(`[BugStack] ${message}`, error);
673
+ } else {
674
+ console.error(`[BugStack] ${message}`);
675
+ }
676
+ }
677
+ }
678
+ };
679
+ var BugStackClient = ErrorCaptureClient;
680
+
681
+ // src/core/utils/sanitize.ts
682
+ var REDACT_PLACEHOLDER = "[REDACTED]";
683
+ var TRUNCATE_PLACEHOLDER = "[TRUNCATED]";
684
+ var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
685
+ "authorization",
686
+ "cookie",
687
+ "set-cookie",
688
+ "x-api-key",
689
+ "x-auth-token",
690
+ "x-bugstack-api-key",
691
+ "proxy-authorization",
692
+ "www-authenticate"
693
+ ]);
694
+ function sanitizeHeaders(headers, client) {
695
+ const sanitized = {};
696
+ headers.forEach((value, key) => {
697
+ const lowerKey = key.toLowerCase();
698
+ if (SENSITIVE_HEADERS.has(lowerKey)) {
699
+ sanitized[key] = REDACT_PLACEHOLDER;
700
+ return;
701
+ }
702
+ if (client?.shouldRedact(key)) {
703
+ sanitized[key] = REDACT_PLACEHOLDER;
704
+ return;
705
+ }
706
+ sanitized[key] = value;
707
+ });
708
+ return sanitized;
709
+ }
710
+ function sanitizeQueryParams(url, client) {
711
+ const sanitized = {};
712
+ url.searchParams.forEach((value, key) => {
713
+ if (client?.shouldRedact(key)) {
714
+ sanitized[key] = REDACT_PLACEHOLDER;
715
+ } else {
716
+ sanitized[key] = value;
717
+ }
718
+ });
719
+ return sanitized;
720
+ }
721
+ function sanitizeObject(obj, client, maxDepth = 10, currentDepth = 0) {
722
+ if (currentDepth > maxDepth) {
723
+ return TRUNCATE_PLACEHOLDER;
724
+ }
725
+ if (obj === null || obj === void 0) {
726
+ return obj;
727
+ }
728
+ if (typeof obj !== "object") {
729
+ return obj;
730
+ }
731
+ if (Array.isArray(obj)) {
732
+ return obj.map(
733
+ (item) => sanitizeObject(item, client, maxDepth, currentDepth + 1)
734
+ );
735
+ }
736
+ const sanitized = {};
737
+ for (const [key, value] of Object.entries(obj)) {
738
+ if (client?.shouldRedact(key)) {
739
+ sanitized[key] = REDACT_PLACEHOLDER;
740
+ } else if (typeof value === "object" && value !== null) {
741
+ sanitized[key] = sanitizeObject(value, client, maxDepth, currentDepth + 1);
742
+ } else {
743
+ sanitized[key] = value;
744
+ }
745
+ }
746
+ return sanitized;
747
+ }
748
+ function truncateBody(data, maxSize) {
749
+ const serialized = JSON.stringify(data);
750
+ if (serialized.length <= maxSize) {
751
+ return { body: data, truncated: false };
752
+ }
753
+ if (typeof data === "string") {
754
+ return {
755
+ body: data.slice(0, maxSize) + `... ${TRUNCATE_PLACEHOLDER}`,
756
+ truncated: true
757
+ };
758
+ }
759
+ return {
760
+ body: {
761
+ __truncated: true,
762
+ __originalSize: serialized.length,
763
+ __maxSize: maxSize,
764
+ preview: serialized.slice(0, maxSize)
765
+ },
766
+ truncated: true
767
+ };
768
+ }
769
+ async function safeParseBody(request, maxSize, client) {
770
+ try {
771
+ const cloned = request.clone();
772
+ const contentType = cloned.headers.get("content-type") ?? "";
773
+ if (contentType.includes("application/json")) {
774
+ const text = await cloned.text();
775
+ if (text.length > maxSize) {
776
+ return {
777
+ body: {
778
+ __truncated: true,
779
+ __originalSize: text.length,
780
+ preview: text.slice(0, maxSize)
781
+ },
782
+ truncated: true
783
+ };
784
+ }
785
+ try {
786
+ const parsed = JSON.parse(text);
787
+ const sanitized = sanitizeObject(parsed, client);
788
+ return truncateBody(sanitized, maxSize);
789
+ } catch {
790
+ return truncateBody(text, maxSize);
791
+ }
792
+ }
793
+ if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
794
+ try {
795
+ const formData = await cloned.formData();
796
+ const data = {};
797
+ formData.forEach((value, key) => {
798
+ if (value instanceof File) {
799
+ data[key] = {
800
+ type: "file",
801
+ name: value.name,
802
+ size: value.size,
803
+ mimeType: value.type
804
+ };
805
+ } else if (client?.shouldRedact(key)) {
806
+ data[key] = REDACT_PLACEHOLDER;
807
+ } else {
808
+ data[key] = value;
809
+ }
810
+ });
811
+ return truncateBody(data, maxSize);
812
+ } catch {
813
+ return { body: "[FormData parsing failed]", truncated: false };
814
+ }
815
+ }
816
+ if (contentType.includes("text/")) {
817
+ const text = await cloned.text();
818
+ return truncateBody(text, maxSize);
819
+ }
820
+ return {
821
+ body: {
822
+ __contentType: contentType,
823
+ __note: "Body not captured for this content type"
824
+ },
825
+ truncated: false
826
+ };
827
+ } catch (err) {
828
+ return null;
829
+ }
830
+ }
831
+
832
+ // src/core/utils/stack-parser.ts
833
+ var V8_STACK_FRAME_REGEX = /^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?(?:(.+?):(\d+):(\d+))\)?$/;
834
+ function isNodeModule(filePath) {
835
+ return filePath.includes("node_modules");
836
+ }
837
+ function isInternalCode(filePath) {
838
+ return filePath.startsWith("node:") || filePath.startsWith("internal/") || !filePath.includes("/");
839
+ }
840
+ function cleanFunctionName(name) {
841
+ if (!name) return void 0;
842
+ return name.replace(/^Object\./, "").replace(/^Module\./, "").replace(/^__webpack_require__\./, "").replace(/^webpack_require\./, "").trim();
843
+ }
844
+ function parseStackTrace(stack) {
845
+ if (!stack) return [];
846
+ const lines = stack.split("\n");
847
+ const frames = [];
848
+ for (const line of lines) {
849
+ const match = V8_STACK_FRAME_REGEX.exec(line);
850
+ if (match) {
851
+ const [, functionName, file, lineStr, columnStr] = match;
852
+ const frame = {
853
+ function: cleanFunctionName(functionName),
854
+ file: file ?? void 0,
855
+ line: lineStr ? parseInt(lineStr, 10) : void 0,
856
+ column: columnStr ? parseInt(columnStr, 10) : void 0
857
+ };
858
+ if (frame.file) {
859
+ frame.isNodeModule = isNodeModule(frame.file);
860
+ frame.isInternal = isInternalCode(frame.file);
861
+ }
862
+ frames.push(frame);
863
+ }
864
+ }
865
+ return frames;
866
+ }
867
+ function getFirstAppFrame(frames) {
868
+ return frames.find((frame) => !frame.isNodeModule && !frame.isInternal);
869
+ }
870
+
871
+ // src/adapters/nextjs/index.ts
872
+ var SDK_VERSION2 = "0.2.0";
873
+ function generateErrorId() {
874
+ const timestamp = Date.now().toString(36);
875
+ const random = Math.random().toString(36).substring(2, 9);
876
+ return `err_${timestamp}_${random}`;
877
+ }
878
+ function extractRoute(request) {
879
+ try {
880
+ const url = new URL(request.url);
881
+ return url.pathname;
882
+ } catch {
883
+ return "unknown";
884
+ }
885
+ }
886
+ function getNodeVersion() {
887
+ try {
888
+ return process.version;
889
+ } catch {
890
+ return "unknown";
891
+ }
892
+ }
893
+ function getNextVersion() {
894
+ try {
895
+ const pkg = __require("next/package.json");
896
+ return pkg.version;
897
+ } catch {
898
+ return void 0;
899
+ }
900
+ }
901
+ async function buildCapturedError(error, request, context, client, routeOptions) {
902
+ const config = client.getConfig();
903
+ const url = new URL(request.url);
904
+ const stackFrames = parseStackTrace(error.stack);
905
+ const firstAppFrame = getFirstAppFrame(stackFrames);
906
+ const capturedError = {
907
+ id: generateErrorId(),
908
+ name: error.name || "Error",
909
+ message: error.message,
910
+ stack: error.stack,
911
+ stackFrames,
912
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
913
+ route: extractRoute(request),
914
+ method: request.method,
915
+ statusCode: routeOptions?.statusCode ?? 500,
916
+ url: request.url,
917
+ environment: config.environment,
918
+ projectId: config.projectId,
919
+ sdkVersion: SDK_VERSION2,
920
+ nodeVersion: getNodeVersion(),
921
+ nextVersion: getNextVersion()
922
+ };
923
+ if (context?.params && Object.keys(context.params).length > 0) {
924
+ capturedError.routeParams = context.params;
925
+ }
926
+ if (config.captureQueryParams && url.searchParams.toString()) {
927
+ capturedError.queryParams = sanitizeQueryParams(url, client);
928
+ }
929
+ if (config.captureHeaders) {
930
+ capturedError.requestHeaders = sanitizeHeaders(request.headers, client);
931
+ }
932
+ if (config.captureRequestBody && hasBody(request.method)) {
933
+ const bodyResult = await safeParseBody(request, config.maxBodySize, client);
934
+ if (bodyResult) {
935
+ capturedError.requestBody = bodyResult.body;
936
+ if (bodyResult.truncated) {
937
+ capturedError.metadata = {
938
+ ...capturedError.metadata,
939
+ bodyTruncated: true
940
+ };
941
+ }
942
+ }
943
+ }
944
+ if (firstAppFrame) {
945
+ capturedError.metadata = {
946
+ ...capturedError.metadata,
947
+ sourceLocation: {
948
+ file: firstAppFrame.file,
949
+ line: firstAppFrame.line,
950
+ column: firstAppFrame.column,
951
+ function: firstAppFrame.function
952
+ }
953
+ };
954
+ }
955
+ if (routeOptions?.metadata) {
956
+ capturedError.metadata = {
957
+ ...capturedError.metadata,
958
+ ...routeOptions.metadata
959
+ };
960
+ }
961
+ return capturedError;
962
+ }
963
+ function hasBody(method) {
964
+ return ["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase());
965
+ }
966
+ function withErrorCapture(handler, config, routeOptions) {
967
+ if (config && !ErrorCaptureClient.isInitialized()) {
968
+ ErrorCaptureClient.init(config);
969
+ }
970
+ return async (request, context) => {
971
+ const client = ErrorCaptureClient.getInstance();
972
+ try {
973
+ const response = await handler(request, context);
974
+ return response;
975
+ } catch (error) {
976
+ const err = error instanceof Error ? error : new Error(String(error));
977
+ if (client) {
978
+ const clientConfig = client.getConfig();
979
+ if (clientConfig.shouldCapture && !clientConfig.shouldCapture(err, request)) {
980
+ throw error;
981
+ }
982
+ if (routeOptions?.shouldCapture && !routeOptions.shouldCapture(err)) {
983
+ throw error;
984
+ }
985
+ buildCapturedError(err, request, context, client, routeOptions).then((capturedError) => {
986
+ return client.reportError(capturedError);
987
+ }).catch(() => {
988
+ });
989
+ }
990
+ throw error;
991
+ }
992
+ };
993
+ }
994
+ var withBugStack = withErrorCapture;
995
+
996
+ export { BugStackClient, ErrorCaptureClient, withBugStack, withErrorCapture };
997
+ //# sourceMappingURL=index.mjs.map
998
+ //# sourceMappingURL=index.mjs.map