bugstack-sdk 1.0.0 → 2.0.1

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