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